Permalink
Browse files

Surprise features: export/import settings. ;)

  • Loading branch information...
denydias committed Dec 7, 2017
1 parent 8b7096d commit 46a2e3aafaadbdc9b1efb25f4a4b0b079f55ad08
View
@@ -106,6 +106,9 @@ function ao_ccss_add_tab($in) {
// Perform plugin activation tasks
function ao_ccss_activation() {
// Create the cache directory
mkdir(AO_CCSS_DIR, 0755);
// Create options with empty values
add_option('autoptimize_ccss_key', '');
add_option('autoptimize_ccss_rules', '');
@@ -136,9 +139,13 @@ function ao_ccss_deactivation() {
delete_option('autoptimize_ccss_viewport');
delete_option('autoptimize_ccss_debug');
// Remove the scheduled events
// Remove scheduled events
wp_clear_scheduled_hook('ao_ccss_queue');
wp_clear_scheduled_hook('ao_ccss_log_truncate');
// Remove cached files and directory
array_map('unlink', glob(AO_CCSS_DIR . '*.{css,html,json,log,zip}', GLOB_BRACE));
rmdir(AO_CCSS_DIR);
}
register_deactivation_hook(__FILE__, 'ao_ccss_deactivation');
View
@@ -249,6 +249,24 @@ p.rules-btn {
top: 1px;
font-size: 15px;
}
p.submit {
float: left;
}
#importSettingsForm {
float: right;
text-align: left;
max-width: 100%;
margin-top: 20px;
padding-top: 10px;
position: relative;
overflow: hidden;
}
#settingsfile {
padding: 0 2px;
}
#settingsfile {
padding: 0 2px;
}
input[type=url]:invalid {color: red; border-color:red;} .form-table th{font-weight:100;}
#autoptimize_main .cb_label {display: block; padding-left: 25px; text-indent: -25px;}
View
@@ -69,15 +69,18 @@ function ao_ccss_settings() {
// Render rules section
ao_ccss_render_queue();
echo '<!-- TODO: here goes more and more settings... -->';
} ?>
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Save Changes', 'autoptimize') ?>" />
</p>
</form>
<form id="importSettingsForm">
<span id="exportSettings" class="button-secondary"><?php _e('Export Settings', 'autoptimize') ?></span>
<input class="button-secondary" id="importSettings" type="button" value="<?php _e('Import Settings', 'autoptimize') ?>" onclick="upload();return false;" />
<input class="button-secondary" id="settingsfile" name="settingsfile" type="file" />
</form>
</div><!-- /#autoptimize_main -->
</div><!-- /#wrap -->
@@ -97,6 +100,7 @@ function ao_ccss_settings() {
echo '<script>';
include('admin_settings_rules.js.php');
include('admin_settings_queue.js.php');
include('admin_settings_impexp.js.php');
echo '</script>';
}
@@ -0,0 +1,38 @@
// Export and download settings
function exportSettings(idToEdit) {
console.log('Exporting...');
var data = {
'action': 'ao_ccss_export',
'ao_ccss_export_nonce': '<?php echo wp_create_nonce("ao_ccss_export_nonce"); ?>',
};
jQuery.post(ajaxurl, data, function(response) {
response_array=JSON.parse(response);
if (response_array['code'] == 200) {
window.location.href = '<?php echo content_url(); ?>/cache/ao_ccss/' + response_array['file'];
}
});
}
function upload(){
var fd = new FormData();
var file = jQuery(document).find('#settingsfile');
var settings_file = file[0].files[0];
fd.append('file', settings_file);
fd.append('action', 'ao_ccss_import');
fd.append('ao_ccss_import_nonce', '<?php echo wp_create_nonce("ao_ccss_import_nonce"); ?>');
jQuery.ajax({
url: ajaxurl,
type: 'POST',
data: fd,
contentType: false,
processData: false,
success: function(response) {
response_array=JSON.parse(response);
if (response_array['code'] == 200) {
window.location.reload();
}
}
});
}
@@ -1,24 +1,25 @@
// Hide object text box
document.getElementById('ao-ccss-queue').style.display = 'none';
var queueOriginEl = document.getElementById('ao-ccss-queue')
if (queueOriginEl) {
queueOriginEl.style.display = 'none';
// Get queue object and call table renderer
jQuery(document).ready(function() {
// Get queue object and call table renderer
jQuery(document).ready(function() {
// Instance queue object
aoCssQueue = JSON.parse(document.getElementById('ao-ccss-queue').value);
<?php if ($ao_ccss_debug) echo "console.log('Queue Object:', aoCssQueue);\n" ?>
// Instance queue object
aoCssQueue = JSON.parse(document.getElementById('ao-ccss-queue').value);
<?php if ($ao_ccss_debug) echo "console.log('Queue Object:', aoCssQueue);\n" ?>
// Render queue table
drawQueueTable(aoCssQueue);
// Render queue table
drawQueueTable(aoCssQueue);
// Let it be sortable
jQuery('#queue-tbl').tablesorter({
sortList: [[0,0]],
headers: {6: {sorter: false}}
// Let it be sortable
jQuery('#queue-tbl').tablesorter({
sortList: [[0,0]],
headers: {6: {sorter: false}}
});
});
//jQuery("#editDefaultButton").click(function(){editDefaultCritCss();});
})
}
// Render the queue in a table
function drawQueueTable(aoCssQueue) {
@@ -3,16 +3,22 @@
if ($ao_ccss_debug) echo "console.log('[WARN] DO NOT use debug mode on production/live environments!');\n";
?>
document.getElementById("critCssOrigin").style.display = 'none';
document.getElementById("autoptimize_css_defer_inline").style.display = 'none';
var rulesOriginEl = document.getElementById("critCssOrigin");
var deferInlineEl = document.getElementById("autoptimize_css_defer_inline");
if (rulesOriginEl)
rulesOriginEl.style.display = 'none';
if (deferInlineEl)
deferInlineEl.style.display = 'none';
jQuery(document).ready(function() {
critCssArray=JSON.parse(document.getElementById("critCssOrigin").value);
<?php if ($ao_ccss_debug) echo "console.log('Rules Object:', critCssArray);\n" ?>
drawTable(critCssArray);
jQuery("#addCritCssButton").click(function(){addEditRow();});
jQuery("#editDefaultButton").click(function(){editDefaultCritCss();});
})
if (rulesOriginEl) {
jQuery(document).ready(function() {
critCssArray=JSON.parse(document.getElementById("critCssOrigin").value);
<?php if ($ao_ccss_debug) echo "console.log('Rules Object:', critCssArray);\n" ?>
drawTable(critCssArray);
jQuery("#addCritCssButton").click(function(){addEditRow();});
jQuery("#editDefaultButton").click(function(){editDefaultCritCss();});
});
}
function drawTable(critCssArray) {
jQuery("#rules-list").empty();
View
@@ -141,6 +141,136 @@ function critcss_rm_callback() {
}
add_action('wp_ajax_rm_critcss', 'critcss_rm_callback');
// Ajax handler export settings
// NOTE: out of scope export settings
function ao_ccss_export_callback() {
// Check referer
check_ajax_referer('ao_ccss_export_nonce', 'ao_ccss_export_nonce');
// Init array, get options and prepare the raw object
$settings = array();
$settings['key'] = get_option('autoptimize_ccss_key');
$settings['rules'] = get_option('autoptimize_ccss_rules');
$settings['queue'] = get_option('autoptimize_ccss_queue');
$settings['viewport'] = get_option('autoptimize_ccss_viewport');
$settings['debug'] = get_option('autoptimize_ccss_debug');
// Initialize error flag
$error = TRUE;
// Check user permissios
if (current_user_can('manage_options')) {
// Prepare settings file path and content
$exportfile = AO_CCSS_DIR . 'settings.json';
$contents = json_encode($settings);
$status = file_put_contents($exportfile, $contents, LOCK_EX);
$error = FALSE;
}
// Prepare archive
$zipfile = AO_CCSS_DIR . date('Ymd') . '_ao_ccss_settings.zip';
$file = pathinfo($zipfile, PATHINFO_BASENAME);
$zip = new ZipArchive();
$ret = $zip->open($zipfile, ZipArchive::OVERWRITE);
if ($ret !== TRUE) {
$error = TRUE;
} else {
$zip->addFile(AO_CCSS_DIR . 'settings.json', 'settings.json');
if (file_exists(AO_CCSS_DIR . 'queue.json')) {
$zip->addFile(AO_CCSS_DIR . 'queue.json', 'queue.json');
}
$options = array('add_path' => './', 'remove_all_path' => TRUE);
$zip->addGlob(AO_CCSS_DIR . '*.css', 0, $options);
$zip->close();
}
// Prepare response
if (!$status || $error) {
$response['code'] ='500';
$response['msg'] = 'Error saving file ' . $file . ', code: ' . $ret;
} else {
$response['code'] = '200';
$response['msg'] = 'File ' . $file . ' saved.';
$response['file'] = $file;
}
// Dispatch respose
echo json_encode($response);
// Close ajax request
wp_die();
}
add_action('wp_ajax_ao_ccss_export', 'ao_ccss_export_callback');
// Ajax handler import settings
// NOTE: out of scope import settings
function ao_ccss_import_callback() {
// Check referer
check_ajax_referer('ao_ccss_import_nonce', 'ao_ccss_import_nonce');
// Initialize error flag
$error = FALSE;
// Process an uploaded file with no errors
if (!$_FILES['file']['error']) {
// Save file to the cache directory
$zipfile = AO_CCSS_DIR . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $zipfile);
// Extract archive
$zip = new ZipArchive;
if ($zip->open($zipfile) === TRUE) {
$zip->extractTo(AO_CCSS_DIR);
$zip->close();
} else {
$error = 'extracting';
}
// Archive extraction ok, continue settings importing
if (!$error) {
// Settings file
$importfile = AO_CCSS_DIR . 'settings.json';
if (file_exists($importfile)) {
// Get settings and turn them into an object
$settings = json_decode(file_get_contents($importfile), TRUE);
// Update options
update_option('autoptimize_ccss_key', $settings['key']);
update_option('autoptimize_ccss_rules', $settings['rules']);
update_option('autoptimize_ccss_queue', $settings['queue']);
update_option('autoptimize_ccss_viewport', $settings['viewport']);
update_option('autoptimize_ccss_debug', $settings['debug']);
// Settings file doesn't exist, update error flag
} else {
$error = 'settings file does not exist';
}
}
}
// Prepare response
if ($error) {
$response['code'] ='500';
$response['msg'] = 'Error importing settings: ' . $error;
} else {
$response['code'] = '200';
$response['msg'] = 'Settings imported successfully';
}
// Dispatch respose
echo json_encode($response);
// Close ajax request
wp_die();
}
add_action('wp_ajax_ao_ccss_import', 'ao_ccss_import_callback');
// Try to avoid directory traversal when reading/writing/deleting critical CSS files
function critcss_check_filename($filename) {
if (strpos($filename, "ccss_") !== 0) {
View
@@ -540,7 +540,7 @@ function ao_ccss_rule_update($ljid, $srule, $file, $hash) {
}
}
// Truncate log file exists and is >= 1MB
// Truncate log file if it exist and is >= 1MB
// NOTE: out of scope log file maintenance
function ao_ccss_log_truncate() {
if (file_exists(AO_CCSS_LOG)) {
View
@@ -6,3 +6,6 @@ jQuery(".toggle-btn").click(function () {
jQuery("span.toggle-indicator", $header).toggleClass('dashicons-arrow-down');
});
});
// Attach an event to export buttons
jQuery("#exportSettings").click(function(){exportSettings();});

1 comment on commit 46a2e3a

@futtta

This comment has been minimized.

Show comment
Hide comment
@futtta

futtta Dec 7, 2017

Owner

you rock @denydias :-)

Owner

futtta commented on 46a2e3a Dec 7, 2017

you rock @denydias :-)

Please sign in to comment.