, ...}
*
* @return {void}
*/
function open_preview_dialog(data) {
var optimization_id = data.id,
title = data.title,
dialog = $('#wpo-popup-preview'),
// table template with pager.
dialog_html = [
'',
''
].join(''),
pager_html = [
''
].join(''),
sites_select_html = '',
sites_select_options = [],
dialog_buttons = {};
// build sites select html.
if ('undefined' != typeof wpoptimize.sites && wpoptimize.sites.length) {
for (var i in wpoptimize.sites) {
if (!wpoptimize.sites.hasOwnProperty(i)) continue;
sites_select_options.push([''].join(''));
}
sites_select_html = [
''
].join('');
}
// add delete button to the dialog.
dialog_buttons[wpoptimize.delete_selected_items_btn] = function() {
var selected_ids = [],
table = $('#wpo-preview-tablesorter');
$('input:checkbox:checked', table).each(function() {
if (!$(this).is('#wpo-select-all-preview-rows')) {
selected_ids.push($(this).val());
}
});
// @codingStandardsIgnoreLine
if (0 == selected_ids.length) return;
var optimization_data = data;
optimization_data['ids'] = selected_ids;
// set site_id option for multisite.
if ($('#wpo-preview-site').length) {
optimization_data['site_id'] = $('#wpo-preview-site').val();
}
preview_loader.show();
wp_optimize.send_command('do_optimization',
{
'optimization_id': optimization_id,
'data': optimization_data
},
function (response) {
// force reload table content.
$('#wpo-preview-tablesorter').trigger('reload');
// uncheck all checkboxes in table.
$('#wpo-select-all-preview-rows').prop('checked', false);
send_command('get_optimization_info', {optimization_id: optimization_id}, function(resp) {
var meta = (resp && resp.result && resp.result.meta) ? resp.result.meta : {},
message = (resp && resp.result && resp.result.output) ? resp.result.output.join('
') : '',
checkboxes = {};
if ('' != message) {
// save checkbox states before update optimization info text.
// used in additional options, like for "remove all transients"
$(['#optimization_info_', optimization_id, ' input[type="checkbox"]'].join('')).each(function() {
checkboxes[$(this).attr('name')] = $(this).prop('checked');
});
$(['#optimization_info_', optimization_id].join('')).html(message);
// restore saved checkboxes state.
for (var i in checkboxes) {
if (!checkboxes.hasOwnProperty(i)) continue;
$(['#optimization_info_', optimization_id, ' input[name="',i,'"]'].join('')).prop('checked', checkboxes[i]);
}
}
});
}
);
};
// add cancel button to the dialog.
dialog_buttons[wpoptimize.close_btn] = function() {
$(this).dialog('destroy');
};
// open dialog.
dialog.dialog({
autoOpen: false,
title: title,
minWidth: 800,
minHeight: 400,
modal: true,
close: function() {
// destroy dialog on close.
$(this).dialog('destroy');
// clear popup content.
$('#wpo-popup-preview').html('');
},
buttons: dialog_buttons
});
// hide table before loading.
$('#wpo-preview-tablesorter').hide();
// put table template into dialog.
dialog.html(dialog_html);
// hide delete button.
$('.ui-dialog-buttonpane button').first().hide();
// add pager and site selector to dialog.
$('.ui-dialog-buttonpane').prepend([pager_html, sites_select_html].join(''));
// add spinner to title.
$('.ui-dialog-title').append(['
'].join(''));
var preview_loader = $('#wpo-preview-loader > img'),
preview_site_select = $('#wpo-preview-site');
/**
* Create new data source object used for fetch preview data from optimization.
*
* @type {TableSorter_DataSource}
*/
var ds = new TableSorter_DataSource({
optimization_id: optimization_id,
limit: 1
});
for (var i in data) {
if (!data.hasOwnProperty(i)) continue;
if ('id' == i || 'title' == i) continue;
ds.set_option(i, data[i]);
}
// if multisite the add site id value to data source object.
if (preview_site_select.length && preview_site_select.val()) {
ds.set_option('site_id', preview_site_select.val());
}
// handle change event for change site select.
preview_site_select.on('change', function() {
// update site id option.
ds.set_option('site_id', preview_site_select.val());
// force reload table content.
$('#wpo-preview-tablesorter').trigger('reload');
});
/**
* Get data from optimization for preview and show it in dialog.
*/
ds.fetch().done(
function(response) {
var table = $('#wpo-preview-tablesorter');
try {
response = wpo_parse_json(response);
} catch (e) {
alert(wpoptimize.error_unexpected_response);
return;
}
// hide table and pager until data loading.
table.hide();
// add table headings with received from optimization
var i,header = [], footer = [],
j = 1, // no sorters counter, 0 index already filled for column with checkboxes.
no_sorters = { 0 : { sorter: false } };
// build header and footer for preview table.
header.push(' | ');
footer.push(' | ');
for (i in response.result.columns) {
if (!response.result.columns.hasOwnProperty(i)) continue;
// set as no sortable option.
no_sorters[j] = { sorter: false };
j++;
header.push([''].join(''));
footer.push(['', response.result.columns[i],' | '].join(''));
}
table.append(['',header,'
'].join(''));
table.append(['',footer,'
'].join(''));
table.append('');
// initialize table sorter for displayed data.
var pager = $("#pager");
table.tablesorter({
widthFixed: true,
widgets: ['zebra'],
headers: no_sorters
})
.tablesorterPager({
container: pager,
size: parseInt($(".pagesize", pager).val()), // set selected page size.
dataSource: ds
});
// handle loading start for preview.
table.on('load_start', function() {
preview_loader.show();
});
// handle loading end data for preview.
table.on('load_end', function(event, response) {
preview_loader.hide();
if (parseInt(response.result.total) > 0) {
// show table with found items.
$('#wpo-preview-tablesorter').show();
// hide "no items found" message.
$('#wpo-preview-message').hide();
// show pager.
$('.ui-dialog-buttonpane #pager').show();
// show delete button.
$('.ui-dialog-buttonpane button').first().show();
} else {
// hide the table.
$('#wpo-preview-tablesorter').hide();
// show "no items found" message.
$('#wpo-preview-message').text(response.result.message).show();
// hide pager.
$('.ui-dialog-buttonpane #pager').hide();
// hide delete button.
$('.ui-dialog-buttonpane button').first().hide();
}
// show site select for multisite.
$('#wpo-preview-site').show();
});
}
);
// open the dialog.
dialog.dialog('open');
}
/**
* Update data-remove_all_transients value for transients preview links.
*/
$('#remove_all_transients').on('change', function() {
var container = $(this).closest('td'),
value = $(this).is(':checked');
$('a', container).each(function() {
$(this).data('remove_all_transients', value);
});
});
/**
* Always purge this page functionality.
*/
var wpo_always_purge_table = $('#wpo_always_purge_table'),
wpo_always_purge_post_types_select = $('#wpo_always_purge_post_types_select'),
wpo_always_purge_post_id_select = $('#wpo_always_purge_post_id_select');
/**
* Add page for purge.
*/
$('#wpo_add_always_purge_btn').on('click', function() {
var btn = $(this),
row = btn.closest('tr'),
post_type_select = $('#wpo_always_purge_post_types_select', row),
post_type = post_type_select.val(),
post_select = $('#wpo_always_purge_post_id_select', row),
post_id = post_select.val(),
post_title = $(['option[value="',post_id,'"]'].join('')).text(),
validation = true;
var selected_post_types = [];
$('#wpo_always_purge_post_types_select', row).find(':selected').each(function() {
selected_post_types.push($(this).text());
});
var new_row_html = [
'| ',selected_post_types.join(', '),' | ',post_title,' | ',wpoptimize.delete,' |
'
].join('');
// check if selected post type
if (0 == post_type.length) {
validation = false;
$('.select2-selection', post_type_select.next()).addClass('wpo_error_field');
}
// check if selected post
if (!post_id) {
validation = false;
$('.select2-selection', post_select.next()).addClass('wpo_error_field');
}
if (validation) {
// remove red borders
$('.select2-selection', post_type_select.next()).removeClass('wpo_error_field');
$('.select2-selection', post_select.next()).removeClass('wpo_error_field');
// clear selected values.
post_type_select.val(null).trigger('change');
post_select.val(null).trigger('change');
// add row with new settings.
row.before(new_row_html);
}
});
/**
* Delete page for purge.
*/
wpo_always_purge_table.on('click', '.wpo-always-purge-delete', function() {
var btn = $(this),
row = btn.closest('tr');
row.remove();
});
wpo_always_purge_post_types_select.select2();
wpo_always_purge_post_id_select.select2({
ajax: {
url: ajaxurl,
type: 'post',
dataType: 'json',
data: function(params) {
var query = {
action: 'wp_optimize_ajax',
subaction: 'get_posts_list',
nonce: wp_optimize_send_command_data.nonce,
data: {
search: params.term,
page: params.page || 1
}
}
return query;
}
}
});
/**
* User per role cache staff.
*/
var enable_per_role_cache_checkbox = $('#enable_per_role_cache'),
per_role_cache_roles_list = $('#wpo_per_role_cache_roles_list');
enable_per_role_cache_checkbox.on('change', function() {
if (enable_per_role_cache_checkbox.prop('checked')) {
per_role_cache_roles_list.removeClass('wpo_hidden');
} else {
per_role_cache_roles_list.addClass('wpo_hidden');
}
});
};
/**
* Flexible scheduler staff.
*/
jQuery(function($) {
var $auto_options = $('#wp-optimize-auto-options');
var $db_settings_form = $('#database_settings_form');
var $time_fields = $('input[type="time"]');
var $date_fields = $('input[type="date"]');
var today = new Date().toISOString().split('T')[0];
// This helps to keep track of scheduled events
var count = $('.wpo_auto_event:last').data('count') || 0;
// Use time picker when input[type="time"] not supported
$time_fields.each(function(index, element) {
if (!Modernizr.inputtypes.time) {
$(element).timepicker({'timeFormat': 'H:i'});
$(element).addClass('no_date_time_support');
$(element).on('changeTime', function() {
$(this).timepicker('hide');
});
}
});
$auto_options.on('focus', 'input[type="time"]', function() {
var element = $(this).get(0);
if (!Modernizr.inputtypes.time) {
$(element).timepicker({'timeFormat': 'H:i'});
$(element).on('changeTime', function() {
$(this).timepicker('hide');
});
}
});
$auto_options.on('keypress', 'input', function(e) {
if (13 === e.keyCode) return false;
});
// Use datepicker when input[type="date"] not supported
$date_fields.each(function(index, element) {
if (!Modernizr.inputtypes.date) {
$(element).datepicker({
dateFormat: "yy-mm-dd",
minDate: 0
});
$(element).addClass('no_date_time_support');
}
});
$auto_options.on('focus', 'input[type="date"]', function() {
var ele = $(this).get(0);
if (!Modernizr.inputtypes.date) {
$(ele).datepicker({
dateFormat: "yy-mm-dd",
minDate: 0
});
}
});
if (0 !== $('.wpo_scheduled_event').length) {
$('.wpo_no_schedules').hide();
} else {
$('.wpo_no_schedules').show();
}
$('.wpo_auto_optimizations').select2({
placeholder: wpoptimize.select_optimizations
});
$('.wpo_auto_optimizations').on('select2:opening select2:closing', function(event) {
var $searchfield = $(this).parent().find('.select2-search__field');
$searchfield.prop('disabled', true);
});
$('#purge_cache_permissions').select2({
placeholder: wpoptimize.select_roles
});
/**
* Detect change on schedule panel and set reminder
*/
$auto_options.on('change', 'select, input[type="date"], input[type="time"]', function() {
$("#save_settings_reminder").slideDown();
display_headers();
});
/**
* Adds settings fields for event scheduling
*/
$db_settings_form.on('click', '#wpo-add-event', function(e) {
e.preventDefault();
count++;
var optimizations = WP_Optimize_Handlebars.optimizations.handlebars({'optimizations': wpoptimize.auto_optimizations, 'count': count});
var schedule_types = WP_Optimize_Handlebars.schedule_types.handlebars({'schedule_types': wpoptimize.schedule_types, 'count': count});
var add_schedule_new = wpoptimize.add_schedule_new;
var add_schedule_cancel = wpoptimize.add_schedule_cancel;
var action = WP_Optimize_Handlebars.action.handlebars({'count': count, 'add_schedule_new': add_schedule_new, 'add_schedule_cancel': add_schedule_cancel });
var html_content = '';
html_content += optimizations + schedule_types + action;
html_content += '
';
$('#wpo_auto_events').append(html_content);
$('.wpo_auto_optimizations').select2({
placeholder: wpoptimize.select_optimizations
});
$('.wpo_auto_optimizations').on('select2:opening select2:closing', function(event) {
var $searchfield = $(this).parent().find('.select2-search__field');
$searchfield.prop('disabled', true);
});
});
/**
* Show appropriate fields (date, time, week and day) when schedule type is changed
*/
$db_settings_form.on('change', '.wpo_schedule_type', function() {
var $container = $(this).closest('.wpo_auto_event');
var add_schedule_new = wpoptimize.add_schedule_new;
var add_schedule_cancel = wpoptimize.add_schedule_cancel;
// Use existing count, if it is editing to existing event or use incremented count
var event_count = $container.data('count') || count;
var schedule_type = $(this).val();
var class_name = '';
if (!Modernizr.inputtypes.date || !Modernizr.inputtypes.time) {
class_name = 'no_date_time_support';
}
var today = new Date();
var dateValue = formatDate(today);
var field_details = {
'date': wpoptimize.date,
'time': wpoptimize.time,
'day': wpoptimize.day,
'day_number': wpoptimize.day_number,
'days': wpoptimize.days,
'date_value': dateValue,
'time_value': '00:00',
'status': wpoptimize.active,
'status_value': "checked",
'week_days': wpoptimize.week_days,
'week': wpoptimize.week,
'count': event_count,
'class_name': class_name,
'today': today
};
var schedule_fields = display_field_details(schedule_type, field_details);
var status = WP_Optimize_Handlebars.status.handlebars({'details': field_details});
var action = WP_Optimize_Handlebars.action.handlebars({'add_schedule_new': add_schedule_new, 'add_schedule_cancel': add_schedule_cancel});
$(this).next().html('');
$container.find('.wpo_event_status').remove();
$container.find('.wpo_event_actions').remove();
if ('' !== schedule_fields) {
$(this).next().html(schedule_fields);
}
$container.append(status + action);
});
/**
* Edit event details
*/
$db_settings_form.on('click', '#wp-optimize-auto-options .wpo_edit_event', function() {
var $container = $(this).closest('.wpo_scheduled_event');
$container.hide();
$container.next().show();
display_headers();
display_select2_options_after_document_change();
});
/**
* Remove event details
*/
$db_settings_form.on('click', '.wpo_remove_event', function() {
var count = $(this).data('count');
var ok_remove = confirm(wpoptimize.confirm_remove_task);
if (true === ok_remove) {
var $scheduled_event = $(this).closest('.wpo_scheduled_event');
var $auto_event = $(this).closest('.wpo_auto_event');
// If event deleted from list, then remove form as well
if (count == $scheduled_event.next().data('count')) {
$scheduled_event.next().remove();
$scheduled_event.remove();
}
// If event deleted from form, then remove stored details as well
if (count == $auto_event.prev().data('count')) {
$auto_event.prev().remove();
}
// Delete newly created event
$auto_event.remove();
setTimeout(function(){
$('#wp-optimize-save-database-settings').trigger('click');
}, 500);
//$("#save_settings_reminder").slideDown();
display_headers();
}
});
/**
* Cancel event edit.
*/
$db_settings_form.on('click', '#wp-optimize-auto-options .wpo_cancel_event', function() {
var $container = $(this).closest('.wpo_auto_event');
$container.hide();
$container.prev().show();
});
/**
* Additional UI processing for save settings in premium
*/
$('#database_settings_form').on('wpo-saving-form-data', function(e) {
var all_filled = true;
var $form = $('#database_settings_form');
$form.find('.wpo_auto_optimizations').each(function() {
var optimizations = $(this).val();
if (Array.isArray(optimizations) && 0 === optimizations.length) {
all_filled = false;
}
});
$form.find('.wpo_schedule_type').each(function() {
if (!$(this).val()) {
all_filled = false;
}
});
$form.find('.wpo_schedule_fields input').each(function() {
var value = $(this).val();
var validate = $(this)[0].type;
switch (validate) {
case 'date':
var params = value.split('-');
var date = parseInt(params[2]),
month = parseInt(params[1]) - 1,
year = parseInt(params[0]),
dateObj = new Date(year, month, date);
if (dateObj instanceof Date && isNaN(dateObj)) {
all_filled = false;
}
break;
case 'time':
var regex = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/;
if (!regex.test(value)) {
all_filled = false;
}
break;
}
});
if (false === all_filled) {
$form.form_errors.add('missing-fields', '');
e.stopImmediatePropagation();
$form.find('.wp-optimize-settings-save-results')
.show()
.addClass('wpo_alert_notice')
.text(wpoptimize.fill_all_fields)
.delay(5000)
.fadeOut(3000, function() {
$(this).removeClass('wpo_alert_notice');
});
} else {
$form.form_errors.remove('missing-fields');
}
$("#save_settings_reminder").slideUp('normal', function() {
display_headers();
});
});
/**
* Displays field details based on selected scheduled type
*
* @param {string} schedule_type
* @param {object} field_details
*
* @return {string}
*/
function display_field_details(schedule_type, field_details) {
var schedule_fields = '';
switch (schedule_type) {
case 'wpo_once':
schedule_fields = WP_Optimize_Handlebars.once.handlebars({'details': field_details});
break;
case 'wpo_daily':
schedule_fields = WP_Optimize_Handlebars.daily.handlebars({'details': field_details});
break;
case 'wpo_weekly':
schedule_fields = WP_Optimize_Handlebars.weekly.handlebars({'details': field_details});
break;
case 'wpo_fortnightly':
schedule_fields = WP_Optimize_Handlebars.fortnightly.handlebars({'details': field_details});
break;
case 'wpo_monthly':
schedule_fields = WP_Optimize_Handlebars.monthly.handlebars({'details': field_details});
break;
}
return schedule_fields;
}
/**
* Displays select2 options after document change.
*
* @return void
*/
function display_select2_options_after_document_change() {
$('.wpo_auto_optimizations').select2({
placeholder: wpoptimize.select_optimizations
});
$('.wpo_auto_optimizations').on('select2:opening select2:closing', function(event) {
var $searchfield = $(this).parent().find('.select2-search__field');
$searchfield.prop('disabled', true);
});
}
/**
* Displays scheduled event headers
*
* @return void
*/
function display_headers() {
if (0 === $('.wpo_scheduled_event:visible').length) {
$('.wpo_auto_event_heading_container').hide();
$('.wpo_no_schedules').show();
} else {
$('.wpo_auto_event_heading_container').show();
$('.wpo_no_schedules').hide();
}
if (0 === $('.wpo_scheduled_event:visible').length && 0 === $('.wpo_auto_event:visible').length && !$('#save_settings_reminder').is(':visible')) {
$('.wpo_no_schedules').show();
} else {
$('.wpo_no_schedules').hide();
}
}
/**
* Converts date object to user friendly date string
*
* @param {Date} date - Date object to be converted
*
* @return String - in the format YYYY-MM-DD (e.g. 2022-12-28)
*/
function formatDate(date) {
month = '' + (date.getMonth() + 1),
day = '' + date.getDate(),
year = date.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
});