add Form renderer and fixed Newsletter saving issue

This commit is contained in:
Jonathan Labreuille 2015-10-30 18:12:07 +01:00
parent e24f8c9653
commit 907fe585de
20 changed files with 1346 additions and 99 deletions

View File

@ -87,8 +87,8 @@ class Menu {
function registered_pages() {
global $_registered_pages;
$pages = array(
//'mailpoet-form-editor' => 'formEditor',
'mailpoet-newsletter-editor' => array($this, 'newletterForm')
'mailpoet-form-editor' => array($this, 'formEditor'),
'mailpoet-newsletter-editor' => array($this, 'newletterEditor')
);
foreach($pages as $menu_slug => $callback) {
$hookname = get_plugin_page_hookname($menu_slug, null);
@ -193,11 +193,17 @@ class Menu {
echo $this->renderer->render('newsletters.html', $data);
}
function newletterForm() {
function newletterEditor() {
$data = array();
wp_enqueue_media();
wp_enqueue_script('tinymce-wplink', includes_url('js/tinymce/plugins/wplink/plugin.js'));
wp_enqueue_style('editor', includes_url('css/editor.css'));
echo $this->renderer->render('newsletter/form.html', $data);
}
function formEditor() {
$data = array();
$data['segments'] = Segment::findArray();
echo $this->renderer->render('form/editor.html', $data);
}
}

100
lib/Form/Block/base.php Normal file
View File

@ -0,0 +1,100 @@
<?php
namespace MailPoet\Form\Block;
abstract class Base {
protected static function getInputValidation($block) {
return 'data-validation-engine="'.static::getInputValidationRules($block).'"';
}
protected static function getInputValidationRules($block) {
$rules = array();
if($block['field'] === 'email') {
$rules[] = 'required';
$rules[] = 'custom[email]';
}
if($block['field'] === 'list') {
$rules[] = 'required';
}
if(isset($block['params']['required'])
&& (bool)$block['params']['required'] === true) {
$rules[] = 'required';
}
if(isset($block['params']['validate'])) {
if(is_array($block['params']['validate'])) {
// handle multiple validation rules
foreach($block['params']['validate'] as $rule) {
$rules[] = 'custom['.$rule.']';
}
} else if(strlen(trim($block['params']['validate'])) > 0) {
// handle single validation rule
$rules[] = 'custom['.$block['params']['validate'].']';
}
}
// generate string if there is at least one rule to validate against
if(empty($rules)) {
return '';
} else {
// make sure rules are not duplicated
$rules = array_unique($rules);
return 'validate['.join(',', $rules).']';
}
}
protected static function renderLabel($block) {
$html = '';
// if the label is displayed as a placeholder, we don't display a label outside
if(isset($block['params']['label_within'])
&& $block['params']['label_within']) {
return $html;
}
if(isset($block['params']['label'])
&& strlen(trim($block['params']['label'])) > 0) {
$html .= '<label class="mailpoet_'.$block['type'].'_label">'.$block['params']['label'];
if(isset($block['params']['required']) && $block['params']['required']) {
$html .= ' <span class="mailpoet_required">*</span>';
}
$html .= '</label>';
}
return $html;
}
protected static function renderInputPlaceholder($block) {
$html = '';
// if the label is displayed as a placeholder,
if(isset($block['params']['label_within']) && $block['params']['label_within']) {
// display only label
$html .= ' placeholder="';
$html .= static::getFieldLabel($block);
// add an asterisk if it's a required field
if(isset($block['params']['required']) && $block['params']['required']) {
$html .= ' *';
}
$html .= '" ';
}
return $html;
}
// return field name depending on block data
protected static function getFieldName($block = array()) {
return $block['field'];
}
protected static function getFieldLabel($block = array()) {
return (isset($block['params']['label'])
&& strlen(trim($block['params']['label'])) > 0)
? trim($block['params']['label']) : '';
}
protected static function getFieldValue($block = array()) {
return (isset($block['params']['value'])
&& strlen(trim($block['params']['value'])) > 0)
? trim($block['params']['value']) : '';
}
}

View File

@ -0,0 +1,43 @@
<?php
namespace MailPoet\Form\Block;
class Checkbox extends Base {
static function render($block) {
$html = '';
$field_name = static::getFieldName($block);
$field_validation = static::getInputValidation($block);
// TODO: check if it still makes sense
// create hidden default value
// $html .= '<input type="hidden"name="'.$field_name.'" value="0" '.static::getInputValidation($block).'/>';
$html .= '<p class="mailpoet_paragraph">';
$html .= static::renderLabel($block);
foreach($block['params']['values'] as $option) {
$html .= '<label class="mailpoet_checkbox_label">';
$html .= '<input type="checkbox" class="mailpoet_checkbox" ';
$html .= 'name="'.$field_name.'" ';
$html .= 'value="1" ';
$html .= (isset($option['is_checked']) && $option['is_checked'])
? 'checked="checked"' : '';
$html .= $field_validation;
$html .= ' />'.$option['value'];
$html .= '</label>';
}
$html .= '</p>';
return $html;
}
}

158
lib/Form/Block/date.php Normal file
View File

@ -0,0 +1,158 @@
<?php
namespace MailPoet\Form\Block;
class Date extends Base {
static function render($block) {
$html = '';
$html .= '<p class="mailpoet_paragraph">';
$html .= static::renderLabel($block);
$html .= static::renderDateSelect($block);
$html .= '</p>';
return $html;
}
private static function renderDateSelect($block = array()) {
$html = '';
$field_name = static::getFieldName($block);
$field_validation = static::getInputValidation($block);
$date_formats = static::getDateFormats();
// automatically select first date format
$date_format = $date_formats[$block['params']['date_type']][0];
// set date format if specified
if(isset($block['params']['date_format'])
&& strlen(trim($block['params']['date_format'])) > 0) {
$date_format = $block['params']['date_format'];
}
// generate an array of selectors based on date format
$date_selectors = explode('/', $date_format);
foreach($date_selectors as $date_selector) {
if($date_selector === 'dd') {
$html .= '<select class="mailpoet_date_day" ';
$html .= 'name="'.$field_name.'[day]" placeholder="'.__('Day').'">';
$html .= static::getDays($block);
$html .= '</select>';
} else if($date_selector === 'mm') {
$html .= '<select class="mailpoet_date_month" ';
$html .= 'name="'.$field_name.'[month]" placeholder="'.__('Month').'">';
$html .= static::getMonths($block);
$html .= '</select>';
} else if($date_selector === 'yyyy') {
$html .= '<select class="mailpoet_date_year" ';
$html .= 'name="'.$field_name.'[year]" placeholder="'.__('Year').'">';
$html .= static::getYears($block);
$html .= '</select>';
}
}
return $html;
}
static function getDateTypes() {
return array(
'year_month_day' => __('Year, month, day'),
'year_month' => __('Year, month'),
'month' => __('Month (January, February,...)'),
'year' => __('Year')
);
}
static function getDateFormats() {
return array(
'year_month_day' => array('mm/dd/yyyy', 'dd/mm/yyyy', 'yyyy/mm/dd'),
'year_month' => array('mm/yyyy', 'yyyy/mm'),
'year' => array('yyyy'),
'month' => array('mm')
);
}
static function getMonthNames() {
return array(__('January'), __('February'), __('March'), __('April'),
__('May'), __('June'), __('July'), __('August'), __('September'),
__('October'), __('November'), __('December')
);
}
static function getMonths($block = array()) {
$defaults = array(
'selected' => null
);
// is default today
if(isset($block['params']['is_default_today'])
&& (bool)$block['params']['is_default_today'] === true) {
$defaults['selected'] = (int)strftime('%m');
}
// merge block with defaults
$block = array_merge($defaults, $block);
$month_names = static::getMonthNames();
$html = '';
for($i = 1; $i < 13; $i++) {
$is_selected = ($i === $block['selected']) ? 'selected="selected"' : '';
$html .= '<option value="'.$i.'" '.$is_selected.'>';
$html .= $month_names[$i - 1];
$html .= '</option>';
}
return $html;
}
static function getYears($block = array()) {
$defaults = array(
'selected' => null,
'from' => (int)strftime('%Y') - 100,
'to' => (int)strftime('%Y')
);
// is default today
if(isset($block['params']['is_default_today'])
&& (bool)$block['params']['is_default_today'] === true) {
$defaults['selected'] = (int)strftime('%Y');
}
// merge block with defaults
$block = array_merge($defaults, $block);
$html = '';
// return years as an array
for($i = (int)$block['to']; $i > (int)($block['from'] - 1); $i--) {
$is_selected = ($i === $block['selected']) ? 'selected="selected"' : '';
$html .= '<option value="'.$i.'" '.$is_selected.'>'.$i.'</option>';
}
return $html;
}
static function getDays($block = array()) {
$defaults = array(
'selected' => null
);
// is default today
if(isset($block['params']['is_default_today'])
&& (bool)$block['params']['is_default_today'] === true) {
$defaults['selected'] = (int)strftime('%d');
}
// merge block with defaults
$block = array_merge($defaults, $block);
$html = '';
// return days as an array
for($i = 1; $i < 32; $i++) {
$is_selected = ($i === $block['selected']) ? 'selected="selected"' : '';
$html .= '<option value="'.$i.'" '.$is_selected.'>'.$i.'</option>';
}
return $html;
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace MailPoet\Form\Block;
class Divider {
static function render() {
return '<hr class="mailpoet_divider" />';
}
}

23
lib/Form/Block/html.php Normal file
View File

@ -0,0 +1,23 @@
<?php
namespace MailPoet\Form\Block;
class Html {
static function render($block) {
$html = '';
if(isset($block['params']['text']) && $block['params']['text']) {
$text = html_entity_decode($block['params']['text'], ENT_QUOTES);
}
if(isset($block['params']['nl2br']) && $block['params']['nl2br']) {
$text = nl2br($text);
}
$html .= '<p class="mailpoet_paragraph">';
$html .= $text;
$html .= '</p>';
return $html;
}
}

31
lib/Form/Block/input.php Normal file
View File

@ -0,0 +1,31 @@
<?php
namespace MailPoet\Form\Block;
class Input extends Base {
static function render($block) {
$html = '';
$html .= '<p class="mailpoet_paragraph">';
$html .= static::renderLabel($block);
$html .= '<input type="text" class="mailpoet_input" ';
$html .= 'name="'.static::getFieldName($block).'" ';
$html .= 'title="'.static::getFieldLabel($block).'" ';
$html .= 'value="'.static::getFieldValue($block).'" ';
$html .= static::renderInputPlaceholder($block);
$html .= static::getInputValidation($block);
$html .= '/>';
$html .= '</p>';
return $html;
}
}

37
lib/Form/Block/lists.php Normal file
View File

@ -0,0 +1,37 @@
<?php
namespace MailPoet\Form\Block;
class Lists extends Base {
static function render($block) {
$html = '';
$field_name = static::getFieldName($block);
$field_validation = static::getInputValidation($block);
$html .= '<p class="mailpoet_paragraph">';
$html .= static::renderLabel($block);
if(!empty($block['params']['values'])) {
// display values
foreach($block['params']['values'] as $list) {
if(!isset($list['id']) || !isset($list['name'])) continue;
$is_checked = (isset($list['is_checked']) && $list['is_checked']) ? 'checked="checked"' : '';
$html .= '<label class="mailpoet_checkbox_label">';
$html .= '<input type="checkbox" class="mailpoet_checkbox" ';
$html .= 'name="'.$field_name.'" ';
$html .= 'value="'.$list['id'].'" '.$is_checked;
$html .= $field_validation;
$html .= ' />'.$list['name'];
$html .= '</label>';
}
}
$html .= '</p>';
return $html;
}
}

42
lib/Form/Block/radio.php Normal file
View File

@ -0,0 +1,42 @@
<?php
namespace MailPoet\Form\Block;
class Radio extends Base {
static function render($block) {
$html = '';
$field_name = static::getFieldName($block);
$field_validation = static::getInputValidation($block);
// TODO: check if it still makes sense
// create hidden default value
// $html .= '<input type="hidden"name="'.$field_name.'" value="0" '.static::getInputValidation($block).'/>';
$html .= '<p class="mailpoet_paragraph">';
$html .= static::renderLabel($block);
foreach($block['params']['values'] as $option) {
$html .= '<label class="mailpoet_radio_label">';
$html .= '<input type="radio" class="mailpoet_radio" ';
$html .= 'name="'.$field_name.'" ';
$html .= 'value="'.$option['value'].'" ';
$html .= (isset($option['is_checked']) && $option['is_checked'])
? 'checked="checked"' : '';
$html .= $field_validation;
$html .= ' />'.$option['value'];
$html .= '</label>';
}
$html .= '</p>';
return $html;
}
}

36
lib/Form/Block/select.php Normal file
View File

@ -0,0 +1,36 @@
<?php
namespace MailPoet\Form\Block;
class Select extends Base {
static function render($block) {
$html = '';
$field_name = static::getFieldName($block);
$field_validation = static::getInputValidation($block);
$html .= '<p class="mailpoet_paragraph">';
$html .= static::renderLabel($block);
$html .= '<select class="mailpoet_select" name="'.$field_name.'">';
if(isset($block['params']['label_within'])
&& $block['params']['label_within']) {
$html .= '<option value="">'.static::getFieldLabel($block).'</option>';
}
foreach($block['params']['values'] as $option) {
$is_selected = (isset($option['is_checked']) && $option['is_checked'])
? 'selected="selected"' : '';
$html .= '<option value="'.$option['value'].'" '.$is_selected.'>';
$html .= $option['value'];
$html .= '</option>';
}
$html .= '</select>';
$html .= '</p>';
return $html;
}
}

17
lib/Form/Block/submit.php Normal file
View File

@ -0,0 +1,17 @@
<?php
namespace MailPoet\Form\Block;
class Submit extends Base {
static function render($block) {
$html = '';
$html .= '<input class="mailpoet_submit" type="submit" ';
$html .= 'value="'.static::getFieldLabel($block).'" ';
$html .= '/>';
return $html;
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace MailPoet\Form\Block;
class Textarea extends Base {
static function render($block) {
$html = '';
$html .= '<p class="mailpoet_paragraph">';
$html .= static::renderLabel($block);
$lines = (isset($block['params']['lines']) ? (int)$block['params']['lines'] : 1);
$html .= '<textarea class="mailpoet_textarea" rows="'.$lines.'" ';
$html .= 'name="'.static::getFieldName($block).'"';
$html .= static::renderInputPlaceholder($block);
$html .= static::getInputValidation($block);
$html .= '></textarea>';
$html .= '</p>';
return $html;
}
}

97
lib/Form/Renderer.php Normal file
View File

@ -0,0 +1,97 @@
<?php
namespace MailPoet\Form;
use MailPoet\Form\Block;
use MailPoet\Form\Util;
if(!defined('ABSPATH')) exit;
class Renderer {
// public: rendering method
static function render($form = array()) {
$html = static::renderStyles($form);
$html .= static::renderHTML($form);
return $html;
}
static function renderStyles($form = array()) {
$html = '<style type="text/css">';
$html .= static::getStyles($form);
$html .= '</style>';
return $html;
}
static function renderHTML($form = array()) {
if(isset($form['data']['body']) && !empty($form['data']['body'])) {
// render blocks
return static::renderBlocks($form['data']['body']);
}
return '';
}
static function getStyles($form = array()) {
if(isset($form['data']['styles'])
&& strlen(trim($form['data']['styles'])) > 0) {
return strip_tags($form['data']['styles']);
} else {
return Util\Styles::getDefaults();
}
}
// private: rendering methods
private static function renderBlocks($blocks = array()) {
$html = '';
foreach ($blocks as $key => $block) {
$html .= static::renderBlock($block)."\n";
}
return $html;
}
private static function renderBlock($block = array()) {
$html = '';
switch ($block['type']) {
case 'html':
$html .= Block\Html::render($block);
break;
case 'divider':
$html .= Block\Divider::render();
break;
case 'checkbox':
$html .= Block\Checkbox::render($block);
break;
case 'radio':
$html .= Block\Radio::render($block);
break;
case 'list':
$html .= Block\Lists::render($block);
break;
case 'date':
$html .= Block\Date::render($block);
break;
case 'select':
$html .= Block\Select::render($block);
break;
case 'input':
$html .= Block\Input::render($block);
break;
case 'textarea':
$html .= Block\Textarea::render($block);
break;
case 'submit':
$html .= Block\Submit::render($block);
break;
}
return $html;
}
}

91
lib/Form/Util/export.php Normal file
View File

@ -0,0 +1,91 @@
<?php
namespace MailPoet\Form\Util;
use MailPoet\Form\Widget;
class Export {
static function getAll($form = null) {
return array(
'html' => static::get('html', $form),
'php' => static::get('php', $form),
'iframe' => static::get('iframe', $form),
'shortcode' => static::get('shortcode', $form),
);
}
static function get($type = 'html', $form = null) {
switch($type) {
case 'iframe':
// generate url to load iframe's content
$iframe_url = add_query_arg(array(
'mailpoet_page' => 'mailpoet_form_iframe',
'mailpoet_form' => $form['form']
), site_url());
// generate iframe
return '<iframe '.
'width="100%" '.
'scrolling="no" '.
'frameborder="0" '.
'src="'.$iframe_url.'" '.
'class="mailpoet_form_iframe" '.
'vspace="0" '.
'tabindex="0" '.
//'style="position: static; top: 0pt; margin: 0px; border-style: none; height: 330px; left: 0pt; visibility: visible;" '. // TODO: need to find a solution for Height.
'marginwidth="0" '.
'marginheight="0" '.
'hspace="0" '.
'allowtransparency="true"></iframe>';
break;
case 'php':
$output = array(
'$form_widget = new \MailPoet\Form\Widget();',
'echo $form_widget->widget(array(\'form\' => '.(int)$form['form'].', \'form_type\' => \'php\'));'
);
return join("\n", $output);
break;
case 'html':
// TODO: get locale setting in order to load translations
$wp_locale = \get_locale();
$output = array();
$output[] = '<!-- BEGIN Scripts : you should place them in the header of your theme -->';
// jQuery
$output[] = '<script type="text/javascript" src="'.includes_url().'js/jquery/jquery.js'.'?mpv='.MAILPOET_VERSION.'"></script>';
// (JS) form validation
$output[] = '<script type="text/javascript" src="'.plugins_url('wysija-newsletters/'.'lib/jquery.validationEngine.js?mpv='.MAILPOET_VERSION).'"></script>';
$output[] = '<script type="text/javascript" src="'.plugins_url('wysija-newsletters/'.'lib/jquery.validationEngine-en.js?mpv='.MAILPOET_VERSION).'"></script>';
// (CSS) form validation styles
$output[] = '<link rel="stylesheet" type="text/css" href="'.plugins_url('wysija-newsletters/'.'lib/validationEngine.jquery.css?mpv='.MAILPOET_VERSION).'">';
// (JS) form submission
$output[] = '<script type="text/javascript" src="'.plugins_url('wysija-newsletters/'.'www/mailpoet_form_subscribe.js?mpv='.MAILPOET_VERSION).'"></script>';
// (JS) variables...
$output[] = '<script type="text/javascript">';
$output[] = ' var MailPoetData = MailPoetData || {';
$output[] = ' is_rtl: '.((int)is_rtl()).",";
$output[] = ' ajax_url: "'.admin_url('admin-ajax.php').'"';
$output[] = ' };';
$output[] = '</script>';
$output[] = '<!--END Scripts-->';
$form_widget = new Widget();
$output[] = $form_widget->widget(array(
'form' => (int)$form['form'],
'form_type' => 'php'
));
return join("\n", $output);
break;
case 'shortcode':
return '[mailpoet_form id="'.(int)$form['form'].'"]';
break;
}
}
}

47
lib/Form/Util/styles.php Normal file
View File

@ -0,0 +1,47 @@
<?php
namespace MailPoet\Form\Util;
class Styles {
static function getDefaults() {
return <<<EOL
/* form */
.mailpoet_form {
}
/* paragraphs (label + input) */
.mailpoet_paragraph {
}
/* labels */
.mailpoet_input_label,
.mailpoet_textarea_label,
.mailpoet_select_label,
.mailpoet_radio_label,
.mailpoet_list_label,
.mailpoet_checkbox_label,
.mailpoet_date_label {
display:block;
}
/* inputs */
.mailpoet_input,
.mailpoet_textarea,
.mailpoet_select,
.mailpoet_radio,
.mailpoet_checkbox,
.mailpoet_date {
display:block;
}
.mailpoet_validate_success {
color:#468847;
}
.mailpoet_validate_error {
color:#B94A48;
}
EOL;
}
}

View File

@ -5,116 +5,598 @@ if(!defined('ABSPATH')) exit;
class Widget extends \WP_Widget {
function __construct() {
function __construct () {
return parent::__construct(
'mailpoet_form',
__('MailPoet Subscription Form'),
__("MailPoet Subscription Form"),
array(
'title' => __('Newsletter subscription form')
'title' => __("Newsletter subscription form"),
)
);
}
public function update($new_instance, $old_instance) {
/**
* Save the new widget's title.
*/
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['form'] = (int)$new_instance['form'];
return $instance;
}
/**
* Output the widget's option form.
*/
public function form($instance) {
$instance = wp_parse_args(
(array)$instance,
array(
'title' => __('Subscribe to our Newsletter')
'title' => __("Subscribe to our Newsletter")
)
);
// set title
$title = isset($instance['title']) ? strip_tags($instance['title']) : '';
$output = '';
// set form
$selected_form = isset($instance['form']) ? (int)($instance['form']) : 0;
$output .= '<p>';
$output .= ' <label for="'.$this->get_field_id('title').'">';
$output .= __('Title:' );
$output .= ' </label>';
$output .= ' <input type="text" class="widefat"';
$output .= ' id="'.$this->get_field_id('title').'"';
$output .= ' name="'.$this->get_field_name('title').'"';
$output .= ' value="'.esc_attr($title).'"';
$output .= ' />';
$output .= '</p>';
$output .= '<p>';
$output .= ' <a href="javascript:;" class="mailpoet_form_new">';
$output .= __('Create a new form');
$output .= ' </a>';
$output .= '</p>';
// get forms list
// TODO: update when ORM ready
// $forms = $mailpoet->forms()->select(array(
// 'filter' => array(
// 'form_deleted_at' => NULL
// )
// ));
$forms = array();
echo $output;
?><p>
<label for="<?php $this->get_field_id( 'title' ) ?>"><?php _e( 'Title:' ); ?></label>
<input
type="text"
class="widefat"
id="<?php echo $this->get_field_id('title') ?>"
name="<?php echo $this->get_field_name('title'); ?>"
value="<?php echo esc_attr($title); ?>"
/>
</p>
<p>
<select class="widefat" id="<?php echo $this->get_field_id('form') ?>" name="<?php echo $this->get_field_name('form'); ?>">
<?php
foreach ($forms as $form) {
$is_selected = ($selected_form === (int)$form['form']) ? 'selected="selected"' : '';
?>
<option value="<?php echo (int)$form['form']; ?>" <?php echo $is_selected; ?>><?php echo esc_html($form['form_name']); ?></option>
<?php } ?>
</select>
</p>
<p>
<a href="javascript:;" class="mailpoet_form_new"><?php _e("Create a new form"); ?></a>
</p>
<script type="text/javascript">
jQuery(function($) {
$(function() {
$('.mailpoet_form_new').on('click', function() {
mailpoet_post_wpi('form_new.php', {}, function(response) {
if(response.form !== undefined) {
window.location.href = "<?php echo admin_url('admin.php?page=mailpoet-forms&action=edit&form='); ?>"+response.form;
} else {
MailPoet.Notice.error(response.error);
}
});
});
});
});
</script>
<?php
}
/**
* Output the widget itself.
*/
function widget($args, $instance = null) {
extract($args);
if($instance === null) { $instance = $args; }
// turn $args into variables
extract($args);
if($instance === null) {
$instance = $args;
}
$title = apply_filters(
'widget_title',
$instance['title'],
empty($instance['title']) ? __( 'Newsletter' ) : $instance['title'],
$instance,
$this->id_base
);
$form_id = $this->id_base.'_'.$this->number;
$form_type = 'widget';
// get form
// TODO: fix when ORM is ready
// $form = $mailpoet->forms()->fetchById($instance['form']);
$form = null;
$output = '';
// if the form was not found, return nothing.
if($form === null) {
return '';
} else {
// init output
$output = '';
// before widget
$output .= (isset($before_widget) ? $before_widget : '');
// before widget
$output .= (isset($before_widget) ? $before_widget : '');
// title
$output .= $before_title.$title.$after_title;
if(isset($form['data'])) {
// title
$output .= (isset($before_title) ? $before_title : '');
$output .= (isset($title) ? $title : '');
$output .= (isset($after_title) ? $after_title : '');
// container
$output .= '<div class="mailpoet_form mailpoet_form_'.$form_type.'">';
// render form
$form_id = $this->id_base.'_'.$this->number;
if(isset($instance['form_type']) && in_array($instance['form_type'], array('html', 'php', 'iframe', 'shortcode'))) {
$form_type = $instance['form_type'];
} else {
$form_type = 'widget';
}
// styles
$styles = '.mailpoet_validate_success { color:#468847; }';
$styles .= '.mailpoet_validate_error { color:#B94A48; }';
$output .= '<style type="text/css">'.$styles.'</style>';
// form container
$output .= '<div class="mailpoet_form mailpoet_form_'.$form_type.'">';
$output .= '<form '.
'id="'.$form_id.'" '.
'method="post" '.
'action="'.admin_url('admin-post.php?action=mailpoet_form_subscribe').'" '.
'class="mailpoet_form mailpoet_form_'.$form_type.'" novalidate>';
// form styles
$output .= MailPoetFormRendering::renderStyles($form);
$output .= '<div class="mailpoet_message"></div>';
$output .= '<form id="'.$form_id.'" method="post" action="'.admin_url('admin-post.php?action=mailpoet_form_subscribe').'" class="mailpoet_form mailpoet_form_'.$form_type.'" novalidate>';
$output .= ' <p>';
$output .= ' <label>'.__('E-mail');
$output .= ' <input type="email" name="email"';
$output .= ' data-rule-required="true"';
$output .= ' data-rule-email="true"';
$output .= ' data-msg-required="'.__('Please enter your email address.').'"';
$output .= ' data-msg-email="'.__('Please enter a valid email address.').'"';
$output .= ' />';
$output .= ' </label>';
$output .= ' </p>';
if(isset($_GET['mailpoet_form']) && (int)$_GET['mailpoet_form'] === $form['form']) {
// form messages (success / error)
$output .= '<div class="mailpoet_message">';
// success message
if(isset($_GET['mailpoet_success'])) {
$output .= '<p class="mailpoet_validate_success">'.strip_tags(urldecode($_GET['mailpoet_success']), '<a><strong><em><br><p>').'</p>';
}
// error message
if(isset($_GET['mailpoet_error'])) {
$output .= '<p class="mailpoet_validate_error">'.strip_tags(urldecode($_GET['mailpoet_error']), '<a><strong><em><br><p>').'</p>';
}
$output .= '</div>';
} else {
$output .= '<div class="mailpoet_message"></div>';
}
$output .= ' <p>';
$output .= ' <label>';
$output .= ' <input type="submit" value="'.esc_attr('Subscribe!').'" />';
$output .= ' </label>';
$output .= ' </p>';
$output .= '<input type="hidden" name="form" value="'.$form['form'].'" />';
$output .= '</form>';
$output .= '</div>';
if(!isset($form['data']['settings']['lists_selected_by']) or (isset($form['data']['settings']['lists_selected_by']) && $form['data']['settings']['lists_selected_by'] !== 'user')) {
if(!empty($form['data']['settings']['lists'])) {
$output .= '<input type="hidden" name="lists" value="'.join(',', $form['data']['settings']['lists']).'" />';
}
}
$output .= MailPoetFormRendering::renderHTML($form);
$output .= '</form>';
// after widget
$output .= (isset($after_widget) ? $after_widget : '');
$output .= '</div>';
echo $output;
// after widget
$output .= (isset($after_widget) ? $after_widget : '');
}
// shortcode: subscribers count
/*$subscribers_count = mailpoet_subscribers_count();
$output = str_replace(
array('[mailpoet_subscribers_count]', '[total_subscribers]'),
array($subscribers_count, $subscribers_count),
$output
);*/
if($form_type === 'widget') {
echo $output;
} else {
return $output;
}
}
}
}
}
// mailpoet shortcodes
// form shortcode
add_shortcode('mailpoet_form', 'mailpoet_form_shortcode');
add_shortcode('wysija_form', 'mailpoet_form_shortcode');
function mailpoet_form_shortcode($params = array()) {
// IMPORTANT: this is to make sure MagicMember won't scan our form and find [user_list] as a code they should replace.
remove_shortcode('user_list');
if(isset($params['id']) && (int)$params['id'] > 0) {
$form_widget = new \MailPoet\Form\Widget();
return $form_widget->widget(array(
'form' => (int)$params['id'],
'form_type' => 'shortcode'
));
}
}
/*
// subscribers count shortcode
add_shortcode('mailpoet_subscribers_count', 'mailpoet_subscribers_count');
add_shortcode('wysija_subscribers_count', 'mailpoet_subscribers_count');
function mailpoet_subscribers_count() {
$mailpoet = new MailPoetWPI();
// return the count of subscribers (STATE_SUBSCRIBED)
$subscribers_count = $mailpoet->subscribers()->count(array(
'filter' => array(
'subscriber_state' => MailPoetSubscribers::STATE_SUBSCRIBED
)
));
return $subscribers_count;
}
add_action('wp_ajax_mailpoet_form_subscribe', 'mailpoet_form_subscribe');
add_action('wp_ajax_nopriv_mailpoet_form_subscribe', 'mailpoet_form_subscribe');
add_action('admin_post_nopriv_mailpoet_form_subscribe', 'mailpoet_form_subscribe');
add_action('admin_post_mailpoet_form_subscribe', 'mailpoet_form_subscribe');
add_action('init', 'mailpoet_form_subscribe');
// set the content filter to replace the shortcode
if(isset($_GET['mailpoet_page']) && strlen(trim($_GET['mailpoet_page'])) > 0) {
$mailpoet = new MailPoetWPI();
switch($_GET['mailpoet_page']) {
case 'mailpoet_form_iframe':
$form_id = (isset($_GET['mailpoet_form']) && (int)$_GET['mailpoet_form'] > 0) ? (int)$_GET['mailpoet_form'] : null;
$form = $mailpoet->forms()->fetchById($form_id);
if($form !== null) {
// render form
print MailPoetFormRendering::getExport('html', $form);
exit;
}
break;
default:
// add_filter('wp_title', 'mailpoet_meta_page_title'));
add_filter('the_title', 'mailpoet_page_title', 10, 2);
add_filter('the_content', 'mailpoet_page_content', 98, 1);
break;
}
}
function mailpoet_page_title($title = '', $id = null) {
$mailpoet = new MailPoetWPI();
// get signup confirmation page id
$page_id = $mailpoet->settings()->get('signup_confirmation_page');
// check if we're on the signup confirmation page
if((int)$page_id === (int)$id) {
global $post;
// disable comments
$post->comment_status = 'close';
// disable password
$post->post_password = '';
$subscriber = null;
// get subscriber key from url
$subscriber_digest = (isset($_GET['mailpoet_key']) && strlen(trim($_GET['mailpoet_key'])) === 32) ? trim($_GET['mailpoet_key']) : null;
if($subscriber_digest !== null) {
// get subscriber
// TODO: change select() to selectOne() once it's implemented
$subscribers = $mailpoet->subscribers()->select(array(
'filter' => array(
'subscriber_digest' => $subscriber_digest
),
'limit' => 1
));
if(!empty($subscribers)) {
$subscriber = array_shift($subscribers);
}
}
// check if we have a subscriber record
if($subscriber === null) {
return __('Your confirmation link expired, please subscribe again.');
} else {
// we have a subscriber, let's check its state
switch($subscriber['subscriber_state']) {
case MailPoetSubscribers::STATE_UNCONFIRMED:
case MailPoetSubscribers::STATE_UNSUBSCRIBED:
// set subscriber state as confirmed
$mailpoet->subscribers()->update(array(
'subscriber' => $subscriber['subscriber'],
'subscriber_state' => MailPoetSubscribers::STATE_SUBSCRIBED,
'subscriber_confirmed_at' => time()
));
return __("You've subscribed");
break;
case MailPoetSubscribers::STATE_SUBSCRIBED:
return __("You've already subscribed");
break;
}
}
} else {
return $title;
}
}
function mailpoet_page_content($content = '') {
if(strpos($content, '[mailpoet_page]') !== FALSE) {
$content = str_replace('[mailpoet_page]', '', $content);
}
return $content;
}
function mailpoet_signup_confirmation_email(array $subscriber, array $lists) {
$mailpoet = new MailPoetWPI();
$mailer = new MailPoetMailer($mailpoet->settings()->getAll());
// email subject & body
$email_subject = $mailpoet->settings()->get('signup_confirmation_email_subject');
$email_body = nl2br($mailpoet->settings()->get('signup_confirmation_email_body'));
// check for lists_to_confirm tag
if(strpos($email_body, '[lists_to_confirm]') !== FALSE) {
// gather all names from lists
$list_names = array_map(function($list) { return $list['list_name']; }, $lists);
// replace shortcode by list names in email's body
$email_body = str_replace('[lists_to_confirm]', join(', ', $list_names), $email_body);
}
// check for activation_link tags
if(strpos($email_body, '[activation_link]') !== FALSE && strpos($email_body, '[/activation_link]') !== FALSE) {
// get confirmation page id
$confirmation_page_id = $mailpoet->settings()->get('signup_confirmation_page');
// generate confirmation link
$confirmation_link = add_query_arg(array(
'mailpoet_key' => $subscriber['subscriber_digest']
), get_permalink($confirmation_page_id));
// we have both tags
$email_body = str_replace(
array('[activation_link]', '[/activation_link]'),
array('<a href="'.$confirmation_link.'">', '</a>'),
$email_body
);
} else {
// no activation link tags detected
// TODO...
}
// send confirmation email
return $mailer->send(array(
'from_email' => $mailpoet->settings()->get('signup_confirmation_from_email'),
'from_name' => $mailpoet->settings()->get('signup_confirmation_from_name'),
'reply_email' => $mailpoet->settings()->get('signup_confirmation_reply_email'),
'reply_name' => $mailpoet->settings()->get('signup_confirmation_reply_name'),
'subject' => $email_subject,
'html' => $email_body,
'text' => '',
'to_email' => $subscriber['subscriber_email'],
'to_name' => $subscriber['subscriber_email'],
));
}
function mailpoet_form_subscribe() {
// check to see if we're in an ajax request or post request
$doing_ajax = (bool)(defined('DOING_AJAX') && DOING_AJAX);
if(isset($_GET['action']) && $_GET['action'] === 'mailpoet_form_subscribe') {
// MailPoetWPI instance
$mailpoet = new MailPoetWPI();
// input data
$data = array();
// output errors
$errors = array();
// get posted data
// ajax data
$data = json_decode(file_get_contents('php://input'), true);
// -or- post data
if($data === NULL && !empty($_POST)) { $data = $_POST; }
// define null subscriber
$subscriber = null;
// check if email is valid
if(MailPoetMailer::isEmailAddress($data['email']) === false) {
// email invalid
$errors[] = __('Invalid email address.');
} else {
// search for subscriber in database
$subscribers = $mailpoet->subscribers()->select(array(
'filter' => array(
'subscriber_email' => $data['email']
),
'offset' => 0,
'limit' => 1
));
// check if we have any subscriber that matches
if(count($subscribers) > 0) {
// use existing subscriber
$subscriber = $subscribers[0];
}
// is signup confirmation enabled?
$needs_confirmation = (bool)$mailpoet->settings()->get('signup_confirmation');
if($subscriber === null) {
// create new subscriber
$subscriber = array(
'subscriber_email' => $data['email'],
'subscriber_firstname' => (isset($data['subscriber_firstname'])) ? $data['subscriber_firstname'] : '',
'subscriber_lastname' => (isset($data['subscriber_lastname'])) ? $data['subscriber_lastname'] : '',
'subscriber_state' => ($needs_confirmation === true) ? MailPoetSubscribers::STATE_UNCONFIRMED : MailPoetSubscribers::STATE_SUBSCRIBED,
'subscriber_created_at' => time()
);
// set custom fields
$meta_fields = $mailpoet->getOption('mailpoet_subscriber_meta', array());
if(!empty($meta_fields)) {
// loop through data to see if any meta field has been passed
foreach($meta_fields as $field => $field_data) {
// check if it's a mandatory field
$is_required = (isset($field_data['params']['required']) && (bool)$field_data['params']['required'] === true);
if(array_key_exists($field, $data)) {
// check if it's a mandatory field
if($is_required === true && empty($data[$field])) {
// if it's missing, throw an error
$errors[] = sprintf(__('&quot;%s&quot; is required'), $field_data['name']);
} else {
// assign field to subscriber
$subscriber[$field] = $data[$field];
}
}
}
}
if(empty($errors)) {
// insert new subscriber
try {
$subscriber = $mailpoet->subscribers()->insert($subscriber);
} catch(Exception $e) {
$errors[] = $e->getMessage();
}
}
} else {
// restore deleted subscriber
if($subscriber['subscriber_deleted_at'] !== NULL) {
// reset subscriber state (depends whether signup confirmation is enabled)
if($needs_confirmation === true) {
$subscriber['subscriber_state'] = MailPoetSubscribers::STATE_UNCONFIRMED;
} else {
$subscriber['subscriber_state'] = MailPoetSubscribers::STATE_SUBSCRIBED;
}
try {
// update subscriber (reset deleted_at and state)
$mailpoet->subscribers()->update(array(
'subscriber' => $subscriber['subscriber'],
'subscriber_state' => $subscriber['subscriber_state'],
'subscriber_deleted_at' => NULL
));
} catch(Exception $e) {
$errors[] = __('An error occurred. Please try again later.');
}
}
}
}
// check if form id has been passed
if(isset($data['form']) && (int)$data['form'] > 0) {
// get form id
$form_id = (int)$data['form'];
// get form
$form = $mailpoet->forms()->fetchById($form_id);
if($form === null) {
$errors[] = __('This form does not exist. Please check your forms.');
} else {
// set subscriptions
if(empty($data['lists'])) {
$errors[] = __('You need to select a list');
} else {
// extract list ids
$list_ids = array_map('intval', explode(',', $data['lists']));
// get lists
$lists = $mailpoet->lists()->fetchByIds($list_ids);
// subscribe user to lists
$has_subscribed = $mailpoet->subscriptions()->addSubscriberToLists($subscriber, $lists, $form);
// if signup confirmation is enabled and the subscriber is unconfirmed
if( $needs_confirmation === true
&& $has_subscribed === true
&& !empty($lists)
&& !empty($subscriber['subscriber_digest'])
&& $subscriber['subscriber_state'] !== MailPoetSubscribers::STATE_SUBSCRIBED
) {
// resend confirmation email
$is_sent = mailpoet_signup_confirmation_email($subscriber, $lists);
// error message if the email could not be sent
if($is_sent === false) {
$errors[] = __('The signup confirmation email could not be sent. Please check your settings.');
}
}
}
}
// get success message to display after subscription
$form_settings = (isset($form['data']['settings']) ? $form['data']['settings'] : null);
if($subscriber !== null && empty($errors)) {
$success = true;
$message = $form_settings['success_message'];
} else {
$success = false;
$message = join('<br />', $errors);
}
if($form_settings !== null) {
// url params for non ajax requests
if($doing_ajax === false) {
// get referer
$referer = (wp_get_referer() !== false) ? wp_get_referer() : $_SERVER['HTTP_REFERER'];
// redirection parameters
$params = array(
'mailpoet_form' => (int)$data['form']
);
// handle success/error messages
if($success === false) {
$params['mailpoet_error'] = urlencode($message);
} else {
$params['mailpoet_success'] = urlencode($message);
}
}
switch ($form_settings['on_success']) {
case 'page':
// response depending on context
if($doing_ajax === true) {
echo json_encode(array(
'success' => $success,
'page' => get_permalink($form_settings['success_page']),
'message' => $message
));
} else {
$redirect_to = ($success === false) ? $referer : get_permalink($form_settings['success_page']);
wp_redirect(add_query_arg($params, $redirect_to));
}
break;
case 'message':
default:
// response depending on context
if($doing_ajax === true) {
echo json_encode(array(
'success' => $success,
'message' => $message
));
} else {
// redirect to previous page
wp_redirect(add_query_arg($params, $referer));
}
break;
}
}
}
exit();
}
}
*/

View File

@ -10,6 +10,13 @@ class Newsletter extends Model {
parent::__construct();
}
function save() {
if(is_string($this->deleted_at) && strlen(trim($this->deleted_at)) === 0) {
$this->set_expr('deleted_at', 'NULL');
}
return parent::save();
}
function segments() {
return $this->has_many_through(
__NAMESPACE__.'\Segment',
@ -131,15 +138,11 @@ class Newsletter extends Model {
$newsletter->set($data);
}
$saved = $newsletter->save();
if($saved === true) {
return $newsletter->id();
} else {
$errors = $newsletter->getValidationErrors();
if(!empty($errors)) {
return $errors;
}
try {
$newsletter->save();
return $newsletter;
} catch(Exception $e) {
return $newsletter->getValidationErrors();
}
return false;
}

View File

@ -54,29 +54,34 @@ class Newsletters {
unset($data['options']);
}
$newsletter_id = Newsletter::createOrUpdate($data);
$newsletter = Newsletter::createOrUpdate($data);
if($newsletter_id !== false) {
if($newsletter->id) {
if(!empty($segment_ids)) {
// remove previous relationships with segments
NewsletterSegment::where('newsletter_id', $newsletter_id)->deleteMany();
// create relationship with segments
NewsletterSegment::where('newsletter_id', $newsletter->id)
->deleteMany();
foreach($segment_ids as $segment_id) {
$relation = NewsletterSegment::create();
$relation->segment_id = $segment_id;
$relation->newsletter_id = $newsletter_id;
$relation->newsletter_id = $newsletter->id;
$relation->save();
}
}
if(!empty($options)) {
NewsletterOption::where('newsletter_id', $newsletter_id)->deletemany();
$optionFields = NewsletterOptionField::where('newsletter_type', $data['type'])->findArray();
NewsletterOption::where('newsletter_id', $newsletter->id)
->deleteMany();
$optionFields = NewsletterOptionField::where(
'newsletter_type',
$data['type']
)->findArray();
foreach($optionFields as $optionField) {
if(isset($options[$optionField['name']])) {
$relation = NewsletterOption::create();
$relation->newsletter_id = $newsletter_id;
$relation->newsletter_id = $newsletter->id;
$relation->option_field_id = $optionField['id'];
$relation->value = $options[$optionField['name']];
$relation->save();
@ -85,7 +90,7 @@ class Newsletters {
}
}
wp_send_json(($newsletter_id !== false));
wp_send_json(($newsletter->id !== false));
}
function delete($data = array()) {

View File

@ -2,7 +2,7 @@
<% block title %>
<h2 class="title">
<span id="mailpoet_form_name"><%= form.form_name %></span>
<span id="mailpoet_form_name"><%= form.name %></span>
<input id="mailpoet_form_name_input" type="text" value="" style="display:none;" />
<span>
<a id="mailpoet_form_edit_name" class="button" href="javascript:;"><%= __('Edit name' ) %></a>
@ -174,21 +174,10 @@
<%= javascript(
'lib/prototype.min.js',
'lib/select2.js',
'lib/scriptaculous.min.js',
'lib/codemirror/codemirror.js',
'lib/codemirror/syntax_php.js',
'lib/codemirror/syntax_css.js',
'lib/jquery.serializeObject.js',
'form_editor.js'
)%>
<%= stylesheet(
'lib/select2/select2.css',
'lib/codemirror/codemirror.css',
'lib/codemirror/theme_neo.css'
) %>
<script type="text/javascript">
jQuery(function($) {
function mailpoet_form_fields(data) {

View File

@ -78,6 +78,9 @@ config.push(_.extend({}, baseConfig, {
'forms/forms.jsx',
'settings/tabs.js'
],
form_editor: [
'select2'
],
newsletter_editor: [
'underscore',
'backbone',