Coding standard fixes

This commit is contained in:
fred
2017-04-15 19:35:52 +02:00
parent dd7f959731
commit a1ea56f505
5 changed files with 294 additions and 298 deletions

View File

@ -1,187 +1,179 @@
(function( $ ) { (function ($) {
'use strict'; 'use strict';
var that; var that;
var mailpoet_import = { var mailpoet_import = {
fatal_error: '',
fatal_error: '', is_logging: false,
is_logging: false,
/**
/** * Start the logger
* Start the logger */
*/ start_logger: function () {
start_logger: function() { that.is_logging = true;
that.is_logging = true; clearTimeout(that.display_logs_timeout);
clearTimeout(that.display_logs_timeout); clearTimeout(that.update_progressbar_timeout);
clearTimeout(that.update_progressbar_timeout); clearTimeout(that.update_wordpress_info_timeout);
clearTimeout(that.update_wordpress_info_timeout); that.update_display();
that.update_display(); },
},
/**
/** * Stop the logger
* Stop the logger */
*/ stop_logger: function () {
stop_logger: function() { that.is_logging = false;
that.is_logging = false; },
},
/**
* Update the display
/** */
* Update the display update_display: function () {
*/ that.display_logs();
update_display: function() { that.update_progressbar();
that.display_logs(); },
that.update_progressbar();
}, /**
* Display the logs
/** */
* Display the logs display_logs: function () {
*/ $.ajax({
display_logs: function() { url: objectPlugin.log_file_url,
$.ajax({ cache: false
url: objectPlugin.log_file_url, }).done(function (result) {
cache: false $('#action_message').html(''); // Clear the action message
}).done(function(result) { $("#logger").html('');
$('#action_message').html(''); // Clear the action message result.split("\n").forEach(function (row) {
$("#logger").html(''); if(row.substr(0, 7) === '[ERROR]' || row.substr(0, 9) === '[WARNING]' || row === 'IMPORT STOPPED BY USER') {
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 row = '<span class="error_msg">' + row + '</span>'; // Mark the errors in red
} }
// Test if the import is complete // Test if the import is complete
else if ( row === 'IMPORT COMPLETE' ) { else if(row === 'IMPORT COMPLETE') {
row = '<span class="complete_msg">' + row + '</span>'; // Mark the complete message in green row = '<span class="complete_msg">' + row + '</span>'; // Mark the complete message in green
$('#action_message').html(MailPoet.I18n.t('import_complete')) $('#action_message').html(MailPoet.I18n.t('import_complete'))
.removeClass('failure').addClass('success'); .removeClass('failure').addClass('success');
} }
$("#logger").append(row + "<br />\n"); $("#logger").append(row + "<br />\n");
});
$("#logger").append('<span class="error_msg">' + that.fatal_error + '</span>' + "<br />\n");
}).always(function() {
if ( that.is_logging ) {
that.display_logs_timeout = setTimeout(that.display_logs, 1000);
}
});
},
/**
* Update the progressbar
*/
update_progressbar: function() {
$.ajax({
url: objectPlugin.progress_url,
cache: false,
dataType: 'json'
}).always(function(result) {
// Move the progress bar
var progress = 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);
}
}); });
}, $("#logger").append('<span class="error_msg">' + that.fatal_error + '</span>' + "<br />\n");
}).always(function () {
if(that.is_logging) {
that.display_logs_timeout = setTimeout(that.display_logs, 1000);
}
});
},
/**
* Update the progressbar
*/
update_progressbar: function () {
$.ajax({
url: objectPlugin.progress_url,
cache: false,
dataType: 'json'
}).always(function (result) {
// Move the progress bar
var progress = 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);
}
});
},
/**
* Start the import
*
* @returns {Boolean}
*/
start_import: function () {
that.fatal_error = '';
// Start displaying the logs
that.start_logger();
/** // Disable the import button
* Start the import that.import_button_label = $('#import').val();
* $('#import').val(MailPoet.I18n.t('importing')).attr('disabled', 'disabled');
* @returns {Boolean} // Show the stop button
*/ $('#stop-import').show();
start_import: function() { // Clear the action message
that.fatal_error = ''; $('#action_message').html('');
// Start displaying the logs
that.start_logger();
// Disable the import button // Run the import
that.import_button_label = $('#import').val(); MailPoet.Ajax.post({
$('#import').val(MailPoet.I18n.t('importing')).attr('disabled', 'disabled'); endpoint: 'MP2MigratorAPI',
// Show the stop button action: 'import',
$('#stop-import').show(); data: {
// Clear the action message }
$('#action_message').html(''); }).always(function () {
// Run the import
MailPoet.Ajax.post({
endpoint: 'MP2MigratorAPI',
action: 'import',
data: {
}
}).always(function() {
that.stop_logger();
that.update_display(); // Get the latest information after the import was stopped
that.reactivate_import_button();
}).done(function(response) {
if (response) {
that.fatal_error = response.data;
}
}).fail(function(response) {
if (response.errors.length > 0) {
MailPoet.Notice.error(
response.errors.map(function(error) { return error.message; }),
{ scroll: true }
);
}
});
return false;
},
/**
* Reactivate the import button
*
*/
reactivate_import_button: function() {
$('#import').val(that.import_button_label).removeAttr('disabled');
$('#stop-import').hide();
},
/**
* Stop import
*
* @returns {Boolean}
*/
stop_import: function() {
$('#stop-import').attr('disabled', 'disabled');
// Stop the import
MailPoet.Ajax.post({
endpoint: 'MP2MigratorAPI',
action: 'stopImport',
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
});
that.stop_logger(); that.stop_logger();
return false; that.update_display(); // Get the latest information after the import was stopped
}, that.reactivate_import_button();
}).done(function (response) {
}; if(response) {
that.fatal_error = response.data;
/** }
* Actions to run when the DOM is ready }).fail(function (response) {
*/ if(response.errors.length > 0) {
$(function() { MailPoet.Notice.error(
that = mailpoet_import; response.errors.map(function (error) {
return error.message;
$('#progressbar').progressbar({value : 0}); }),
{scroll: true}
);
}
});
return false;
},
/**
* Reactivate the import button
*
*/
reactivate_import_button: function () {
$('#import').val(that.import_button_label).removeAttr('disabled');
$('#stop-import').hide();
},
/**
* Stop import
*
* @returns {Boolean}
*/
stop_import: function () {
$('#stop-import').attr('disabled', 'disabled');
// Stop the import
MailPoet.Ajax.post({
endpoint: 'MP2MigratorAPI',
action: 'stopImport',
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
});
that.stop_logger();
return false;
}
// Import button };
$('#import').click(that.start_import);
// Stop import button
$('#stop-import').click(that.stop_import);
});
/** /**
* Actions to run when the window is loaded * Actions to run when the DOM is ready
*/ */
$( window ).load(function() { $(function () {
that = mailpoet_import;
});
})( jQuery ); $('#progressbar').progressbar({value: 0});
// Import button
$('#import').click(that.start_import);
// Stop import button
$('#stop-import').click(that.stop_import);
});
})(jQuery);

View File

@ -35,7 +35,7 @@ class MP2MigratorAPI extends APIEndpoint {
*/ */
public function stopImport($data) { public function stopImport($data) {
try { try {
$process = $this->MP2Migrator->stop_import(); $process = $this->MP2Migrator->stopImport();
return $this->successResponse($process); return $this->successResponse($process);
} catch(\Exception $e) { } catch(\Exception $e) {
return $this->errorResponse(array( return $this->errorResponse(array(

View File

@ -1,4 +1,5 @@
<?php <?php
namespace MailPoet\Config; namespace MailPoet\Config;
use MailPoet\Util\ProgressBar; use MailPoet\Util\ProgressBar;
@ -7,76 +8,78 @@ if(!defined('ABSPATH')) exit;
class MP2Migrator { class MP2Migrator {
private $log_file; private $log_file;
public $log_file_url; public $log_file_url;
public $progressbar; public $progressbar;
public function __construct() { public function __construct() {
$log_filename = Env::$plugin_name . '-mp2migration.log'; $log_filename = Env::$plugin_name . '-mp2migration.log';
$upload_dir = wp_upload_dir(); $upload_dir = wp_upload_dir();
$this->log_file = $upload_dir['basedir'] . '/' . $log_filename; $this->log_file = $upload_dir['basedir'] . '/' . $log_filename;
$this->log_file_url = $upload_dir['baseurl'] . '/' . $log_filename; $this->log_file_url = $upload_dir['baseurl'] . '/' . $log_filename;
$this->progressbar = new ProgressBar('mp2migration'); $this->progressbar = new ProgressBar('mp2migration');
} }
/** /**
* Test if the migration is proposed * Test if the migration is proposed
* *
* @return boolean * @return boolean
*/ */
public function proposeMigration() { public function proposeMigration() {
if ( isset($_REQUEST['nomigrate']) ) { if(isset($_REQUEST['nomigrate'])) {
// Store the user's choice if he doesn't want to migrate from MP2 // Store the user's choice if he doesn't want to migrate from MP2
update_option('mailpoet_migration_complete', true); update_option('mailpoet_migration_complete', true);
} }
if ( get_option('mailpoet_migration_complete') ) { if(get_option('mailpoet_migration_complete')) {
return false; return false;
} else { } else {
return $this->table_exists('wysija_campaign'); // Check if the MailPoet 2 tables exist return $this->tableExists('wysija_campaign'); // Check if the MailPoet 2 tables exist
} }
} }
/** /**
* Test if a table exists * Test if a table exists
* *
* @param string $table Table name * @param string $table Table name
* @return boolean * @return boolean
*/ */
public function table_exists($table) { private function tableExists($table) {
global $wpdb; global $wpdb;
try { try {
$sql = "SHOW TABLES LIKE '{$wpdb->prefix}{$table}'"; $sql = "SHOW TABLES LIKE '{$wpdb->prefix}{$table}'";
$result = $wpdb->query($sql); $result = $wpdb->query($sql);
return !empty($result); return !empty($result);
} catch ( Exception $e ) {} } catch (Exception $e) {
// Do nothing
}
return false; return false;
} }
/** /**
* Initialize the migration page * Initialize the migration page
* *
*/ */
public function init() { public function init() {
$this->enqueue_scripts(); $this->enqueueScripts();
$this->log('INIT'); $this->log('INIT');
} }
/** /**
* Register the JavaScript for the admin area. * Register the JavaScript for the admin area.
* *
*/ */
private function enqueue_scripts() { private function enqueueScripts() {
wp_enqueue_script('jquery-ui-progressbar'); wp_enqueue_script('jquery-ui-progressbar');
} }
/** /**
* Write a message in the log file * Write a message in the log file
* *
* @param string $message * @param string $message
*/ */
public function log($message) { private function log($message) {
file_put_contents($this->log_file, "$message\n", FILE_APPEND); file_put_contents($this->log_file, "$message\n", FILE_APPEND);
} }
@ -87,28 +90,27 @@ class MP2Migrator {
*/ */
public function import() { public function import() {
$this->log('START IMPORT'); $this->log('START IMPORT');
update_option('mailpoet_stop_import', false, false); // Reset the stop import action update_option('mailpoet_stopImport', false, false); // Reset the stop import action
// TODO to remove, for testing only // TODO to remove, for testing only
$this->progressbar->set_total_count(0); $this->progressbar->setTotalCount(0);
$this->progressbar->set_total_count(10); $this->progressbar->setTotalCount(10);
for ( $i = 0; $i < 10; $i++ ) { for($i = 0; $i < 10; $i++) {
$this->progressbar->increment_current_count(1); $this->progressbar->incrementCurrentCount(1);
usleep(300000); usleep(300000);
if ( $this->import_stopped() ) { if($this->importStopped()) {
return; return;
} }
} }
$this->log('END IMPORT'); $this->log('END IMPORT');
} }
/** /**
* Stop the import * Stop the import
* *
*/ */
public function stop_import() { public function stopImport() {
update_option('mailpoet_stop_import', true); update_option('mailpoet_stopImport', true);
$this->log('IMPORT STOPPED BY USER'); $this->log('IMPORT STOPPED BY USER');
} }
@ -117,8 +119,8 @@ class MP2Migrator {
* *
* @return boolean Import must stop or not * @return boolean Import must stop or not
*/ */
public function import_stopped() { private function importStopped() {
return get_option('mailpoet_stop_import'); return get_option('mailpoet_stopImport');
} }
} }

View File

@ -272,7 +272,7 @@ class Menu {
} }
$mp2Migrator = new MP2Migrator(); $mp2Migrator = new MP2Migrator();
if ($mp2Migrator->proposeMigration()) { if($mp2Migrator->proposeMigration()) {
$mp2Migrator->init(); $mp2Migrator->init();
$data = array( $data = array(
'log_file_url' => $mp2Migrator->log_file_url, 'log_file_url' => $mp2Migrator->log_file_url,

View File

@ -1,97 +1,99 @@
<?php <?php
namespace MailPoet\Util; namespace MailPoet\Util;
use MailPoet\Config\Env; use MailPoet\Config\Env;
if(!defined('ABSPATH')) exit; if(!defined('ABSPATH')) exit;
if ( !class_exists('ProgressBar', false) ) { if(!class_exists('ProgressBar', false)) {
/**
* The Progress Bar class
*
*/
class ProgressBar {
private $total_count = 0;
private $current_count = 0;
private $filename;
public $url;
/**
* Initialize the class and set its properties.
*
*/
public function __construct($progress_bar_id) {
$upload_dir = wp_upload_dir();
$filename = Env::$plugin_name . '-' . $progress_bar_id . '-progress.json';
$this->filename = $upload_dir['basedir'] . '/' . $filename;
$this->url = $upload_dir['baseurl'] . '/' . $filename;
$counters = $this->readProgress();
if(isset($counters->total)) {
$this->total_count = $counters->total;
}
if(isset($counters->current)) {
$this->current_count = $counters->current;
}
}
/**
* Get the progress file URL
*
* @return string Progress file URL
*/
public function getUrl() {
return $this->url;
}
/**
* Read the progress counters
*
* @return array|false Array of counters
*/
private function readProgress() {
if(file_exists($this->filename)) {
$json_content = file_get_contents($this->filename);
return json_decode($json_content);
} else {
return false;
}
}
/**
* Set the total count
*
* @param int $count Count
*/
public function setTotalCount($count) {
if($count != $this->total_count) {
$this->total_count = $count;
$this->current_count = 0;
$this->saveProgress();
}
}
/**
* Increment the current count
*
* @param int $count Count
*/
public function incrementCurrentCount($count) {
$this->current_count += $count;
$this->saveProgress();
}
/**
* Save the progress counters
*
*/
private function saveProgress() {
file_put_contents($this->filename, json_encode(array(
'total' => $this->total_count,
'current' => $this->current_count,
)));
}
}
/**
* The Progress Bar class
*
*/
class ProgressBar {
private $total_count = 0;
private $current_count = 0;
private $filename;
public $url;
/**
* Initialize the class and set its properties.
*
*/
public function __construct($progress_bar_id) {
$upload_dir = wp_upload_dir();
$filename = Env::$plugin_name . '-' . $progress_bar_id . '-progress.json';
$this->filename = $upload_dir['basedir'] . '/' . $filename;
$this->url = $upload_dir['baseurl'] . '/' . $filename;
$counters = $this->read_progress();
if ( isset($counters->total) ) {
$this->total_count = $counters->total;
}
if ( isset($counters->current) ) {
$this->current_count = $counters->current;
}
}
/**
* Get the progress file URL
*
* @return string Progress file URL
*/
public function get_url() {
return $this->url;
}
/**
* Read the progress counters
*
* @return array|false Array of counters
*/
private function read_progress() {
if ( file_exists($this->filename) ) {
$json_content = file_get_contents($this->filename);
return json_decode($json_content);
} else {
return false;
}
}
/**
* Set the total count
*
* @param int $count Count
*/
public function set_total_count($count) {
if ( $count != $this->total_count ) {
$this->total_count = $count;
$this->current_count = 0;
$this->save_progress();
}
}
/**
* Increment the current count
*
* @param int $count Count
*/
public function increment_current_count($count) {
$this->current_count += $count;
$this->save_progress();
}
/**
* Save the progress counters
*
*/
private function save_progress() {
file_put_contents($this->filename, json_encode(array(
'total' => $this->total_count,
'current' => $this->current_count,
)));
}
}
} }