Change line endings from DOS CRLF to Unix LF

This commit is contained in:
Tautvidas Sipavičius
2016-06-30 14:39:28 +03:00
parent 607395be6f
commit 0ac701eb20
15 changed files with 2211 additions and 2211 deletions

View File

@ -1,197 +1,197 @@
<?php <?php
namespace MailPoet\Config; namespace MailPoet\Config;
use MailPoet\Models; use MailPoet\Models;
use MailPoet\Cron\Supervisor; use MailPoet\Cron\Supervisor;
use MailPoet\Router; use MailPoet\Router;
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
require_once(ABSPATH . 'wp-admin/includes/plugin.php'); require_once(ABSPATH . 'wp-admin/includes/plugin.php');
class Initializer { class Initializer {
function __construct($params = array( function __construct($params = array(
'file' => '', 'file' => '',
'version' => '1.0.0' 'version' => '1.0.0'
)) { )) {
Env::init($params['file'], $params['version']); Env::init($params['file'], $params['version']);
} }
function init() { function init() {
$this->setupDB(); $this->setupDB();
register_activation_hook(Env::$file, array($this, 'runMigrator')); register_activation_hook(Env::$file, array($this, 'runMigrator'));
register_activation_hook(Env::$file, array($this, 'runPopulator')); register_activation_hook(Env::$file, array($this, 'runPopulator'));
add_action('plugins_loaded', array($this, 'setup')); add_action('plugins_loaded', array($this, 'setup'));
add_action('init', array($this, 'onInit')); add_action('init', array($this, 'onInit'));
add_action('widgets_init', array($this, 'setupWidget')); add_action('widgets_init', array($this, 'setupWidget'));
} }
function setup() { function setup() {
try { try {
$this->setupRenderer(); $this->setupRenderer();
$this->setupLocalizer(); $this->setupLocalizer();
$this->setupMenu(); $this->setupMenu();
$this->setupPermissions(); $this->setupPermissions();
$this->setupAnalytics(); $this->setupAnalytics();
$this->setupChangelog(); $this->setupChangelog();
$this->setupShortcodes(); $this->setupShortcodes();
$this->setupHooks(); $this->setupHooks();
$this->setupImages(); $this->setupImages();
$this->runQueueSupervisor(); $this->runQueueSupervisor();
} catch(\Exception $e) { } catch(\Exception $e) {
// if anything goes wrong during init // if anything goes wrong during init
// automatically deactivate the plugin // automatically deactivate the plugin
deactivate_plugins(Env::$file); deactivate_plugins(Env::$file);
} }
} }
function onInit() { function onInit() {
$this->setupRouter(); $this->setupRouter();
$this->setupPublicAPI(); $this->setupPublicAPI();
$this->setupPages(); $this->setupPages();
} }
function setupDB() { function setupDB() {
\ORM::configure(Env::$db_source_name); \ORM::configure(Env::$db_source_name);
\ORM::configure('username', Env::$db_username); \ORM::configure('username', Env::$db_username);
\ORM::configure('password', Env::$db_password); \ORM::configure('password', Env::$db_password);
\ORM::configure('logging', WP_DEBUG); \ORM::configure('logging', WP_DEBUG);
\ORM::configure('logger', function($query, $time) { \ORM::configure('logger', function($query, $time) {
// error_log("\n".$query."\n"); // error_log("\n".$query."\n");
}); });
\ORM::configure('driver_options', array( \ORM::configure('driver_options', array(
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
\PDO::MYSQL_ATTR_INIT_COMMAND => \PDO::MYSQL_ATTR_INIT_COMMAND =>
'SET TIME_ZONE = "' . Env::$db_timezone_offset. '"' 'SET TIME_ZONE = "' . Env::$db_timezone_offset. '"'
)); ));
$settings = Env::$db_prefix . 'settings'; $settings = Env::$db_prefix . 'settings';
$segments = Env::$db_prefix . 'segments'; $segments = Env::$db_prefix . 'segments';
$forms = Env::$db_prefix . 'forms'; $forms = Env::$db_prefix . 'forms';
$custom_fields = Env::$db_prefix . 'custom_fields'; $custom_fields = Env::$db_prefix . 'custom_fields';
$subscribers = Env::$db_prefix . 'subscribers'; $subscribers = Env::$db_prefix . 'subscribers';
$subscriber_segment = Env::$db_prefix . 'subscriber_segment'; $subscriber_segment = Env::$db_prefix . 'subscriber_segment';
$subscriber_custom_field = Env::$db_prefix . 'subscriber_custom_field'; $subscriber_custom_field = Env::$db_prefix . 'subscriber_custom_field';
$newsletter_segment = Env::$db_prefix . 'newsletter_segment'; $newsletter_segment = Env::$db_prefix . 'newsletter_segment';
$sending_queues = Env::$db_prefix . 'sending_queues'; $sending_queues = Env::$db_prefix . 'sending_queues';
$newsletters = Env::$db_prefix . 'newsletters'; $newsletters = Env::$db_prefix . 'newsletters';
$newsletter_templates = Env::$db_prefix . 'newsletter_templates'; $newsletter_templates = Env::$db_prefix . 'newsletter_templates';
$newsletter_option_fields = Env::$db_prefix . 'newsletter_option_fields'; $newsletter_option_fields = Env::$db_prefix . 'newsletter_option_fields';
$newsletter_option = Env::$db_prefix . 'newsletter_option'; $newsletter_option = Env::$db_prefix . 'newsletter_option';
$newsletter_links = Env::$db_prefix . 'newsletter_links'; $newsletter_links = Env::$db_prefix . 'newsletter_links';
$newsletter_posts = Env::$db_prefix . 'newsletter_posts'; $newsletter_posts = Env::$db_prefix . 'newsletter_posts';
$statistics_newsletters = Env::$db_prefix . 'statistics_newsletters'; $statistics_newsletters = Env::$db_prefix . 'statistics_newsletters';
$statistics_clicks = Env::$db_prefix . 'statistics_clicks'; $statistics_clicks = Env::$db_prefix . 'statistics_clicks';
$statistics_opens = Env::$db_prefix . 'statistics_opens'; $statistics_opens = Env::$db_prefix . 'statistics_opens';
$statistics_unsubscribes = Env::$db_prefix . 'statistics_unsubscribes'; $statistics_unsubscribes = Env::$db_prefix . 'statistics_unsubscribes';
$statistics_forms = Env::$db_prefix . 'statistics_forms'; $statistics_forms = Env::$db_prefix . 'statistics_forms';
define('MP_SETTINGS_TABLE', $settings); define('MP_SETTINGS_TABLE', $settings);
define('MP_SEGMENTS_TABLE', $segments); define('MP_SEGMENTS_TABLE', $segments);
define('MP_FORMS_TABLE', $forms); define('MP_FORMS_TABLE', $forms);
define('MP_CUSTOM_FIELDS_TABLE', $custom_fields); define('MP_CUSTOM_FIELDS_TABLE', $custom_fields);
define('MP_SUBSCRIBERS_TABLE', $subscribers); define('MP_SUBSCRIBERS_TABLE', $subscribers);
define('MP_SUBSCRIBER_SEGMENT_TABLE', $subscriber_segment); define('MP_SUBSCRIBER_SEGMENT_TABLE', $subscriber_segment);
define('MP_SUBSCRIBER_CUSTOM_FIELD_TABLE', $subscriber_custom_field); define('MP_SUBSCRIBER_CUSTOM_FIELD_TABLE', $subscriber_custom_field);
define('MP_SENDING_QUEUES_TABLE', $sending_queues); define('MP_SENDING_QUEUES_TABLE', $sending_queues);
define('MP_NEWSLETTERS_TABLE', $newsletters); define('MP_NEWSLETTERS_TABLE', $newsletters);
define('MP_NEWSLETTER_TEMPLATES_TABLE', $newsletter_templates); define('MP_NEWSLETTER_TEMPLATES_TABLE', $newsletter_templates);
define('MP_NEWSLETTER_SEGMENT_TABLE', $newsletter_segment); define('MP_NEWSLETTER_SEGMENT_TABLE', $newsletter_segment);
define('MP_NEWSLETTER_OPTION_FIELDS_TABLE', $newsletter_option_fields); define('MP_NEWSLETTER_OPTION_FIELDS_TABLE', $newsletter_option_fields);
define('MP_NEWSLETTER_LINKS_TABLE', $newsletter_links); define('MP_NEWSLETTER_LINKS_TABLE', $newsletter_links);
define('MP_NEWSLETTER_POSTS_TABLE', $newsletter_posts); define('MP_NEWSLETTER_POSTS_TABLE', $newsletter_posts);
define('MP_NEWSLETTER_OPTION_TABLE', $newsletter_option); define('MP_NEWSLETTER_OPTION_TABLE', $newsletter_option);
define('MP_STATISTICS_NEWSLETTERS_TABLE', $statistics_newsletters); define('MP_STATISTICS_NEWSLETTERS_TABLE', $statistics_newsletters);
define('MP_STATISTICS_CLICKS_TABLE', $statistics_clicks); define('MP_STATISTICS_CLICKS_TABLE', $statistics_clicks);
define('MP_STATISTICS_OPENS_TABLE', $statistics_opens); define('MP_STATISTICS_OPENS_TABLE', $statistics_opens);
define('MP_STATISTICS_UNSUBSCRIBES_TABLE', $statistics_unsubscribes); define('MP_STATISTICS_UNSUBSCRIBES_TABLE', $statistics_unsubscribes);
define('MP_STATISTICS_FORMS_TABLE', $statistics_forms); define('MP_STATISTICS_FORMS_TABLE', $statistics_forms);
} }
function runMigrator() { function runMigrator() {
$migrator = new Migrator(); $migrator = new Migrator();
$migrator->up(); $migrator->up();
} }
function runPopulator() { function runPopulator() {
$populator = new Populator(); $populator = new Populator();
$populator->up(); $populator->up();
} }
function setupRenderer() { function setupRenderer() {
$renderer = new Renderer(); $renderer = new Renderer();
$this->renderer = $renderer->init(); $this->renderer = $renderer->init();
} }
function setupLocalizer() { function setupLocalizer() {
$localizer = new Localizer($this->renderer); $localizer = new Localizer($this->renderer);
$localizer->init(); $localizer->init();
} }
function setupMenu() { function setupMenu() {
$menu = new Menu($this->renderer, Env::$assets_url); $menu = new Menu($this->renderer, Env::$assets_url);
$menu->init(); $menu->init();
} }
function setupRouter() { function setupRouter() {
$router = new Router\Router(); $router = new Router\Router();
$router->init(); $router->init();
} }
function setupWidget() { function setupWidget() {
$widget = new Widget($this->renderer); $widget = new Widget($this->renderer);
$widget->init(); $widget->init();
} }
function setupAnalytics() { function setupAnalytics() {
$widget = new Analytics(); $widget = new Analytics();
$widget->init(); $widget->init();
} }
function setupPermissions() { function setupPermissions() {
$permissions = new Permissions(); $permissions = new Permissions();
$permissions->init(); $permissions->init();
} }
function setupChangelog() { function setupChangelog() {
$changelog = new Changelog(); $changelog = new Changelog();
$changelog->init(); $changelog->init();
} }
function setupPages() { function setupPages() {
$pages = new \MailPoet\Settings\Pages(); $pages = new \MailPoet\Settings\Pages();
$pages->init(); $pages->init();
} }
function setupShortcodes() { function setupShortcodes() {
$shortcodes = new Shortcodes(); $shortcodes = new Shortcodes();
$shortcodes->init(); $shortcodes->init();
} }
function setupHooks() { function setupHooks() {
$hooks = new Hooks(); $hooks = new Hooks();
$hooks->init(); $hooks->init();
} }
function setupPublicAPI() { function setupPublicAPI() {
$publicAPI = new PublicAPI(); $publicAPI = new PublicAPI();
$publicAPI->init(); $publicAPI->init();
} }
function runQueueSupervisor() { function runQueueSupervisor() {
if(php_sapi_name() === 'cli') return; if(php_sapi_name() === 'cli') return;
try { try {
$supervisor = new Supervisor(); $supervisor = new Supervisor();
$supervisor->checkDaemon(); $supervisor->checkDaemon();
} catch(\Exception $e) { } catch(\Exception $e) {
// Prevent Daemon exceptions from breaking out and breaking UI // Prevent Daemon exceptions from breaking out and breaking UI
} }
} }
function setupImages() { function setupImages() {
add_image_size('mailpoet_newsletter_max', 1320); add_image_size('mailpoet_newsletter_max', 1320);
} }
} }

View File

@ -1,360 +1,360 @@
<?php <?php
namespace MailPoet\Config; namespace MailPoet\Config;
use MailPoet\Models\Subscriber; use MailPoet\Models\Subscriber;
use MailPoet\Models\Newsletter; use MailPoet\Models\Newsletter;
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
class Migrator { class Migrator {
function __construct() { function __construct() {
$this->prefix = Env::$db_prefix; $this->prefix = Env::$db_prefix;
$this->charset = Env::$db_charset; $this->charset = Env::$db_charset;
$this->models = array( $this->models = array(
'segments', 'segments',
'settings', 'settings',
'custom_fields', 'custom_fields',
'sending_queues', 'sending_queues',
'subscribers', 'subscribers',
'subscriber_segment', 'subscriber_segment',
'subscriber_custom_field', 'subscriber_custom_field',
'newsletters', 'newsletters',
'newsletter_templates', 'newsletter_templates',
'newsletter_option_fields', 'newsletter_option_fields',
'newsletter_option', 'newsletter_option',
'newsletter_segment', 'newsletter_segment',
'newsletter_links', 'newsletter_links',
'newsletter_posts', 'newsletter_posts',
'forms', 'forms',
'statistics_newsletters', 'statistics_newsletters',
'statistics_clicks', 'statistics_clicks',
'statistics_opens', 'statistics_opens',
'statistics_unsubscribes', 'statistics_unsubscribes',
'statistics_forms' 'statistics_forms'
); );
} }
function up() { function up() {
global $wpdb; global $wpdb;
$_this = $this; $_this = $this;
$migrate = function($model) use($_this) { $migrate = function($model) use($_this) {
dbDelta($_this->$model()); dbDelta($_this->$model());
}; };
array_map($migrate, $this->models); array_map($migrate, $this->models);
} }
function down() { function down() {
global $wpdb; global $wpdb;
$drop_table = function($model) use($wpdb) { $drop_table = function($model) use($wpdb) {
$table = $this->prefix . $model; $table = $this->prefix . $model;
$wpdb->query("DROP TABLE {$table}"); $wpdb->query("DROP TABLE {$table}");
}; };
array_map($drop_table, $this->models); array_map($drop_table, $this->models);
} }
function segments() { function segments() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'name varchar(90) NOT NULL,', 'name varchar(90) NOT NULL,',
'type varchar(90) NOT NULL DEFAULT "default",', 'type varchar(90) NOT NULL DEFAULT "default",',
'description varchar(250) NOT NULL DEFAULT "",', 'description varchar(250) NOT NULL DEFAULT "",',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'deleted_at TIMESTAMP NULL,', 'deleted_at TIMESTAMP NULL,',
'PRIMARY KEY (id),', 'PRIMARY KEY (id),',
'UNIQUE KEY name (name)' 'UNIQUE KEY name (name)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function settings() { function settings() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'name varchar(20) NOT NULL,', 'name varchar(20) NOT NULL,',
'value longtext,', 'value longtext,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id),', 'PRIMARY KEY (id),',
'UNIQUE KEY name (name)' 'UNIQUE KEY name (name)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function custom_fields() { function custom_fields() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'name varchar(90) NOT NULL,', 'name varchar(90) NOT NULL,',
'type varchar(90) NOT NULL,', 'type varchar(90) NOT NULL,',
'params longtext NOT NULL,', 'params longtext NOT NULL,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id),', 'PRIMARY KEY (id),',
'UNIQUE KEY name (name)' 'UNIQUE KEY name (name)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function sending_queues() { function sending_queues() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'newsletter_id mediumint(9) NOT NULL,', 'newsletter_id mediumint(9) NOT NULL,',
'newsletter_rendered_body longtext,', 'newsletter_rendered_body longtext,',
'newsletter_rendered_subject varchar(250) NULL DEFAULT NULL,', 'newsletter_rendered_subject varchar(250) NULL DEFAULT NULL,',
'subscribers longtext,', 'subscribers longtext,',
'status varchar(12) NULL DEFAULT NULL,', 'status varchar(12) NULL DEFAULT NULL,',
'priority mediumint(9) NOT NULL DEFAULT 0,', 'priority mediumint(9) NOT NULL DEFAULT 0,',
'count_total mediumint(9) NOT NULL DEFAULT 0,', 'count_total mediumint(9) NOT NULL DEFAULT 0,',
'count_processed mediumint(9) NOT NULL DEFAULT 0,', 'count_processed mediumint(9) NOT NULL DEFAULT 0,',
'count_to_process mediumint(9) NOT NULL DEFAULT 0,', 'count_to_process mediumint(9) NOT NULL DEFAULT 0,',
'count_failed mediumint(9) NOT NULL DEFAULT 0,', 'count_failed mediumint(9) NOT NULL DEFAULT 0,',
'scheduled_at TIMESTAMP NULL,', 'scheduled_at TIMESTAMP NULL,',
'processed_at TIMESTAMP NULL,', 'processed_at TIMESTAMP NULL,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'deleted_at TIMESTAMP NULL,', 'deleted_at TIMESTAMP NULL,',
'PRIMARY KEY (id)', 'PRIMARY KEY (id)',
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function subscribers() { function subscribers() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'wp_user_id bigint(20) NULL,', 'wp_user_id bigint(20) NULL,',
'first_name tinytext NOT NULL DEFAULT "",', 'first_name tinytext NOT NULL DEFAULT "",',
'last_name tinytext NOT NULL DEFAULT "",', 'last_name tinytext NOT NULL DEFAULT "",',
'email varchar(150) NOT NULL,', 'email varchar(150) NOT NULL,',
'status varchar(12) NOT NULL DEFAULT "' . Subscriber::STATUS_UNCONFIRMED . '",', 'status varchar(12) NOT NULL DEFAULT "' . Subscriber::STATUS_UNCONFIRMED . '",',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'deleted_at TIMESTAMP NULL,', 'deleted_at TIMESTAMP NULL,',
'PRIMARY KEY (id),', 'PRIMARY KEY (id),',
'UNIQUE KEY email (email)' 'UNIQUE KEY email (email)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function subscriber_segment() { function subscriber_segment() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'subscriber_id mediumint(9) NOT NULL,', 'subscriber_id mediumint(9) NOT NULL,',
'segment_id mediumint(9) NOT NULL,', 'segment_id mediumint(9) NOT NULL,',
'status varchar(12) NOT NULL DEFAULT "' . Subscriber::STATUS_SUBSCRIBED . '",', 'status varchar(12) NOT NULL DEFAULT "' . Subscriber::STATUS_SUBSCRIBED . '",',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id),', 'PRIMARY KEY (id),',
'UNIQUE KEY subscriber_segment (subscriber_id,segment_id)' 'UNIQUE KEY subscriber_segment (subscriber_id,segment_id)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function subscriber_custom_field() { function subscriber_custom_field() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'subscriber_id mediumint(9) NOT NULL,', 'subscriber_id mediumint(9) NOT NULL,',
'custom_field_id mediumint(9) NOT NULL,', 'custom_field_id mediumint(9) NOT NULL,',
'value varchar(255) NOT NULL DEFAULT "",', 'value varchar(255) NOT NULL DEFAULT "",',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id),', 'PRIMARY KEY (id),',
'UNIQUE KEY subscriber_id_custom_field_id (subscriber_id,custom_field_id)' 'UNIQUE KEY subscriber_id_custom_field_id (subscriber_id,custom_field_id)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function newsletters() { function newsletters() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'subject varchar(250) NOT NULL DEFAULT "",', 'subject varchar(250) NOT NULL DEFAULT "",',
'type varchar(20) NOT NULL DEFAULT "standard",', 'type varchar(20) NOT NULL DEFAULT "standard",',
'sender_address varchar(150) NOT NULL DEFAULT "",', 'sender_address varchar(150) NOT NULL DEFAULT "",',
'sender_name varchar(150) NOT NULL DEFAULT "",', 'sender_name varchar(150) NOT NULL DEFAULT "",',
'status varchar(20) NOT NULL DEFAULT "'.Newsletter::STATUS_DRAFT.'",', 'status varchar(20) NOT NULL DEFAULT "'.Newsletter::STATUS_DRAFT.'",',
'reply_to_address varchar(150) NOT NULL DEFAULT "",', 'reply_to_address varchar(150) NOT NULL DEFAULT "",',
'reply_to_name varchar(150) NOT NULL DEFAULT "",', 'reply_to_name varchar(150) NOT NULL DEFAULT "",',
'preheader varchar(250) NOT NULL DEFAULT "",', 'preheader varchar(250) NOT NULL DEFAULT "",',
'body longtext,', 'body longtext,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'deleted_at TIMESTAMP NULL,', 'deleted_at TIMESTAMP NULL,',
'PRIMARY KEY (id)' 'PRIMARY KEY (id)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function newsletter_templates() { function newsletter_templates() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'name varchar(250) NOT NULL,', 'name varchar(250) NOT NULL,',
'description varchar(250) NOT NULL,', 'description varchar(250) NOT NULL,',
'body LONGTEXT,', 'body LONGTEXT,',
'thumbnail LONGTEXT,', 'thumbnail LONGTEXT,',
'readonly TINYINT(1) DEFAULT 0,', 'readonly TINYINT(1) DEFAULT 0,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id)' 'PRIMARY KEY (id)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function newsletter_option_fields() { function newsletter_option_fields() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'name varchar(90) NOT NULL,', 'name varchar(90) NOT NULL,',
'newsletter_type varchar(90) NOT NULL,', 'newsletter_type varchar(90) NOT NULL,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id),', 'PRIMARY KEY (id),',
'UNIQUE KEY name_newsletter_type (newsletter_type,name)' 'UNIQUE KEY name_newsletter_type (newsletter_type,name)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function newsletter_option() { function newsletter_option() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'newsletter_id mediumint(9) NOT NULL,', 'newsletter_id mediumint(9) NOT NULL,',
'option_field_id mediumint(9) NOT NULL,', 'option_field_id mediumint(9) NOT NULL,',
'value varchar(255) NOT NULL DEFAULT "",', 'value varchar(255) NOT NULL DEFAULT "",',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id),', 'PRIMARY KEY (id),',
'UNIQUE KEY newsletter_id_option_field_id (newsletter_id,option_field_id)' 'UNIQUE KEY newsletter_id_option_field_id (newsletter_id,option_field_id)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function newsletter_segment() { function newsletter_segment() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'newsletter_id mediumint(9) NOT NULL,', 'newsletter_id mediumint(9) NOT NULL,',
'segment_id mediumint(9) NOT NULL,', 'segment_id mediumint(9) NOT NULL,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id),', 'PRIMARY KEY (id),',
'UNIQUE KEY newsletter_segment (newsletter_id,segment_id)' 'UNIQUE KEY newsletter_segment (newsletter_id,segment_id)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function newsletter_links() { function newsletter_links() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'newsletter_id mediumint(9) NOT NULL,', 'newsletter_id mediumint(9) NOT NULL,',
'queue_id mediumint(9) NOT NULL,', 'queue_id mediumint(9) NOT NULL,',
'url varchar(255) NOT NULL,', 'url varchar(255) NOT NULL,',
'hash varchar(20) NOT NULL,', 'hash varchar(20) NOT NULL,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id)', 'PRIMARY KEY (id)',
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function newsletter_posts() { function newsletter_posts() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'newsletter_id mediumint(9) NOT NULL,', 'newsletter_id mediumint(9) NOT NULL,',
'post_id mediumint(9) NOT NULL,', 'post_id mediumint(9) NOT NULL,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id)', 'PRIMARY KEY (id)',
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function forms() { function forms() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'name varchar(90) NOT NULL,', 'name varchar(90) NOT NULL,',
'body longtext,', 'body longtext,',
'settings longtext,', 'settings longtext,',
'styles longtext,', 'styles longtext,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'deleted_at TIMESTAMP NULL,', 'deleted_at TIMESTAMP NULL,',
'PRIMARY KEY (id)' 'PRIMARY KEY (id)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function statistics_newsletters() { function statistics_newsletters() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'newsletter_id mediumint(9) NOT NULL,', 'newsletter_id mediumint(9) NOT NULL,',
'subscriber_id mediumint(9) NOT NULL,', 'subscriber_id mediumint(9) NOT NULL,',
'queue_id mediumint(9) NOT NULL,', 'queue_id mediumint(9) NOT NULL,',
'sent_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'sent_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id)', 'PRIMARY KEY (id)',
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function statistics_clicks() { function statistics_clicks() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'newsletter_id mediumint(9) NOT NULL,', 'newsletter_id mediumint(9) NOT NULL,',
'subscriber_id mediumint(9) NOT NULL,', 'subscriber_id mediumint(9) NOT NULL,',
'queue_id mediumint(9) NOT NULL,', 'queue_id mediumint(9) NOT NULL,',
'link_id mediumint(9) NOT NULL,', 'link_id mediumint(9) NOT NULL,',
'count mediumint(9) NOT NULL,', 'count mediumint(9) NOT NULL,',
'created_at TIMESTAMP NULL,', 'created_at TIMESTAMP NULL,',
'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,', 'updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,',
'PRIMARY KEY (id)', 'PRIMARY KEY (id)',
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function statistics_opens() { function statistics_opens() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'newsletter_id mediumint(9) NOT NULL,', 'newsletter_id mediumint(9) NOT NULL,',
'subscriber_id mediumint(9) NOT NULL,', 'subscriber_id mediumint(9) NOT NULL,',
'queue_id mediumint(9) NOT NULL,', 'queue_id mediumint(9) NOT NULL,',
'created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,', 'created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,',
'PRIMARY KEY (id)', 'PRIMARY KEY (id)',
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function statistics_unsubscribes() { function statistics_unsubscribes() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'newsletter_id mediumint(9) NOT NULL,', 'newsletter_id mediumint(9) NOT NULL,',
'subscriber_id mediumint(9) NOT NULL,', 'subscriber_id mediumint(9) NOT NULL,',
'queue_id mediumint(9) NOT NULL,', 'queue_id mediumint(9) NOT NULL,',
'created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,', 'created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,',
'PRIMARY KEY (id)', 'PRIMARY KEY (id)',
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
function statistics_forms() { function statistics_forms() {
$attributes = array( $attributes = array(
'id mediumint(9) NOT NULL AUTO_INCREMENT,', 'id mediumint(9) NOT NULL AUTO_INCREMENT,',
'form_id mediumint(9) NOT NULL,', 'form_id mediumint(9) NOT NULL,',
'subscriber_id mediumint(9) NOT NULL,', 'subscriber_id mediumint(9) NOT NULL,',
'created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,', 'created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,',
'PRIMARY KEY (id),', 'PRIMARY KEY (id),',
'UNIQUE KEY form_subscriber (form_id,subscriber_id)' 'UNIQUE KEY form_subscriber (form_id,subscriber_id)'
); );
return $this->sqlify(__FUNCTION__, $attributes); return $this->sqlify(__FUNCTION__, $attributes);
} }
private function sqlify($model, $attributes) { private function sqlify($model, $attributes) {
$table = $this->prefix . $model; $table = $this->prefix . $model;
$sql = array(); $sql = array();
$sql[] = "CREATE TABLE " . $table . " ("; $sql[] = "CREATE TABLE " . $table . " (";
$sql = array_merge($sql, $attributes); $sql = array_merge($sql, $attributes);
$sql[] = ") " . $this->charset . ";"; $sql[] = ") " . $this->charset . ";";
return implode("\n", $sql); return implode("\n", $sql);
} }
} }

View File

@ -1,160 +1,160 @@
<?php <?php
namespace MailPoet\Config; namespace MailPoet\Config;
use \MailPoet\Util\Security; use \MailPoet\Util\Security;
use \MailPoet\Models\Form; use \MailPoet\Models\Form;
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
class Widget { class Widget {
private $renderer = null; private $renderer = null;
function __construct($renderer = null) { function __construct($renderer = null) {
if($renderer !== null) { if($renderer !== null) {
$this->renderer = $renderer; $this->renderer = $renderer;
} }
} }
function init() { function init() {
$this->registerWidget(); $this->registerWidget();
if(!is_admin()) { if(!is_admin()) {
$this->setupDependencies(); $this->setupDependencies();
$this->setupIframe(); $this->setupIframe();
} else { } else {
$this->setupAdminDependencies(); $this->setupAdminDependencies();
} }
} }
function setupIframe() { function setupIframe() {
$form_id = (isset($_GET['mailpoet_form_iframe']) ? (int)$_GET['mailpoet_form_iframe'] : 0); $form_id = (isset($_GET['mailpoet_form_iframe']) ? (int)$_GET['mailpoet_form_iframe'] : 0);
if($form_id > 0) { if($form_id > 0) {
$form = Form::findOne($form_id); $form = Form::findOne($form_id);
if($form !== false) { if($form !== false) {
$form_widget = new \MailPoet\Form\Widget(); $form_widget = new \MailPoet\Form\Widget();
$form_html = $form_widget->widget(array( $form_html = $form_widget->widget(array(
'form' => $form_id, 'form' => $form_id,
'form_type' => 'iframe' 'form_type' => 'iframe'
)); ));
// capture javascripts // capture javascripts
ob_start(); ob_start();
wp_print_scripts('jquery'); wp_print_scripts('jquery');
wp_print_scripts('mailpoet_vendor'); wp_print_scripts('mailpoet_vendor');
wp_print_scripts('mailpoet_public'); wp_print_scripts('mailpoet_public');
$scripts = ob_get_contents(); $scripts = ob_get_contents();
ob_end_clean(); ob_end_clean();
// language attributes // language attributes
$language_attributes = array(); $language_attributes = array();
$is_rtl = (bool)(function_exists('is_rtl') && is_rtl()); $is_rtl = (bool)(function_exists('is_rtl') && is_rtl());
if($is_rtl) { if($is_rtl) {
$language_attributes[] = 'dir="rtl"'; $language_attributes[] = 'dir="rtl"';
} }
if($lang = get_bloginfo('language')) { if($lang = get_bloginfo('language')) {
if(get_option('html_type') === 'text/html') { if(get_option('html_type') === 'text/html') {
$language_attributes[] = "lang=\"$lang\""; $language_attributes[] = "lang=\"$lang\"";
} }
} }
$language_attributes = apply_filters( $language_attributes = apply_filters(
'language_attributes', implode(' ', $language_attributes) 'language_attributes', implode(' ', $language_attributes)
); );
$data = array( $data = array(
'language_attributes' => $language_attributes, 'language_attributes' => $language_attributes,
'scripts' => $scripts, 'scripts' => $scripts,
'form' => $form_html, 'form' => $form_html,
'mailpoet_form' => array( 'mailpoet_form' => array(
'ajax_url' => admin_url('admin-ajax.php', 'absolute'), 'ajax_url' => admin_url('admin-ajax.php', 'absolute'),
'is_rtl' => $is_rtl, 'is_rtl' => $is_rtl,
'token' => Security::generateToken() 'token' => Security::generateToken()
) )
); );
echo $this->renderer->render('form/iframe.html', $data); echo $this->renderer->render('form/iframe.html', $data);
} }
exit(); exit();
} }
} }
function registerWidget() { function registerWidget() {
register_widget('\MailPoet\Form\Widget'); register_widget('\MailPoet\Form\Widget');
} }
function setupDependencies() { function setupDependencies() {
wp_enqueue_style('mailpoet_public', Env::$assets_url.'/css/public.css'); wp_enqueue_style('mailpoet_public', Env::$assets_url.'/css/public.css');
wp_enqueue_script('mailpoet_vendor', wp_enqueue_script('mailpoet_vendor',
Env::$assets_url.'/js/vendor.js', Env::$assets_url.'/js/vendor.js',
array(), array(),
Env::$version, Env::$version,
true true
); );
wp_enqueue_script('mailpoet_public', wp_enqueue_script('mailpoet_public',
Env::$assets_url.'/js/public.js', Env::$assets_url.'/js/public.js',
array(), array(),
Env::$version, Env::$version,
true true
); );
wp_localize_script('mailpoet_public', 'MailPoetForm', array( wp_localize_script('mailpoet_public', 'MailPoetForm', array(
'ajax_url' => admin_url('admin-ajax.php'), 'ajax_url' => admin_url('admin-ajax.php'),
'is_rtl' => (function_exists('is_rtl') ? (bool)is_rtl() : false), 'is_rtl' => (function_exists('is_rtl') ? (bool)is_rtl() : false),
'token' => Security::generateToken() 'token' => Security::generateToken()
)); ));
} }
function setupAdminDependencies() { function setupAdminDependencies() {
if( if(
empty($_GET['page']) empty($_GET['page'])
or or
isset($_GET['page']) && strpos($_GET['page'], 'mailpoet') === false isset($_GET['page']) && strpos($_GET['page'], 'mailpoet') === false
) { ) {
wp_enqueue_script('mailpoet_vendor', wp_enqueue_script('mailpoet_vendor',
Env::$assets_url.'/js/vendor.js', Env::$assets_url.'/js/vendor.js',
array(), array(),
Env::$version, Env::$version,
true true
); );
wp_enqueue_script('mailpoet_admin', wp_enqueue_script('mailpoet_admin',
Env::$assets_url.'/js/mailpoet.js', Env::$assets_url.'/js/mailpoet.js',
array(), array(),
Env::$version, Env::$version,
true true
); );
} }
} }
// TODO: extract this method into an Initializer // TODO: extract this method into an Initializer
// - the "ajax" part might probably be useless // - the "ajax" part might probably be useless
// - the "post" (non-ajax) part needs to be redone properly // - the "post" (non-ajax) part needs to be redone properly
function setupActions() { function setupActions() {
// ajax requests // ajax requests
add_action( add_action(
'wp_ajax_mailpoet_form_subscribe', 'wp_ajax_mailpoet_form_subscribe',
'mailpoet_form_subscribe' 'mailpoet_form_subscribe'
); );
add_action( add_action(
'wp_ajax_nopriv_mailpoet_form_subscribe', 'wp_ajax_nopriv_mailpoet_form_subscribe',
'mailpoet_form_subscribe' 'mailpoet_form_subscribe'
); );
// post request // post request
add_action( add_action(
'admin_post_nopriv_mailpoet_form_subscribe', 'admin_post_nopriv_mailpoet_form_subscribe',
'mailpoet_form_subscribe' 'mailpoet_form_subscribe'
); );
add_action( add_action(
'admin_post_mailpoet_form_subscribe', 'admin_post_mailpoet_form_subscribe',
'mailpoet_form_subscribe' 'mailpoet_form_subscribe'
); );
add_action( add_action(
'init', 'init',
'mailpoet_form_subscribe' 'mailpoet_form_subscribe'
); );
} }
} }

View File

@ -1,143 +1,143 @@
<?php <?php
namespace MailPoet\Mailer; namespace MailPoet\Mailer;
use MailPoet\Models\Setting; use MailPoet\Models\Setting;
require_once(ABSPATH . 'wp-includes/pluggable.php'); require_once(ABSPATH . 'wp-includes/pluggable.php');
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
class Mailer { class Mailer {
public $mailer; public $mailer;
public $sender; public $sender;
public $reply_to; public $reply_to;
public $mailer_instance; public $mailer_instance;
function __construct($mailer = false, $sender = false, $reply_to = false) { function __construct($mailer = false, $sender = false, $reply_to = false) {
$this->mailer = $this->getMailer($mailer); $this->mailer = $this->getMailer($mailer);
$this->sender = $this->getSender($sender); $this->sender = $this->getSender($sender);
$this->reply_to = $this->getReplyTo($reply_to); $this->reply_to = $this->getReplyTo($reply_to);
$this->mailer_instance = $this->buildMailer(); $this->mailer_instance = $this->buildMailer();
} }
function send($newsletter, $subscriber) { function send($newsletter, $subscriber) {
$subscriber = $this->transformSubscriber($subscriber); $subscriber = $this->transformSubscriber($subscriber);
return $this->mailer_instance->send($newsletter, $subscriber); return $this->mailer_instance->send($newsletter, $subscriber);
} }
function buildMailer() { function buildMailer() {
switch($this->mailer['method']) { switch($this->mailer['method']) {
case 'AmazonSES': case 'AmazonSES':
$mailer_instance = new $this->mailer['class']( $mailer_instance = new $this->mailer['class'](
$this->mailer['region'], $this->mailer['region'],
$this->mailer['access_key'], $this->mailer['access_key'],
$this->mailer['secret_key'], $this->mailer['secret_key'],
$this->sender, $this->sender,
$this->reply_to $this->reply_to
); );
break; break;
case 'ElasticEmail': case 'ElasticEmail':
$mailer_instance = new $this->mailer['class']( $mailer_instance = new $this->mailer['class'](
$this->mailer['api_key'], $this->mailer['api_key'],
$this->sender, $this->sender,
$this->reply_to $this->reply_to
); );
break; break;
case 'MailGun': case 'MailGun':
$mailer_instance = new $this->mailer['class']( $mailer_instance = new $this->mailer['class'](
$this->mailer['domain'], $this->mailer['domain'],
$this->mailer['api_key'], $this->mailer['api_key'],
$this->sender, $this->sender,
$this->reply_to $this->reply_to
); );
break; break;
case 'MailPoet': case 'MailPoet':
$mailer_instance = new $this->mailer['class']( $mailer_instance = new $this->mailer['class'](
$this->mailer['mailpoet_api_key'], $this->mailer['mailpoet_api_key'],
$this->sender, $this->sender,
$this->reply_to $this->reply_to
); );
break; break;
case 'SendGrid': case 'SendGrid':
$mailer_instance = new $this->mailer['class']( $mailer_instance = new $this->mailer['class'](
$this->mailer['api_key'], $this->mailer['api_key'],
$this->sender, $this->sender,
$this->reply_to $this->reply_to
); );
break; break;
case 'PHPMail': case 'PHPMail':
$mailer_instance = new $this->mailer['class']( $mailer_instance = new $this->mailer['class'](
$this->sender, $this->sender,
$this->reply_to $this->reply_to
); );
break; break;
case 'SMTP': case 'SMTP':
$mailer_instance = new $this->mailer['class']( $mailer_instance = new $this->mailer['class'](
$this->mailer['host'], $this->mailer['host'],
$this->mailer['port'], $this->mailer['port'],
$this->mailer['authentication'], $this->mailer['authentication'],
$this->mailer['login'], $this->mailer['login'],
$this->mailer['password'], $this->mailer['password'],
$this->mailer['encryption'], $this->mailer['encryption'],
$this->sender, $this->sender,
$this->reply_to $this->reply_to
); );
break; break;
default: default:
throw new \Exception(__('Mailing method does not exist.')); throw new \Exception(__('Mailing method does not exist.'));
} }
return $mailer_instance; return $mailer_instance;
} }
function getMailer($mailer = false) { function getMailer($mailer = false) {
if(!$mailer) { if(!$mailer) {
$mailer = Setting::getValue('mta'); $mailer = Setting::getValue('mta');
if(!$mailer || !isset($mailer['method'])) throw new \Exception(__('Mailer is not configured.')); if(!$mailer || !isset($mailer['method'])) throw new \Exception(__('Mailer is not configured.'));
} }
$mailer['class'] = 'MailPoet\\Mailer\\Methods\\' . $mailer['method']; $mailer['class'] = 'MailPoet\\Mailer\\Methods\\' . $mailer['method'];
return $mailer; return $mailer;
} }
function getSender($sender = false) { function getSender($sender = false) {
if(empty($sender)) { if(empty($sender)) {
$sender = Setting::getValue('sender', array()); $sender = Setting::getValue('sender', array());
if(empty($sender['address'])) throw new \Exception(__('Sender name and email are not configured.')); if(empty($sender['address'])) throw new \Exception(__('Sender name and email are not configured.'));
} }
return array( return array(
'from_name' => $sender['name'], 'from_name' => $sender['name'],
'from_email' => $sender['address'], 'from_email' => $sender['address'],
'from_name_email' => sprintf('%s <%s>', $sender['name'], $sender['address']) 'from_name_email' => sprintf('%s <%s>', $sender['name'], $sender['address'])
); );
} }
function getReplyTo($reply_to = false) { function getReplyTo($reply_to = false) {
if(!$reply_to) { if(!$reply_to) {
$reply_to = Setting::getValue('reply_to', null); $reply_to = Setting::getValue('reply_to', null);
if(!$reply_to) { if(!$reply_to) {
$reply_to = array( $reply_to = array(
'name' => $this->sender['from_name'], 'name' => $this->sender['from_name'],
'address' => $this->sender['from_email'] 'address' => $this->sender['from_email']
); );
} }
} }
if(empty($reply_to['address'])) { if(empty($reply_to['address'])) {
$reply_to['address'] = $this->sender['from_email']; $reply_to['address'] = $this->sender['from_email'];
} }
return array( return array(
'reply_to_name' => $reply_to['name'], 'reply_to_name' => $reply_to['name'],
'reply_to_email' => $reply_to['address'], 'reply_to_email' => $reply_to['address'],
'reply_to_name_email' => sprintf('%s <%s>', $reply_to['name'], $reply_to['address']) 'reply_to_name_email' => sprintf('%s <%s>', $reply_to['name'], $reply_to['address'])
); );
} }
function transformSubscriber($subscriber) { function transformSubscriber($subscriber) {
if(!is_array($subscriber)) return $subscriber; if(!is_array($subscriber)) return $subscriber;
if(isset($subscriber['address'])) $subscriber['email'] = $subscriber['address']; if(isset($subscriber['address'])) $subscriber['email'] = $subscriber['address'];
$first_name = (isset($subscriber['first_name'])) ? $subscriber['first_name'] : ''; $first_name = (isset($subscriber['first_name'])) ? $subscriber['first_name'] : '';
$last_name = (isset($subscriber['last_name'])) ? $subscriber['last_name'] : ''; $last_name = (isset($subscriber['last_name'])) ? $subscriber['last_name'] : '';
if(!$first_name && !$last_name) return $subscriber['email']; if(!$first_name && !$last_name) return $subscriber['email'];
$subscriber = sprintf('%s %s <%s>', $first_name, $last_name, $subscriber['email']); $subscriber = sprintf('%s %s <%s>', $first_name, $last_name, $subscriber['email']);
$subscriber = trim(preg_replace('!\s\s+!', ' ', $subscriber)); $subscriber = trim(preg_replace('!\s\s+!', ' ', $subscriber));
return $subscriber; return $subscriber;
} }
} }

View File

@ -1,160 +1,160 @@
<?php <?php
namespace MailPoet\Models; namespace MailPoet\Models;
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
class Model extends \Sudzy\ValidModel { class Model extends \Sudzy\ValidModel {
protected $_errors; protected $_errors;
function __construct() { function __construct() {
$this->_errors = array(); $this->_errors = array();
parent::__construct(); parent::__construct();
} }
static function create() { static function create() {
return parent::create(); return parent::create();
} }
function getErrors() { function getErrors() {
if(empty($this->_errors)) { if(empty($this->_errors)) {
return false; return false;
} else { } else {
return $this->_errors; return $this->_errors;
} }
} }
function setError($error = '') { function setError($error = '') {
if(!empty($error)) { if(!empty($error)) {
if(is_array($error)) { if(is_array($error)) {
$this->_errors = array_merge($this->_errors, $error); $this->_errors = array_merge($this->_errors, $error);
$this->_errors = array_unique($this->_errors); $this->_errors = array_unique($this->_errors);
} else { } else {
$this->_errors[] = $error; $this->_errors[] = $error;
} }
} }
} }
function save() { function save() {
$this->setTimestamp(); $this->setTimestamp();
try { try {
parent::save(); parent::save();
} catch(\Sudzy\ValidationException $e) { } catch(\Sudzy\ValidationException $e) {
$this->setError($e->getValidationErrors()); $this->setError($e->getValidationErrors());
} catch(\PDOException $e) { } catch(\PDOException $e) {
switch($e->getCode()) { switch($e->getCode()) {
case 23000: case 23000:
preg_match("/for key \'(.*?)\'/i", $e->getMessage(), $matches); preg_match("/for key \'(.*?)\'/i", $e->getMessage(), $matches);
if(isset($matches[1])) { if(isset($matches[1])) {
$column = $matches[1]; $column = $matches[1];
$this->setError( $this->setError(
sprintf( sprintf(
__('Another record already exists. Please specify a different "%1$s".'), __('Another record already exists. Please specify a different "%1$s".'),
$column $column
) )
); );
} else { } else {
$this->setError($e->getMessage()); $this->setError($e->getMessage());
} }
break; break;
default: default:
$this->setError($e->getMessage()); $this->setError($e->getMessage());
} }
} }
return $this; return $this;
} }
function trash() { function trash() {
return $this->set_expr('deleted_at', 'NOW()')->save(); return $this->set_expr('deleted_at', 'NOW()')->save();
} }
static function bulkTrash($orm) { static function bulkTrash($orm) {
$model = get_called_class(); $model = get_called_class();
return self::bulkAction($orm, function($ids) use($model) { return self::bulkAction($orm, function($ids) use($model) {
self::rawExecute(join(' ', array( self::rawExecute(join(' ', array(
'UPDATE `'.$model::$_table.'`', 'UPDATE `'.$model::$_table.'`',
'SET `deleted_at` = NOW()', 'SET `deleted_at` = NOW()',
'WHERE `id` IN ('.rtrim(str_repeat('?,', count($ids)), ',').')' 'WHERE `id` IN ('.rtrim(str_repeat('?,', count($ids)), ',').')'
)), )),
$ids $ids
); );
}); });
} }
static function bulkDelete($orm) { static function bulkDelete($orm) {
$model = get_called_class(); $model = get_called_class();
return self::bulkAction($orm, function($ids) use($model) { return self::bulkAction($orm, function($ids) use($model) {
$model::whereIn('id', $ids)->deleteMany(); $model::whereIn('id', $ids)->deleteMany();
}); });
} }
function restore() { function restore() {
return $this->set_expr('deleted_at', 'NULL')->save(); return $this->set_expr('deleted_at', 'NULL')->save();
} }
static function bulkRestore($orm) { static function bulkRestore($orm) {
$model = get_called_class(); $model = get_called_class();
return self::bulkAction($orm, function($ids) use($model) { return self::bulkAction($orm, function($ids) use($model) {
self::rawExecute(join(' ', array( self::rawExecute(join(' ', array(
'UPDATE `'.$model::$_table.'`', 'UPDATE `'.$model::$_table.'`',
'SET `deleted_at` = NULL', 'SET `deleted_at` = NULL',
'WHERE `id` IN ('.rtrim(str_repeat('?,', count($ids)), ',').')' 'WHERE `id` IN ('.rtrim(str_repeat('?,', count($ids)), ',').')'
)), )),
$ids $ids
); );
}); });
} }
static function bulkAction($orm, $callback = false) { static function bulkAction($orm, $callback = false) {
$total = $orm->count(); $total = $orm->count();
if($total === 0) return false; if($total === 0) return false;
$rows = $orm->select(static::$_table.'.id') $rows = $orm->select(static::$_table.'.id')
->offset(null) ->offset(null)
->limit(null) ->limit(null)
->findArray(); ->findArray();
$ids = array_map(function($model) { $ids = array_map(function($model) {
return (int)$model['id']; return (int)$model['id'];
}, $rows); }, $rows);
if($callback !== false) { if($callback !== false) {
$callback($ids); $callback($ids);
} }
// get number of affected rows // get number of affected rows
return $orm->get_last_statement()->rowCount(); return $orm->get_last_statement()->rowCount();
} }
function duplicate($data = array()) { function duplicate($data = array()) {
$model = get_called_class(); $model = get_called_class();
$model_data = array_merge($this->asArray(), $data); $model_data = array_merge($this->asArray(), $data);
unset($model_data['id']); unset($model_data['id']);
$duplicate = $model::create(); $duplicate = $model::create();
$duplicate->hydrate($model_data); $duplicate->hydrate($model_data);
$duplicate->set_expr('created_at', 'NOW()'); $duplicate->set_expr('created_at', 'NOW()');
$duplicate->set_expr('updated_at', 'NOW()'); $duplicate->set_expr('updated_at', 'NOW()');
$duplicate->set_expr('deleted_at', 'NULL'); $duplicate->set_expr('deleted_at', 'NULL');
if($duplicate->save()) { if($duplicate->save()) {
return $duplicate; return $duplicate;
} else { } else {
return false; return false;
} }
} }
private function setTimestamp() { private function setTimestamp() {
if($this->created_at === null) { if($this->created_at === null) {
$this->set_expr('created_at', 'NOW()'); $this->set_expr('created_at', 'NOW()');
} }
} }
static function getPublished() { static function getPublished() {
return static::whereNull('deleted_at'); return static::whereNull('deleted_at');
} }
static function getTrashed() { static function getTrashed() {
return static::whereNotNull('deleted_at'); return static::whereNotNull('deleted_at');
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,46 +1,46 @@
<?php <?php
namespace MailPoet\Models; namespace MailPoet\Models;
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
class NewsletterTemplate extends Model { class NewsletterTemplate extends Model {
public static $_table = MP_NEWSLETTER_TEMPLATES_TABLE; public static $_table = MP_NEWSLETTER_TEMPLATES_TABLE;
function __construct() { function __construct() {
parent::__construct(); parent::__construct();
$this->addValidations('name', array( $this->addValidations('name', array(
'required' => __('Please specify a name.') 'required' => __('Please specify a name.')
)); ));
$this->addValidations('body', array( $this->addValidations('body', array(
'required' => __('The template body cannot be empty.') 'required' => __('The template body cannot be empty.')
)); ));
} }
function asArray() { function asArray() {
$template = parent::asArray(); $template = parent::asArray();
if(isset($template['body'])) { if(isset($template['body'])) {
$template['body'] = json_decode($template['body'], true); $template['body'] = json_decode($template['body'], true);
} }
return $template; return $template;
} }
static function createOrUpdate($data = array()) { static function createOrUpdate($data = array()) {
$template = false; $template = false;
if(isset($data['id']) && (int)$data['id'] > 0) { if(isset($data['id']) && (int)$data['id'] > 0) {
$template = self::findOne((int)$data['id']); $template = self::findOne((int)$data['id']);
} }
if($template === false) { if($template === false) {
$template = self::create(); $template = self::create();
$template->hydrate($data); $template->hydrate($data);
} else { } else {
unset($data['id']); unset($data['id']);
$template->set($data); $template->set($data);
} }
$template->save(); $template->save();
return $template; return $template;
} }
} }

View File

@ -1,160 +1,160 @@
<?php <?php
namespace MailPoet\Models; namespace MailPoet\Models;
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
class Setting extends Model { class Setting extends Model {
public static $_table = MP_SETTINGS_TABLE; public static $_table = MP_SETTINGS_TABLE;
public static $defaults = null; public static $defaults = null;
const DEFAULT_SENDING_METHOD_GROUP = 'website'; const DEFAULT_SENDING_METHOD_GROUP = 'website';
const DEFAULT_SENDING_METHOD = 'PHPMail'; const DEFAULT_SENDING_METHOD = 'PHPMail';
const DEFAULT_SENDING_FREQUENCY_EMAILS = 25; const DEFAULT_SENDING_FREQUENCY_EMAILS = 25;
const DEFAULT_SENDING_FREQUENCY_INTERVAL = 5; // in minutes const DEFAULT_SENDING_FREQUENCY_INTERVAL = 5; // in minutes
function __construct() { function __construct() {
parent::__construct(); parent::__construct();
$this->addValidations('name', array( $this->addValidations('name', array(
'required' => __('Please specify a name.') 'required' => __('Please specify a name.')
)); ));
} }
public static function getDefaults() { public static function getDefaults() {
if(self::$defaults === null) { if(self::$defaults === null) {
self::loadDefaults(); self::loadDefaults();
} }
return self::$defaults; return self::$defaults;
} }
public static function loadDefaults() { public static function loadDefaults() {
self::$defaults = array( self::$defaults = array(
'mta_group' => self::DEFAULT_SENDING_METHOD_GROUP, 'mta_group' => self::DEFAULT_SENDING_METHOD_GROUP,
'mta' => array( 'mta' => array(
'method' => self::DEFAULT_SENDING_METHOD, 'method' => self::DEFAULT_SENDING_METHOD,
'frequency' => array( 'frequency' => array(
'emails' => self::DEFAULT_SENDING_FREQUENCY_EMAILS, 'emails' => self::DEFAULT_SENDING_FREQUENCY_EMAILS,
'interval' => self::DEFAULT_SENDING_FREQUENCY_INTERVAL 'interval' => self::DEFAULT_SENDING_FREQUENCY_INTERVAL
) )
), ),
'signup_confirmation' => array( 'signup_confirmation' => array(
'enabled' => true, 'enabled' => true,
'subject' => sprintf(__('Confirm your subscription to %1$s'), get_option('blogname')), 'subject' => sprintf(__('Confirm your subscription to %1$s'), get_option('blogname')),
'body' => __("Hello!\n\nHurray! You've subscribed to our site.\n\nPlease confirm your subscription to the list(s): [lists_to_confirm] by clicking the link below: \n\n[activation_link]Click here to confirm your subscription.[/activation_link]\n\nThank you,\n\nThe Team") 'body' => __("Hello!\n\nHurray! You've subscribed to our site.\n\nPlease confirm your subscription to the list(s): [lists_to_confirm] by clicking the link below: \n\n[activation_link]Click here to confirm your subscription.[/activation_link]\n\nThank you,\n\nThe Team")
), ),
'tracking' => array( 'tracking' => array(
'enabled' => true 'enabled' => true
) )
); );
} }
public static function getValue($key, $default = null) { public static function getValue($key, $default = null) {
$keys = explode('.', $key); $keys = explode('.', $key);
$defaults = self::getDefaults(); $defaults = self::getDefaults();
if(count($keys) === 1) { if(count($keys) === 1) {
$setting = Setting::where('name', $key)->findOne(); $setting = Setting::where('name', $key)->findOne();
if($setting === false) { if($setting === false) {
if($default === null && array_key_exists($key, $defaults)) { if($default === null && array_key_exists($key, $defaults)) {
return $defaults[$key]; return $defaults[$key];
} else { } else {
return $default; return $default;
} }
} else { } else {
if(is_serialized($setting->value)) { if(is_serialized($setting->value)) {
$value = unserialize($setting->value); $value = unserialize($setting->value);
} else { } else {
$value = $setting->value; $value = $setting->value;
} }
if(is_array($value) && array_key_exists($key, $defaults)) { if(is_array($value) && array_key_exists($key, $defaults)) {
return array_replace_recursive($defaults[$key], $value); return array_replace_recursive($defaults[$key], $value);
} else { } else {
return $value; return $value;
} }
} }
} else { } else {
$main_key = array_shift($keys); $main_key = array_shift($keys);
$setting = static::getValue($main_key, $default); $setting = static::getValue($main_key, $default);
if($setting !== $default) { if($setting !== $default) {
for($i = 0, $count = count($keys); $i < $count; $i++) { for($i = 0, $count = count($keys); $i < $count; $i++) {
if(!is_array($setting)) { if(!is_array($setting)) {
$setting = array(); $setting = array();
} }
if(array_key_exists($keys[$i], $setting)) { if(array_key_exists($keys[$i], $setting)) {
$setting = $setting[$keys[$i]]; $setting = $setting[$keys[$i]];
} else { } else {
return $default; return $default;
} }
} }
} }
return $setting; return $setting;
} }
} }
public static function setValue($key, $value) { public static function setValue($key, $value) {
$keys = explode('.', $key); $keys = explode('.', $key);
if(count($keys) === 1) { if(count($keys) === 1) {
if(is_array($value)) { if(is_array($value)) {
$value = serialize($value); $value = serialize($value);
} }
$setting = Setting::createOrUpdate(array( $setting = Setting::createOrUpdate(array(
'name' => $key, 'name' => $key,
'value' => $value 'value' => $value
)); ));
return ($setting->id() > 0 && $setting->getErrors() === false); return ($setting->id() > 0 && $setting->getErrors() === false);
} else { } else {
$main_key = array_shift($keys); $main_key = array_shift($keys);
$setting_value = static::getValue($main_key, array()); $setting_value = static::getValue($main_key, array());
$current_value = &$setting_value; $current_value = &$setting_value;
$last_key = array_pop($keys); $last_key = array_pop($keys);
foreach($keys as $key) { foreach($keys as $key) {
$current_value =& $current_value[$key]; $current_value =& $current_value[$key];
} }
if(is_scalar($current_value)) { if(is_scalar($current_value)) {
$current_value = array(); $current_value = array();
} }
$current_value[$last_key] = $value; $current_value[$last_key] = $value;
return static::setValue($main_key, $setting_value); return static::setValue($main_key, $setting_value);
} }
} }
public static function getAll() { public static function getAll() {
$settingsCollection = self::findMany(); $settingsCollection = self::findMany();
$settings = array(); $settings = array();
if(!empty($settingsCollection)) { if(!empty($settingsCollection)) {
foreach($settingsCollection as $setting) { foreach($settingsCollection as $setting) {
$value = (is_serialized($setting->value) $value = (is_serialized($setting->value)
? unserialize($setting->value) ? unserialize($setting->value)
: $setting->value : $setting->value
); );
$settings[$setting->name] = $value; $settings[$setting->name] = $value;
} }
} }
return array_replace_recursive(self::getDefaults(), $settings); return array_replace_recursive(self::getDefaults(), $settings);
} }
public static function createOrUpdate($data = array()) { public static function createOrUpdate($data = array()) {
$setting = false; $setting = false;
if(isset($data['name'])) { if(isset($data['name'])) {
$setting = self::where('name', $data['name'])->findOne(); $setting = self::where('name', $data['name'])->findOne();
} }
if($setting === false) { if($setting === false) {
$setting = self::create(); $setting = self::create();
$setting->hydrate($data); $setting->hydrate($data);
} else { } else {
$setting->value = $data['value']; $setting->value = $data['value'];
} }
return $setting->save(); return $setting->save();
} }
} }

View File

@ -1,132 +1,132 @@
<?php <?php
namespace MailPoet\Newsletter\Links; namespace MailPoet\Newsletter\Links;
use MailPoet\Models\NewsletterLink; use MailPoet\Models\NewsletterLink;
use MailPoet\Newsletter\Shortcodes\Shortcodes; use MailPoet\Newsletter\Shortcodes\Shortcodes;
use MailPoet\Util\Helpers; use MailPoet\Util\Helpers;
use MailPoet\Util\Security; use MailPoet\Util\Security;
class Links { class Links {
const DATA_TAG = '[mailpoet_data]'; const DATA_TAG = '[mailpoet_data]';
const HASH_LENGTH = 5; const HASH_LENGTH = 5;
static function extract($content) { static function extract($content) {
$extracted_links = array(); $extracted_links = array();
// adopted from WP's wp_extract_urls() function & modified to work on hrefs // adopted from WP's wp_extract_urls() function & modified to work on hrefs
# match href=' or href=" # match href=' or href="
$regex = '#(?:href.*?=.*?)(["\']?)(' $regex = '#(?:href.*?=.*?)(["\']?)('
# match http:// # match http://
. '(?:([\w-]+:)?//?)' . '(?:([\w-]+:)?//?)'
# match everything except for special characters # until . # match everything except for special characters # until .
. '[^\s()<>]+' . '[^\s()<>]+'
. '[.]' . '[.]'
# conditionally match everything except for special characters after . # conditionally match everything except for special characters after .
. '(?:' . '(?:'
. '\([\w\d]+\)|' . '\([\w\d]+\)|'
. '(?:' . '(?:'
. '[^`!()\[\]{}:;\'".,<>«»“”‘’\s]|' . '[^`!()\[\]{}:;\'".,<>«»“”‘’\s]|'
. '(?:[:]\d+)?/?' . '(?:[:]\d+)?/?'
. ')+' . ')+'
. ')' . ')'
. ')\\1#'; . ')\\1#';
// extract shortcodes with [link:*] format // extract shortcodes with [link:*] format
$shortcodes = new Shortcodes(); $shortcodes = new Shortcodes();
$shortcodes = $shortcodes->extract($content, $categories = array('link')); $shortcodes = $shortcodes->extract($content, $categories = array('link'));
$extracted_links = array_map(function($shortcode) { $extracted_links = array_map(function($shortcode) {
return array( return array(
'html' => $shortcode, 'html' => $shortcode,
'link' => $shortcode 'link' => $shortcode
); );
}, $shortcodes); }, $shortcodes);
// extract urls with href="url" format // extract urls with href="url" format
preg_match_all($regex, $content, $matched_urls); preg_match_all($regex, $content, $matched_urls);
$matched_urls_count = count($matched_urls[0]); $matched_urls_count = count($matched_urls[0]);
if($matched_urls_count) { if($matched_urls_count) {
for($index = 0; $index < $matched_urls_count; $index++) { for($index = 0; $index < $matched_urls_count; $index++) {
$extracted_links[] = array( $extracted_links[] = array(
'html' => $matched_urls[0][$index], 'html' => $matched_urls[0][$index],
'link' => $matched_urls[2][$index] 'link' => $matched_urls[2][$index]
); );
} }
} }
return array_unique($extracted_links, SORT_REGULAR); return array_unique($extracted_links, SORT_REGULAR);
} }
static function process($content) { static function process($content) {
$extracted_links = self::extract($content); $extracted_links = self::extract($content);
$processed_links = array(); $processed_links = array();
foreach($extracted_links as $extracted_link) { foreach($extracted_links as $extracted_link) {
$hash = Security::generateRandomString(self::HASH_LENGTH); $hash = Security::generateRandomString(self::HASH_LENGTH);
$processed_links[] = array( $processed_links[] = array(
'hash' => $hash, 'hash' => $hash,
'url' => $extracted_link['link'] 'url' => $extracted_link['link']
); );
$params = array( $params = array(
'mailpoet' => '', 'mailpoet' => '',
'endpoint' => 'track', 'endpoint' => 'track',
'action' => 'click', 'action' => 'click',
'data' => self::DATA_TAG . '-' . $hash 'data' => self::DATA_TAG . '-' . $hash
); );
$tracked_link = add_query_arg($params, home_url()); $tracked_link = add_query_arg($params, home_url());
// first, replace URL in the extracted HTML source with encoded link // first, replace URL in the extracted HTML source with encoded link
$tracked_link_html_source = str_replace( $tracked_link_html_source = str_replace(
$extracted_link['link'], $tracked_link, $extracted_link['link'], $tracked_link,
$extracted_link['html'] $extracted_link['html']
); );
// second, replace original extracted HTML source with tracked URL source // second, replace original extracted HTML source with tracked URL source
$content = str_replace( $content = str_replace(
$extracted_link['html'], $tracked_link_html_source, $content $extracted_link['html'], $tracked_link_html_source, $content
); );
// third, replace text version URL with tracked link: [description](url) // third, replace text version URL with tracked link: [description](url)
// regex is used to avoid replacing description URLs that are wrapped in round brackets // regex is used to avoid replacing description URLs that are wrapped in round brackets
// i.e., <a href="http://google.com">(http://google.com)</a> => [(http://google.com)](http://tracked_link) // i.e., <a href="http://google.com">(http://google.com)</a> => [(http://google.com)](http://tracked_link)
$regex_escaped_extracted_link = preg_quote($extracted_link['link'], '/'); $regex_escaped_extracted_link = preg_quote($extracted_link['link'], '/');
$content = preg_replace( $content = preg_replace(
'/\[(' . $regex_escaped_extracted_link . ')\](\(' . $regex_escaped_extracted_link . '\))/', '/\[(' . $regex_escaped_extracted_link . ')\](\(' . $regex_escaped_extracted_link . '\))/',
'[$1](' . $tracked_link . ')', '[$1](' . $tracked_link . ')',
$content $content
); );
} }
return array( return array(
$content, $content,
$processed_links $processed_links
); );
} }
static function replaceSubscriberData( static function replaceSubscriberData(
$newsletter_id, $newsletter_id,
$subscriber_id, $subscriber_id,
$queue_id, $queue_id,
$content $content
) { ) {
$regex = sprintf('/data=(%s(?:-\w+)?)/', preg_quote(self::DATA_TAG)); $regex = sprintf('/data=(%s(?:-\w+)?)/', preg_quote(self::DATA_TAG));
preg_match_all($regex, $content, $links); preg_match_all($regex, $content, $links);
foreach($links[1] as $link) { foreach($links[1] as $link) {
$hash = null; $hash = null;
if(preg_match('/-/', $link)) { if(preg_match('/-/', $link)) {
list(, $hash) = explode('-', $link); list(, $hash) = explode('-', $link);
} }
$data = array( $data = array(
'newsletter' => $newsletter_id, 'newsletter' => $newsletter_id,
'subscriber' => $subscriber_id, 'subscriber' => $subscriber_id,
'queue' => $queue_id, 'queue' => $queue_id,
'hash' => $hash 'hash' => $hash
); );
$data = rtrim(base64_encode(serialize($data)), '='); $data = rtrim(base64_encode(serialize($data)), '=');
$content = str_replace($link, $data, $content); $content = str_replace($link, $data, $content);
} }
return $content; return $content;
} }
static function save(array $links, $newsletter_id, $queue_id) { static function save(array $links, $newsletter_id, $queue_id) {
foreach($links as $link) { foreach($links as $link) {
if(empty($link['hash'] || empty($link['url']))) continue; if(empty($link['hash'] || empty($link['url']))) continue;
$newsletter_link = NewsletterLink::create(); $newsletter_link = NewsletterLink::create();
$newsletter_link->newsletter_id = $newsletter_id; $newsletter_link->newsletter_id = $newsletter_id;
$newsletter_link->queue_id = $queue_id; $newsletter_link->queue_id = $queue_id;
$newsletter_link->hash = $link['hash']; $newsletter_link->hash = $link['hash'];
$newsletter_link->url = $link['url']; $newsletter_link->url = $link['url'];
$newsletter_link->save(); $newsletter_link->save();
} }
} }
} }

View File

@ -1,27 +1,27 @@
<?php <?php
namespace MailPoet\Newsletter\Renderer\PostProcess; namespace MailPoet\Newsletter\Renderer\PostProcess;
use MailPoet\Newsletter\Links\Links; use MailPoet\Newsletter\Links\Links;
use MailPoet\Newsletter\Renderer\Renderer; use MailPoet\Newsletter\Renderer\Renderer;
class OpenTracking { class OpenTracking {
static function process($template) { static function process($template) {
$DOM = new \pQuery(); $DOM = new \pQuery();
$DOM = $DOM->parseStr($template); $DOM = $DOM->parseStr($template);
$template = $DOM->query('body'); $template = $DOM->query('body');
$open_tracking_image = sprintf( $open_tracking_image = sprintf(
'<img alt="" class="" src="%s/%s"/>', '<img alt="" class="" src="%s/%s"/>',
home_url(), home_url(),
esc_attr('?mailpoet&endpoint=track&action=open&data=' . Links::DATA_TAG) esc_attr('?mailpoet&endpoint=track&action=open&data=' . Links::DATA_TAG)
); );
$template->html($template->html() . $open_tracking_image); $template->html($template->html() . $open_tracking_image);
return $DOM->__toString(); return $DOM->__toString();
} }
static function addTrackingImage() { static function addTrackingImage() {
add_filter(Renderer::POST_PROCESS_FILTER, function ($template) { add_filter(Renderer::POST_PROCESS_FILTER, function ($template) {
return OpenTracking::process($template); return OpenTracking::process($template);
}); });
return true; return true;
} }
} }

View File

@ -1,17 +1,17 @@
<?php <?php
namespace MailPoet\Newsletter\Shortcodes\Categories; namespace MailPoet\Newsletter\Shortcodes\Categories;
class Date { class Date {
static function process($action) { static function process($action) {
$date = new \DateTime('now'); $date = new \DateTime('now');
$actions = array( $actions = array(
'd' => $date->format('d'), 'd' => $date->format('d'),
'dordinal' => $date->format('dS'), 'dordinal' => $date->format('dS'),
'dtext' => $date->format('D'), 'dtext' => $date->format('D'),
'm' => $date->format('m'), 'm' => $date->format('m'),
'mtext' => $date->format('F'), 'mtext' => $date->format('F'),
'y' => $date->format('Y') 'y' => $date->format('Y')
); );
return (isset($actions[$action])) ? $actions[$action] : false; return (isset($actions[$action])) ? $actions[$action] : false;
} }
} }

View File

@ -1,57 +1,57 @@
<?php <?php
namespace MailPoet\Newsletter\Shortcodes\Categories; namespace MailPoet\Newsletter\Shortcodes\Categories;
use MailPoet\Models\SendingQueue; use MailPoet\Models\SendingQueue;
use MailPoet\Newsletter\Shortcodes\ShortcodesHelper; use MailPoet\Newsletter\Shortcodes\ShortcodesHelper;
require_once( ABSPATH . "wp-includes/pluggable.php" ); require_once( ABSPATH . "wp-includes/pluggable.php" );
class Newsletter { class Newsletter {
static function process($action, static function process($action,
$default_value = false, $default_value = false,
$newsletter, $newsletter,
$subscriber, $subscriber,
$queue = false, $queue = false,
$content $content
) { ) {
switch($action) { switch($action) {
case 'subject': case 'subject':
return ($newsletter) ? $newsletter['subject'] : false; return ($newsletter) ? $newsletter['subject'] : false;
case 'total': case 'total':
return substr_count($content, 'data-post-id'); return substr_count($content, 'data-post-id');
case 'post_title': case 'post_title':
preg_match_all('/data-post-id="(\d+)"/ism', $content, $posts); preg_match_all('/data-post-id="(\d+)"/ism', $content, $posts);
$post_ids = array_unique($posts[1]); $post_ids = array_unique($posts[1]);
$latest_post = self::getLatestWPPost($post_ids); $latest_post = self::getLatestWPPost($post_ids);
return ($latest_post) ? $latest_post['post_title'] : false; return ($latest_post) ? $latest_post['post_title'] : false;
case 'number': case 'number':
if($newsletter['type'] !== 'notification') return false; if($newsletter['type'] !== 'notification') return false;
$sent_newsletters = $sent_newsletters =
SendingQueue::where('newsletter_id', $newsletter['id']) SendingQueue::where('newsletter_id', $newsletter['id'])
->where('status', 'completed') ->where('status', 'completed')
->count(); ->count();
return ++$sent_newsletters; return ++$sent_newsletters;
default: default:
return false; return false;
} }
} }
private static function getLatestWPPost($post_ids) { private static function getLatestWPPost($post_ids) {
$posts = new \WP_Query( $posts = new \WP_Query(
array( array(
'post__in' => $post_ids, 'post__in' => $post_ids,
'posts_per_page' => 1, 'posts_per_page' => 1,
'ignore_sticky_posts' => true, 'ignore_sticky_posts' => true,
'orderby' => 'post_date', 'orderby' => 'post_date',
'order' => 'DESC' 'order' => 'DESC'
) )
); );
return (count($posts)) ? return (count($posts)) ?
$posts->posts[0]->to_array() : $posts->posts[0]->to_array() :
false; false;
} }
} }

View File

@ -1,97 +1,97 @@
<?php <?php
namespace MailPoet\Newsletter\Shortcodes; namespace MailPoet\Newsletter\Shortcodes;
class Shortcodes { class Shortcodes {
public $newsletter; public $newsletter;
public $subscriber; public $subscriber;
public $queue; public $queue;
const SHORTCODE_CATEGORY_NAMESPACE = 'MailPoet\Newsletter\Shortcodes\Categories\\'; const SHORTCODE_CATEGORY_NAMESPACE = 'MailPoet\Newsletter\Shortcodes\Categories\\';
function __construct( function __construct(
$newsletter = false, $newsletter = false,
$subscriber = false, $subscriber = false,
$queue = false $queue = false
) { ) {
$this->newsletter = (is_object($newsletter)) ? $this->newsletter = (is_object($newsletter)) ?
$newsletter->asArray() : $newsletter->asArray() :
$newsletter; $newsletter;
$this->subscriber = (is_object($subscriber)) ? $this->subscriber = (is_object($subscriber)) ?
$subscriber->asArray() : $subscriber->asArray() :
$subscriber; $subscriber;
$this->queue = (is_object($queue)) ? $this->queue = (is_object($queue)) ?
$queue->asArray() : $queue->asArray() :
$queue; $queue;
} }
function extract($content, $categories = false) { function extract($content, $categories = false) {
$categories = (is_array($categories)) ? implode('|', $categories) : false; $categories = (is_array($categories)) ? implode('|', $categories) : false;
$regex = sprintf( $regex = sprintf(
'/\[%s:.*?\]/ism', '/\[%s:.*?\]/ism',
($categories) ? '(?:' . $categories . ')' : '(?:\w+)' ($categories) ? '(?:' . $categories . ')' : '(?:\w+)'
); );
preg_match_all($regex, $content, $shortcodes); preg_match_all($regex, $content, $shortcodes);
$shortcodes = $shortcodes[0]; $shortcodes = $shortcodes[0];
return (count($shortcodes)) ? return (count($shortcodes)) ?
array_unique($shortcodes) : array_unique($shortcodes) :
false; false;
} }
function match($shortcode) { function match($shortcode) {
preg_match( preg_match(
'/\[(?P<category>\w+)?:(?P<action>\w+)(?:.*?\|.*?default:(?P<default>.*?))?\]/', '/\[(?P<category>\w+)?:(?P<action>\w+)(?:.*?\|.*?default:(?P<default>.*?))?\]/',
$shortcode, $shortcode,
$match $match
); );
return $match; return $match;
} }
function process($shortcodes, $content = false) { function process($shortcodes, $content = false) {
$processed_shortcodes = array_map( $processed_shortcodes = array_map(
function($shortcode) use ($content) { function($shortcode) use ($content) {
$shortcode_details = $this->match($shortcode); $shortcode_details = $this->match($shortcode);
$shortcode_category = !empty($shortcode_details['category']) ? $shortcode_category = !empty($shortcode_details['category']) ?
ucfirst($shortcode_details['category']) : ucfirst($shortcode_details['category']) :
false; false;
$shortcode_action = !empty($shortcode_details['action']) ? $shortcode_action = !empty($shortcode_details['action']) ?
$shortcode_details['action'] : $shortcode_details['action'] :
false; false;
$shortcode_class = $shortcode_class =
self::SHORTCODE_CATEGORY_NAMESPACE . $shortcode_category; self::SHORTCODE_CATEGORY_NAMESPACE . $shortcode_category;
$shortcode_default_value = !empty($shortcode_details['default']) ? $shortcode_default_value = !empty($shortcode_details['default']) ?
$shortcode_details['default'] : $shortcode_details['default'] :
false; false;
if(!class_exists($shortcode_class)) { if(!class_exists($shortcode_class)) {
$custom_shortcode = apply_filters( $custom_shortcode = apply_filters(
'mailpoet_newsletter_shortcode', 'mailpoet_newsletter_shortcode',
$shortcode, $shortcode,
$this->newsletter, $this->newsletter,
$this->subscriber, $this->subscriber,
$this->queue, $this->queue,
$content $content
); );
return ($custom_shortcode === $shortcode) ? return ($custom_shortcode === $shortcode) ?
false : false :
$custom_shortcode; $custom_shortcode;
} }
return $shortcode_class::process( return $shortcode_class::process(
$shortcode_action, $shortcode_action,
$shortcode_default_value, $shortcode_default_value,
$this->newsletter, $this->newsletter,
$this->subscriber, $this->subscriber,
$this->queue, $this->queue,
$content $content
); );
}, $shortcodes); }, $shortcodes);
return $processed_shortcodes; return $processed_shortcodes;
} }
function replace($content, $categories = false) { function replace($content, $categories = false) {
$shortcodes = $this->extract($content, $categories); $shortcodes = $this->extract($content, $categories);
if(!$shortcodes) { if(!$shortcodes) {
return $content; return $content;
} }
$processed_shortcodes = $this->process($shortcodes, $content); $processed_shortcodes = $this->process($shortcodes, $content);
$shortcodes = array_intersect_key($shortcodes, $processed_shortcodes); $shortcodes = array_intersect_key($shortcodes, $processed_shortcodes);
return str_replace($shortcodes, $processed_shortcodes, $content); return str_replace($shortcodes, $processed_shortcodes, $content);
} }
} }

View File

@ -1,103 +1,103 @@
<?php <?php
namespace MailPoet\Router; namespace MailPoet\Router;
use \MailPoet\Util\Security; use \MailPoet\Util\Security;
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
class Router { class Router {
function __construct() { function __construct() {
} }
function init() { function init() {
// security token // security token
add_action( add_action(
'admin_head', 'admin_head',
array($this, 'setToken') array($this, 'setToken')
); );
// Admin API (Ajax only) // Admin API (Ajax only)
add_action( add_action(
'wp_ajax_mailpoet', 'wp_ajax_mailpoet',
array($this, 'setupAdmin') array($this, 'setupAdmin')
); );
// Public API (Ajax) // Public API (Ajax)
add_action( add_action(
'wp_ajax_nopriv_mailpoet', 'wp_ajax_nopriv_mailpoet',
array($this, 'setupPublic') array($this, 'setupPublic')
); );
// Public API (Post) // Public API (Post)
add_action( add_action(
'admin_post_nopriv_mailpoet', 'admin_post_nopriv_mailpoet',
array($this, 'setupPublic') array($this, 'setupPublic')
); );
} }
function setupAdmin() { function setupAdmin() {
$this->verifyToken(); $this->verifyToken();
$this->checkPermissions(); $this->checkPermissions();
return $this->processRoute(); return $this->processRoute();
} }
function setupPublic() { function setupPublic() {
$this->verifyToken(); $this->verifyToken();
return $this->processRoute(); return $this->processRoute();
} }
function processRoute() { function processRoute() {
$class = ucfirst($_POST['endpoint']); $class = ucfirst($_POST['endpoint']);
$endpoint = __NAMESPACE__ . "\\" . $class; $endpoint = __NAMESPACE__ . "\\" . $class;
$method = $_POST['method']; $method = $_POST['method'];
$doing_ajax = (bool)(defined('DOING_AJAX') && DOING_AJAX); $doing_ajax = (bool)(defined('DOING_AJAX') && DOING_AJAX);
if($doing_ajax) { if($doing_ajax) {
$data = isset($_POST['data']) ? stripslashes_deep($_POST['data']) : array(); $data = isset($_POST['data']) ? stripslashes_deep($_POST['data']) : array();
} else { } else {
$data = $_POST; $data = $_POST;
} }
if(is_array($data) && !empty($data)) { if(is_array($data) && !empty($data)) {
// filter out reserved keywords from data // filter out reserved keywords from data
$reserved_keywords = array( $reserved_keywords = array(
'token', 'token',
'endpoint', 'endpoint',
'method', 'method',
'mailpoet_redirect' 'mailpoet_redirect'
); );
$data = array_diff_key($data, array_flip($reserved_keywords)); $data = array_diff_key($data, array_flip($reserved_keywords));
} }
try { try {
$endpoint = new $endpoint(); $endpoint = new $endpoint();
$response = $endpoint->$method($data); $response = $endpoint->$method($data);
wp_send_json($response); wp_send_json($response);
} catch(\Exception $e) { } catch(\Exception $e) {
error_log($e->getMessage()); error_log($e->getMessage());
exit; exit;
} }
} }
function setToken() { function setToken() {
$global = '<script type="text/javascript">'; $global = '<script type="text/javascript">';
$global .= 'var mailpoet_token = "'.Security::generateToken().'";'; $global .= 'var mailpoet_token = "'.Security::generateToken().'";';
$global .= '</script>'; $global .= '</script>';
echo $global; echo $global;
} }
function checkPermissions() { function checkPermissions() {
if(!current_user_can('manage_options')) { if(!current_user_can('manage_options')) {
die(); die();
} }
} }
function verifyToken() { function verifyToken() {
if( if(
empty($_POST['token']) empty($_POST['token'])
|| ||
!wp_verify_nonce($_POST['token'], 'mailpoet_token') !wp_verify_nonce($_POST['token'], 'mailpoet_token')
) { ) {
die(); die();
} }
} }
} }

View File

@ -1,26 +1,26 @@
<?php <?php
namespace MailPoet\Router; namespace MailPoet\Router;
use \MailPoet\Models\Setting; use \MailPoet\Models\Setting;
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
class Settings { class Settings {
function __construct() { function __construct() {
} }
function get() { function get() {
$settings = Setting::getAll(); $settings = Setting::getAll();
return $settings; return $settings;
} }
function set($settings = array()) { function set($settings = array()) {
if(empty($settings)) { if(empty($settings)) {
return false; return false;
} else { } else {
foreach($settings as $name => $value) { foreach($settings as $name => $value) {
Setting::setValue($name, $value); Setting::setValue($name, $value);
} }
return true; return true;
} }
} }
} }