Numerous fixes following the code review:

H1 title should be "Welcome to MailPoet version 3!", as per wireframes
remove logo in top right of the page
remove the classes feature-section one-col to the parent
new styles for #logger
progress bar: ensure that the color and size for the font are the same as our current progress bar.
display the progress bar at 100% when the import of subscribers and lists is complete
move loadSQL() function in tests/_support/Helper/Database.php
remove CSS browser prefixes
use AMD module definition to embed the JavaScript
remove extra whitespace in JavaScript file
remove the redundant functions descriptions
rename objectPlugin to mailpoet_mp2_migrator
replace private $chunks_size by the constant CHUNK_SIZE
add the constant IMPORT_TIMEOUT_IN_SECONDS
replace Helpers::mysqlDate() by $datetime->formatTime(time(), \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT)
make the log messages translatable
fix PHPDoc
replace Env::$plugin_name by 'mailpoet' in the translation functions
use $snake_case for variable names, use lowercaseCamelCase for method names, use CamelCase for class names
define MP2 table names as constants
add spaces around ternary operators
use the models for MP3 entities, instead of counting via raw SQL queries
use \ORM::for_table('some_table')::count()
This commit is contained in:
fred
2017-05-17 17:35:42 +02:00
parent 707d5efec1
commit c78933f7c4
8 changed files with 233 additions and 252 deletions

View File

@ -21,13 +21,8 @@ progressbar_gradient_to_color = #fd9215
.ui-progressbar .ui-progressbar-value
height: 100%
background-color: progressbar_color
background-image: -webkit-linear-gradient(top, progressbar_color, progressbar_gradient_to_color)
background-image: -moz-linear-gradient(top, progressbar_color, progressbar_gradient_to_color)
background-image: -o-linear-gradient(top, progressbar_color, progressbar_gradient_to_color)
background-image: -ms-linear-gradient(top, progressbar_color, progressbar_gradient_to_color)
background-image: linear-gradient(to bottom, progressbar_color, progressbar_gradient_to_color)
border-radius: 3px
-webkit-box-shadow: 0 1px 0 rgba(255,255,255,0.5) inset
box-shadow: 0 1px 0 rgba(255,255,255,0.5) inset
border 0

View File

@ -1,48 +1,34 @@
(function ($) {
define('mp2migrator', ['mailpoet', 'jquery'], function(MailPoet, jQuery) {
'use strict';
MailPoet.MP2Migrator = {
var that;
var mailpoet_import = {
fatal_error: '',
is_logging: false,
/**
* Start the logger
*/
start_logger: function () {
that.is_logging = true;
clearTimeout(that.display_logs_timeout);
clearTimeout(that.update_progressbar_timeout);
clearTimeout(that.update_wordpress_info_timeout);
that.update_display();
startLogger: function () {
MailPoet.MP2Migrator.is_logging = true;
clearTimeout(MailPoet.MP2Migrator.displayLogs_timeout);
clearTimeout(MailPoet.MP2Migrator.updateProgressbar_timeout);
clearTimeout(MailPoet.MP2Migrator.update_wordpress_info_timeout);
MailPoet.MP2Migrator.updateDisplay();
},
/**
* Stop the logger
*/
stop_logger: function () {
that.is_logging = false;
stopLogger: function () {
MailPoet.MP2Migrator.is_logging = false;
},
/**
* Update the display
*/
update_display: function () {
that.display_logs();
that.update_progressbar();
updateDisplay: function () {
MailPoet.MP2Migrator.displayLogs();
MailPoet.MP2Migrator.updateProgressbar();
},
/**
* Display the logs
*/
display_logs: function () {
$.ajax({
url: objectPlugin.log_file_url,
displayLogs: function () {
jQuery.ajax({
url: mailpoet_mp2_migrator.log_file_url,
cache: false
}).done(function (result) {
$('#action_message').html(''); // Clear the action message
$("#logger").html('');
jQuery('#action_message').html(''); // Clear the action message
jQuery("#logger").html('');
result.split("\n").forEach(function (row) {
if(row.substr(0, 7) === '[ERROR]' || row.substr(0, 9) === '[WARNING]' || row === 'IMPORT STOPPED BY USER') {
row = '<span class="error_msg">' + row + '</span>'; // Mark the errors in red
@ -50,56 +36,48 @@
// Test if the import is complete
else if(row === 'IMPORT COMPLETE') {
row = '<span class="complete_msg">' + row + '</span>'; // Mark the complete message in green
$('#action_message').html(MailPoet.I18n.t('import_complete'))
jQuery('#action_message').html(MailPoet.I18n.t('import_complete'))
.removeClass('failure').addClass('success');
}
$("#logger").append(row + "<br />\n");
jQuery("#logger").append(row + "<br />\n");
});
$("#logger").append('<span class="error_msg">' + that.fatal_error + '</span>' + "<br />\n");
jQuery("#logger").append('<span class="error_msg">' + MailPoet.MP2Migrator.fatal_error + '</span>' + "<br />\n");
}).always(function () {
if(that.is_logging) {
that.display_logs_timeout = setTimeout(that.display_logs, 1000);
if(MailPoet.MP2Migrator.is_logging) {
MailPoet.MP2Migrator.displayLogs_timeout = setTimeout(MailPoet.MP2Migrator.displayLogs, 1000);
}
});
},
/**
* Update the progressbar
*/
update_progressbar: function () {
$.ajax({
url: objectPlugin.progress_url,
updateProgressbar: function () {
jQuery.ajax({
url: mailpoet_mp2_migrator.progress_url,
cache: false,
dataType: 'json'
}).always(function (result) {
// Move the progress bar
var progress = Math.round(Number(result.current) / Number(result.total) * 100);
$('#progressbar').progressbar('option', 'value', progress);
$('#progresslabel').html(progress + '%');
if(that.is_logging) {
that.update_progressbar_timeout = setTimeout(that.update_progressbar, 1000);
jQuery('#progressbar').progressbar('option', 'value', progress);
jQuery('#progresslabel').html(progress + '%');
if(MailPoet.MP2Migrator.is_logging) {
MailPoet.MP2Migrator.updateProgressbar_timeout = setTimeout(MailPoet.MP2Migrator.updateProgressbar, 1000);
}
});
},
/**
* Start the import
*
* @returns {Boolean}
*/
start_import: function () {
that.fatal_error = '';
startImport: function () {
MailPoet.MP2Migrator.fatal_error = '';
// Start displaying the logs
that.start_logger();
MailPoet.MP2Migrator.startLogger();
// Disable the import button
that.import_button_label = $('#import').val();
$('#import').val(MailPoet.I18n.t('importing')).attr('disabled', 'disabled');
MailPoet.MP2Migrator.import_button_label = jQuery('#import').val();
jQuery('#import').val(MailPoet.I18n.t('importing')).attr('disabled', 'disabled');
// Show the stop button
$('#stop-import').show();
jQuery('#stop-import').show();
// Clear the action message
$('#action_message').html('');
jQuery('#action_message').html('');
// Run the import
MailPoet.Ajax.post({
@ -109,12 +87,12 @@
data: {
}
}).always(function () {
that.stop_logger();
that.update_display(); // Get the latest information after the import was stopped
that.reactivate_import_button();
MailPoet.MP2Migrator.stopLogger();
MailPoet.MP2Migrator.updateDisplay(); // Get the latest information after the import was stopped
MailPoet.MP2Migrator.reactivateImportButton();
}).done(function (response) {
if(response) {
that.fatal_error = response.data;
MailPoet.MP2Migrator.fatal_error = response.data;
}
}).fail(function (response) {
if(response.errors.length > 0) {
@ -129,22 +107,13 @@
return false;
},
/**
* Reactivate the import button
*
*/
reactivate_import_button: function () {
$('#import').val(that.import_button_label).removeAttr('disabled');
$('#stop-import').hide();
reactivateImportButton: function () {
jQuery('#import').val(MailPoet.MP2Migrator.import_button_label).removeAttr('disabled');
jQuery('#stop-import').hide();
},
/**
* Stop the import
*
* @returns {Boolean}
*/
stop_import: function () {
$('#stop-import').attr('disabled', 'disabled');
stopImport: function () {
jQuery('#stop-import').attr('disabled', 'disabled');
// Stop the import
MailPoet.Ajax.post({
api_version: window.mailpoet_api_version,
@ -153,20 +122,15 @@
data: {
}
}).always(function () {
$('#stop-import').removeAttr('disabled'); // Enable the button
that.reactivate_import_button();
that.update_display(); // Get the latest information after the import was stopped
jQuery('#stop-import').removeAttr('disabled'); // Enable the button
MailPoet.MP2Migrator.reactivateImportButton();
MailPoet.MP2Migrator.updateDisplay(); // Get the latest information after the import was stopped
});
that.stop_logger();
MailPoet.MP2Migrator.stopLogger();
return false;
},
/**
* Skip the import
*
* @returns {Boolean}
*/
skip_import: function () {
skipImport: function () {
MailPoet.Ajax.post({
api_version: window.mailpoet_api_version,
endpoint: 'MP2Migrator',
@ -184,19 +148,23 @@
/**
* Actions to run when the DOM is ready
*/
$(function () {
that = mailpoet_import;
$('#progressbar').progressbar({value: 0});
jQuery(function () {
jQuery('#progressbar').progressbar({value: 0});
// Import button
$('#import').click(that.start_import);
jQuery('#import').click(function() {
MailPoet.MP2Migrator.startImport();
});
// Stop import button
$('#stop-import').click(that.stop_import);
jQuery('#stop-import').click(function() {
MailPoet.MP2Migrator.stopImport();
});
// Skip import link
$('#skip-import').click(that.skip_import);
jQuery('#skip-import').click(function() {
MailPoet.MP2Migrator.skipImport();
});
});
})(jQuery);
});

View File

@ -11,24 +11,52 @@ use MailPoet\Models\SubscriberSegment;
use MailPoet\Models\SubscriberCustomField;
use MailPoet\Models\ImportedDataMapping;
use MailPoet\Config\Activator;
use MailPoet\Util\Helpers;
if(!defined('ABSPATH')) exit;
class MP2Migrator {
const IMPORT_TIMEOUT_IN_SECONDS = 7200; // Timeout = 2 hours
const CHUNK_SIZE = 10; // To import the data by batch
private $log_file;
public $log_file_url;
public $progressbar;
private $chunks_size = 10; // To import the data by batch
public function __construct() {
$this->defineMP2Tables();
$log_filename = 'mp2migration.log';
$this->log_file = Env::$temp_path . '/' . $log_filename;
$this->log_file_url = Env::$temp_url . '/' . $log_filename;
$this->progressbar = new ProgressBar('mp2migration');
}
private function defineMP2Tables() {
global $wpdb;
if(!defined('MP2_CAMPAIGN_TABLE')) {
define('MP2_CAMPAIGN_TABLE', $wpdb->prefix . 'wysija_campaign');
}
if(!defined('MP2_CUSTOM_FIELD_TABLE')) {
define('MP2_CUSTOM_FIELD_TABLE', $wpdb->prefix . 'wysija_custom_field');
}
if(!defined('MP2_EMAIL_TABLE')) {
define('MP2_EMAIL_TABLE', $wpdb->prefix . 'wysija_email');
}
if(!defined('MP2_FORM_TABLE')) {
define('MP2_FORM_TABLE', $wpdb->prefix . 'wysija_form');
}
if(!defined('MP2_LIST_TABLE')) {
define('MP2_LIST_TABLE', $wpdb->prefix . 'wysija_list');
}
if(!defined('MP2_USER_TABLE')) {
define('MP2_USER_TABLE', $wpdb->prefix . 'wysija_user');
}
if(!defined('MP2_USER_LIST_TABLE')) {
define('MP2_USER_LIST_TABLE', $wpdb->prefix . 'wysija_user_list');
}
}
/**
* Test if the migration is needed
*
@ -38,7 +66,7 @@ class MP2Migrator {
if(Setting::getValue('mailpoet_migration_complete')) {
return false;
} else {
return $this->tableExists('wysija_campaign'); // Check if the MailPoet 2 tables exist
return $this->tableExists(MP2_CAMPAIGN_TABLE); // Check if the MailPoet 2 tables exist
}
}
@ -60,7 +88,7 @@ class MP2Migrator {
global $wpdb;
try {
$sql = "SHOW TABLES LIKE '{$wpdb->prefix}{$table}'";
$sql = "SHOW TABLES LIKE '{$table}'";
$result = $wpdb->query($sql);
return !empty($result);
} catch (Exception $e) {
@ -83,8 +111,7 @@ class MP2Migrator {
*
*/
private function enqueueScripts() {
wp_register_script('mp2migrator', Env::$assets_url . '/js/mp2migrator.js', array('jquery-ui-progressbar'));
wp_enqueue_script('mp2migrator');
wp_enqueue_script('jquery-ui-progressbar');
}
/**
@ -99,13 +126,14 @@ class MP2Migrator {
/**
* Import the data from MailPoet 2
*
* @return boolean Result
* @return string Result
*/
public function import() {
set_time_limit(7200); // Timeout = 2 hours
set_time_limit(IMPORT_TIMEOUT_IN_SECONDS);
ob_start();
$this->emptyLog();
$this->log(sprintf("=== START IMPORT %s ===", date('Y-m-d H:i:s')));
$datetime = new \MailPoet\WP\DateTime();
$this->log(sprintf('=== ' . __('START IMPORT', 'mailpoet') . ' %s ===', $datetime->formatTime(time(), \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT)));
Setting::setValue('import_stopped', false); // Reset the stop import action
$this->eraseMP3Data();
@ -115,7 +143,7 @@ class MP2Migrator {
$this->importCustomFields();
$this->importSubscribers();
$this->log(sprintf("=== END IMPORT %s ===", date('Y-m-d H:i:s')));
$this->log(sprintf('=== ' . __('END IMPORT', 'mailpoet') . ' %s ===', $datetime->formatTime(time(), \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT)));
$result = ob_get_contents();
ob_clean();
return $result;
@ -137,7 +165,7 @@ class MP2Migrator {
Activator::deactivate();
Activator::activate();
$this->resetMigrationCounters();
$this->log(__("MailPoet data erased", Env::$plugin_name));
$this->log(__("MailPoet data erased", 'mailpoet'));
}
/**
@ -155,7 +183,7 @@ class MP2Migrator {
*/
public function stopImport() {
Setting::setValue('import_stopped', true);
$this->log(__('IMPORT STOPPED BY USER', Env::$plugin_name));
$this->log(__('IMPORT STOPPED BY USER', 'mailpoet'));
}
/**
@ -183,33 +211,36 @@ class MP2Migrator {
*/
private function getDataToMigrate() {
$result = '';
$totalCount = 0;
$total_count = 0;
$this->progressbar->setTotalCount(0);
$result .= __('MailPoet 2 data found:', Env::$plugin_name) . "\n";
$result .= __('MailPoet 2 data found:', 'mailpoet') . "\n";
// User Lists
$usersListsCount = Helpers::rowsCount('wysija_list');
$totalCount += $usersListsCount;
$result .= sprintf(_n('%d subscribers list', '%d subscribers lists', $usersListsCount, Env::$plugin_name), $usersListsCount) . "\n";
$users_lists_count = \ORM::for_table(MP2_LIST_TABLE)->count();
$total_count += $users_lists_count;
$result .= sprintf(_n('%d subscribers list', '%d subscribers lists', $users_lists_count, 'mailpoet'), $users_lists_count) . "\n";
// Users
$usersCount = Helpers::rowsCount('wysija_user');
$totalCount += $usersCount;
$result .= sprintf(_n('%d subscriber', '%d subscribers', $usersCount, Env::$plugin_name), $usersCount) . "\n";
$users_count = \ORM::for_table(MP2_USER_TABLE)->count();
$total_count += $users_count;
$result .= sprintf(_n('%d subscriber', '%d subscribers', $users_count, 'mailpoet'), $users_count) . "\n";
// TODO to reactivate during the next phases
/*
// Emails
$emailsCount = Helpers::rowsCount('wysija_email');
$totalCount += $emailsCount;
$result .= sprintf(_n('%d newsletter', '%d newsletters', $emailsCount, Env::$plugin_name), $emailsCount) . "\n";
$emails_count = \ORM::for_table(MP2_EMAIL_TABLE)->count();
$total_count += $emails_count;
$result .= sprintf(_n('%d newsletter', '%d newsletters', $emails_count, 'mailpoet'), $emails_count) . "\n";
// Forms
$formsCount = Helpers::rowsCount('wysija_form');
$totalCount += $formsCount;
$result .= sprintf(_n('%d form', '%d forms', $formsCount, Env::$plugin_name), $formsCount) . "\n";
$forms_count = \ORM::for_table(MP2_FORM_TABLE)->count();
$total_count += $forms_count;
$result .= sprintf(_n('%d form', '%d forms', $forms_count, 'mailpoet'), $forms_count) . "\n";
*/
$this->progressbar->setTotalCount($totalCount);
$this->progressbar->setTotalCount($total_count);
return $result;
}
@ -223,12 +254,12 @@ class MP2Migrator {
if($this->importStopped()) {
return;
}
$this->log(__("Importing segments...", Env::$plugin_name));
$this->log(__("Importing segments...", 'mailpoet'));
do {
if($this->importStopped()) {
break;
}
$lists = $this->getLists($this->chunks_size);
$lists = $this->getLists(self::CHUNK_SIZE);
$lists_count = count($lists);
if(is_array($lists)) {
@ -242,7 +273,7 @@ class MP2Migrator {
$this->progressbar->incrementCurrentCount($lists_count);
} while(($lists != null) && ($lists_count > 0));
$this->log(sprintf(_n("%d segment imported", "%d segments imported", $imported_segments_count, Env::$plugin_name), $imported_segments_count));
$this->log(sprintf(_n("%d segment imported", "%d segments imported", $imported_segments_count, 'mailpoet'), $imported_segments_count));
}
/**
@ -257,7 +288,7 @@ class MP2Migrator {
$lists = array();
$last_id = Setting::getValue('last_imported_list_id', 0);
$table = $wpdb->prefix . 'wysija_list';
$table = MP2_LIST_TABLE;
$sql = "
SELECT l.list_id, l.name, l.description, l.is_enabled, l.created_at
FROM `$table` l
@ -277,12 +308,13 @@ class MP2Migrator {
* @return Segment
*/
private function importSegment($list_data) {
$datetime = new \MailPoet\WP\DateTime();
$segment = Segment::createOrUpdate(array(
'id' => $list_data['list_id'],
'name' => $list_data['name'],
'type' => $list_data['is_enabled']? 'default': 'wp_users',
'type' => $list_data['is_enabled'] ? 'default' : 'wp_users',
'description' => $list_data['description'],
'created_at' => Helpers::mysqlDate($list_data['created_at']),
'created_at' => $datetime->formatTime($list_data['created_at'], \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT),
));
Setting::setValue('last_imported_list_id', $list_data['list_id']);
return $segment;
@ -297,7 +329,7 @@ class MP2Migrator {
if($this->importStopped()) {
return;
}
$this->log(__("Importing custom fields...", Env::$plugin_name));
$this->log(__("Importing custom fields...", 'mailpoet'));
$custom_fields = $this->getCustomFields();
foreach($custom_fields as $custom_field) {
@ -307,7 +339,7 @@ class MP2Migrator {
}
}
$this->log(sprintf(_n("%d custom field imported", "%d custom fields imported", $imported_custom_fields_count, Env::$plugin_name), $imported_custom_fields_count));
$this->log(sprintf(_n("%d custom field imported", "%d custom fields imported", $imported_custom_fields_count, 'mailpoet'), $imported_custom_fields_count));
}
/**
@ -320,7 +352,7 @@ class MP2Migrator {
global $wpdb;
$custom_fields = array();
$table = $wpdb->prefix . 'wysija_custom_field';
$table = MP2_CUSTOM_FIELD_TABLE;
$sql = "
SELECT cf.id, cf.name, cf.type, cf.required, cf.settings
FROM `$table` cf
@ -343,25 +375,25 @@ class MP2Migrator {
'type' => $this->mapCustomFieldType($custom_field['type']),
'params' => $this->mapCustomFieldParams($custom_field),
);
$customField = new CustomField();
$customField->createOrUpdate($data);
return $customField;
$custom_field = new CustomField();
$custom_field->createOrUpdate($data);
return $custom_field;
}
/**
* Map the MailPoet 2 custom field type with the MailPoet custom field type
*
* @param string $MP2type MP2 custom field type
* @param string $mp2_type MP2 custom field type
* @return string MP3 custom field type
*/
private function mapCustomFieldType($MP2type) {
private function mapCustomFieldType($mp2_type) {
$type = '';
switch($MP2type) {
switch($mp2_type) {
case 'input':
$type = 'text';
break;
default:
$type = $MP2type;
$type = $mp2_type;
}
return $type;
}
@ -388,12 +420,12 @@ class MP2Migrator {
/**
* Map the validate value
*
* @param string $MP2value MP2 value
* @param string $mp2_value MP2 value
* @return string MP3 value
*/
private function mapCustomFieldValidateValue($MP2value) {
private function mapCustomFieldValidateValue($mp2_value) {
$value = '';
switch($MP2value) {
switch($mp2_value) {
case 'onlyLetterSp':
case 'onlyLetterNumber':
$value = 'alphanum';
@ -417,12 +449,12 @@ class MP2Migrator {
if($this->importStopped()) {
return;
}
$this->log(__("Importing subscribers...", Env::$plugin_name));
$this->log(__("Importing subscribers...", 'mailpoet'));
do {
if($this->importStopped()) {
break;
}
$users = $this->getUsers($this->chunks_size);
$users = $this->getUsers(self::CHUNK_SIZE);
$users_count = count($users);
if(is_array($users)) {
@ -438,7 +470,7 @@ class MP2Migrator {
$this->progressbar->incrementCurrentCount($users_count);
} while(($users != null) && ($users_count > 0));
$this->log(sprintf(_n("%d subscriber imported", "%d subscribers imported", $imported_subscribers_count, Env::$plugin_name), $imported_subscribers_count));
$this->log(sprintf(_n("%d subscriber imported", "%d subscribers imported", $imported_subscribers_count, 'mailpoet'), $imported_subscribers_count));
}
/**
@ -453,7 +485,7 @@ class MP2Migrator {
$users = array();
$last_id = Setting::getValue('last_imported_user_id', 0);
$table = $wpdb->prefix . 'wysija_user';
$table = MP2_USER_TABLE;
$sql = "
SELECT u.*
FROM `$table` u
@ -473,17 +505,18 @@ class MP2Migrator {
* @return Subscriber
*/
private function importSubscriber($user_data) {
$datetime = new \MailPoet\WP\DateTime();
$subscriber = Subscriber::createOrUpdate(array(
'id' => $user_data['user_id'],
'wp_user_id' => !empty($user_data['wpuser_id'])? $user_data['wpuser_id'] : null,
'wp_user_id' => !empty($user_data['wpuser_id']) ? $user_data['wpuser_id'] : null,
'email' => $user_data['email'],
'first_name' => $user_data['firstname'],
'last_name' => $user_data['lastname'],
'status' => $this->mapUserStatus($user_data['status']),
'created_at' => Helpers::mysqlDate($user_data['created_at']),
'subscribed_ip' => !empty($user_data['ip'])? $user_data['ip'] : null,
'confirmed_ip' => !empty($user_data['confirmed_ip'])? $user_data['confirmed_ip'] : null,
'confirmed_at' => !empty($user_data['confirmed_at'])? Helpers::mysqlDate($user_data['confirmed_at']) : null,
'created_at' => $datetime->formatTime($user_data['created_at'], \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT),
'subscribed_ip' => !empty($user_data['ip']) ? $user_data['ip'] : null,
'confirmed_ip' => !empty($user_data['confirmed_ip']) ? $user_data['confirmed_ip'] : null,
'confirmed_at' => !empty($user_data['confirmed_at']) ? $datetime->formatTime($user_data['confirmed_at'], \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT) : null,
));
Setting::setValue('last_imported_user_id', $user_data['user_id']);
if(!empty($subscriber)) {
@ -492,7 +525,7 @@ class MP2Migrator {
'old_id' => $user_data['user_id'],
'type' => 'subscribers',
'new_id' => $subscriber->id,
'created_at' => Helpers::mysqlDate(time()),
'created_at' => $datetime->formatTime(time(), \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT),
));
}
return $subscriber;
@ -545,7 +578,7 @@ class MP2Migrator {
global $wpdb;
$user_lists = array();
$table = $wpdb->prefix . 'wysija_user_list';
$table = MP2_USER_LIST_TABLE;
$sql = "
SELECT ul.list_id, ul.sub_date, ul.unsub_date
FROM `$table` ul
@ -564,16 +597,17 @@ class MP2Migrator {
* @return SubscriberSegment
*/
private function importSubscriberSegment($subscriber_id, $user_list) {
$datetime = new \MailPoet\WP\DateTime();
$data = array(
'subscriber_id' => $subscriber_id,
'segment_id' => $user_list['list_id'],
'status' => empty($user_list['unsub_date'])? 'subscribed' : 'unsubscribed',
'created_at' => Helpers::mysqlDate($user_list['sub_date']),
'updated_at' => !empty($user_list['unsub_date'])? Helpers::mysqlDate($user_list['unsub_date']) : null,
'status' => empty($user_list['unsub_date']) ? 'subscribed' : 'unsubscribed',
'created_at' => $datetime->formatTime($user_list['sub_date'], \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT),
'updated_at' => !empty($user_list['unsub_date']) ? $datetime->formatTime($user_list['unsub_date'], \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT) : null,
);
$subscriberSegment = new SubscriberSegment();
$subscriberSegment->createOrUpdate($data);
return $subscriberSegment;
$subscriber_segment = new SubscriberSegment();
$subscriber_segment->createOrUpdate($data);
return $subscriber_segment;
}
/**
@ -620,18 +654,19 @@ class MP2Migrator {
*/
private function importSubscriberCustomField($subscriber_id, $custom_field, $custom_field_value) {
if($custom_field['type'] == 'date') {
$value = Helpers::mysqlDate($custom_field_value); // Convert the date field
$datetime = new \MailPoet\WP\DateTime();
$value = $datetime->formatTime($custom_field_value, \MailPoet\WP\DateTime::DEFAULT_DATE_TIME_FORMAT); // Convert the date field
} else {
$value = $custom_field_value;
}
$data = array(
'subscriber_id' => $subscriber_id,
'custom_field_id' => $custom_field['id'],
'value' => isset($value)? $value : '',
'value' => isset($value) ? $value : '',
);
$subscriberCustomField = new SubscriberCustomField();
$subscriberCustomField->createOrUpdate($data);
return $subscriberCustomField;
$subscriber_custom_field = new SubscriberCustomField();
$subscriber_custom_field->createOrUpdate($data);
return $subscriber_custom_field;
}
/**

View File

@ -1,6 +1,5 @@
<?php
namespace MailPoet\Util;
use MailPoet\Config\Env;
class Helpers {
const DIVIDER = '***MailPoet***';
@ -138,47 +137,4 @@ class Helpers {
return explode(self::DIVIDER, $object);
}
/**
* Convert a timestamp to a Mysql datetime
*
* @param int $timestamp Timestamp
* @return string Datetime
*/
static public function mysqlDate($timestamp) {
return date('Y-m-d H:i:s', $timestamp);
}
/**
* Count the number of rows in a table
*
* @global object $wpdb
* @param string $table Table
* @param bool $withoutPrefix Table name without DB prefix
* @return int Number of rows found
*/
static public function rowsCount($table, $withoutPrefix=true) {
global $wpdb;
if($withoutPrefix) {
$table = $wpdb->prefix . $table;
}
$sql = "SELECT COUNT(*) FROM `$table`";
$count = $wpdb->get_var($sql);
return $count;
}
/**
* Load a SQL file
*
* @param string $filename Filename without extension
*/
static public function loadSQL($filename) {
$db = \ORM::getDb();
$full_filename = Env::$path . '/tests/_data/' . $filename . '.sql';
$sql = file_get_contents($full_filename);
$db->exec($sql);
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace Helper;
use MailPoet\Config\Env;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
class Database extends \Codeception\Module
{
/**
* Load a SQL file
*
* @param string $filename Filename without extension
*/
static public function loadSQL($filename) {
$db = \ORM::getDb();
$full_filename = Env::$path . '/tests/_data/' . $filename . '.sql';
$sql = file_get_contents($full_filename);
$db->exec($sql);
}
}

View File

@ -1,8 +1,13 @@
<?php
use MailPoet\Config\MP2Migrator;
use MailPoet\Models\Setting;
use MailPoet\Util\Helpers;
use MailPoet\Models\CustomField;
use MailPoet\Models\ImportedDataMapping;
use MailPoet\Models\Segment;
use MailPoet\Models\Subscriber;
use MailPoet\Models\SubscriberCustomField;
use MailPoet\Models\SubscriberSegment;
use Helper\Database;
class MP2MigratorTest extends MailPoetTest {
@ -18,11 +23,11 @@ class MP2MigratorTest extends MailPoetTest {
*
*/
public function testIsMigrationNeeded() {
Helpers::loadSQL('dropMP2Tables');
Database::loadSQL('dropMP2Tables');
$result = $this->MP2Migrator->isMigrationNeeded();
expect($result)->false();
Helpers::loadSQL('createMP2Tables');
Database::loadSQL('createMP2Tables');
$result = $this->MP2Migrator->isMigrationNeeded();
expect($result)->true();
}
@ -40,20 +45,19 @@ class MP2MigratorTest extends MailPoetTest {
*
*/
public function testEraseMP3Data() {
global $wpdb;
$this->invokeMethod($this->MP2Migrator, 'eraseMP3Data');
// Check if the subscribers number is equal to the WordPress users number
$MPSubscribersCount = Helpers::rowsCount(MP_SUBSCRIBERS_TABLE, false);
$WPUsersCount = Helpers::rowsCount('users');
expect($MPSubscribersCount)->equals($WPUsersCount);
$WPUsersCount = \ORM::for_table($wpdb->prefix . 'users')->count();
expect(Subscriber::count())->equals($WPUsersCount);
// Check if the custom fields number is 0
$MPCustomFieldsCount = Helpers::rowsCount(MP_CUSTOM_FIELDS_TABLE, false);
expect($MPCustomFieldsCount)->equals(0);
expect(CustomField::count())->equals(0);
// Check if the subscribers custom fields number is 0
$MPSubscribersCustomFieldCount = Helpers::rowsCount(MP_SUBSCRIBER_CUSTOM_FIELD_TABLE, false);
expect($MPSubscribersCustomFieldCount)->equals(0);
expect(SubscriberCustomField::count())->equals(0);
}
/**
@ -88,7 +92,7 @@ class MP2MigratorTest extends MailPoetTest {
*
*/
private function initImport() {
Helpers::loadSQL('createMP2Tables');
Database::loadSQL('createMP2Tables');
$this->invokeMethod($this->MP2Migrator, 'eraseMP3Data');
}
@ -97,7 +101,7 @@ class MP2MigratorTest extends MailPoetTest {
*
*/
private function loadMP2Fixtures() {
Helpers::loadSQL('populateMP2Tables');
Database::loadSQL('populateMP2Tables');
}
/**
@ -112,8 +116,7 @@ class MP2MigratorTest extends MailPoetTest {
$this->initImport();
$this->loadMP2Fixtures();
$this->invokeMethod($this->MP2Migrator, 'importSegments');
$segmentsCount = Helpers::rowsCount(MP_SEGMENTS_TABLE, false);
expect($segmentsCount)->equals(3);
expect(Segment::count())->equals(3);
// Check a segment data
$this->initImport();
@ -149,8 +152,7 @@ class MP2MigratorTest extends MailPoetTest {
$this->initImport();
$this->loadMP2Fixtures();
$this->invokeMethod($this->MP2Migrator, 'importCustomFields');
$customFieldsCount = Helpers::rowsCount(MP_CUSTOM_FIELDS_TABLE, false);
expect($customFieldsCount)->equals(10);
expect(CustomField::count())->equals(10);
// Check a custom field data
$this->initImport();
@ -193,8 +195,7 @@ class MP2MigratorTest extends MailPoetTest {
$this->initImport();
$this->loadMP2Fixtures();
$this->invokeMethod($this->MP2Migrator, 'importSubscribers');
$subscribersCount = Helpers::rowsCount(MP_SUBSCRIBERS_TABLE, false);
expect($subscribersCount)->equals(4);
expect(Subscriber::count())->equals(4);
// Check a subscriber data
$this->initImport();
@ -239,8 +240,7 @@ class MP2MigratorTest extends MailPoetTest {
$this->loadMP2Fixtures();
$this->invokeMethod($this->MP2Migrator, 'importSegments');
$this->invokeMethod($this->MP2Migrator, 'importSubscribers');
$subscribersCount = Helpers::rowsCount(MP_SUBSCRIBER_SEGMENT_TABLE, false);
expect($subscribersCount)->equals(7);
expect(SubscriberSegment::count())->equals(7);
// Check a subscriber segment data
@ -298,8 +298,7 @@ class MP2MigratorTest extends MailPoetTest {
$this->loadMP2Fixtures();
$this->invokeMethod($this->MP2Migrator, 'importCustomFields');
$this->invokeMethod($this->MP2Migrator, 'importSubscribers');
$subscribersCount = Helpers::rowsCount(MP_SUBSCRIBER_CUSTOM_FIELD_TABLE, false);
expect($subscribersCount)->equals(40);
expect(SubscriberCustomField::count())->equals(40);
// Check a subscriber custom field data

View File

@ -38,13 +38,18 @@
</div>
</div>
<% endblock %>
<script type="text/javascript">
var objectPlugin = {
log_file_url: '<%= log_file_url %>',
progress_url: '<%= progress_url %>'
};
</script>
<% block after_javascript %>
<%= javascript(
'mp2migrator.js'
)%>
<script type="text/javascript">
var mailpoet_mp2_migrator = {
log_file_url: '<%= log_file_url %>',
progress_url: '<%= progress_url %>'
};
</script>
<% endblock %>
<% block translations %>

View File

@ -247,7 +247,8 @@ config.push(_.extend({}, baseConfig, {
]
},
externals: {
'jquery': 'jQuery'
'jquery': 'jQuery',
'mailpoet': 'MailPoet'
}
}));