PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.5.3
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.5.3
4.7.0 4.6.1 4.6.0 4.5.5 4.5.4 4.5.3 4.5.2 3.2.20 3.2.21 3.2.22 3.2.3 3.2.5 3.2.6 3.2.7 3.2.9 3.3.0 3.3.1 3.3.2 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.7.0 3.7.1 All 111 releases
wp-optimize / includes / class-wp-optimize-commands.php

class-wp-optimize-commands.php in WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance 4.5.3, at includes/class-wp-optimize-commands.php

2,230 lines 71.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 if (!defined('ABSPATH')) die('No direct access allowed');
4
5 /**
6 * All commands that are intended to be available for calling from any sort of control interface (e.g. wp-admin, UpdraftCentral) go in here. All public methods should either return the data to be returned, or a WP_Error with associated error code, message and error data.
7 */
8 class WP_Optimize_Commands {
9
10 private $optimizer;
11
12 protected $options;
13
14 private $wpo_sites; // used in get_optimizations_info command.
15
16 public function __construct() {
17 $this->optimizer = WP_Optimize()->get_optimizer();
18 $this->options = WP_Optimize()->get_options();
19 }
20
21 public function get_version() {
22 return WPO_VERSION;
23 }
24
25 public function enable_or_disable_feature($data) {
26
27 $type = (string) $data['type'];
28 $enable = (bool) $data['enable'];
29
30 $options = array($type => $enable);
31
32 return $this->optimizer->trackback_comment_actions($options);
33 }
34
35 public function save_manual_run_optimization_options($sent_options) {
36 return $this->options->save_sent_manual_run_optimization_options($sent_options);
37 }
38
39 public function get_status_box_contents() {
40 $status_data = $this->get_all_status_data();
41
42 return WP_Optimize()->include_template('database/status-box-contents.php', true, $status_data);
43 }
44
45 /**
46 * Get the database tabs information.
47 *
48 * @return string auto cleanup content.
49 */
50 public function get_settings_auto_cleanup_contents() {
51 $settings_cleanup_data = $this->get_wp_optimize_schedule_cleanup_settings_data();
52
53 return WP_Optimize()->include_template('database/settings-auto-cleanup.php', true, array('show_innodb_option' => WP_Optimize()->template_should_include_data() && $this->optimizer->show_innodb_force_optimize(), 'settings_cleanup_data' => $settings_cleanup_data));
54 }
55
56 /**
57 * Get the settings tab information.
58 *
59 * @return string logging settings content.
60 */
61 public function get_logging_settings_contents() {
62 $loggers_data = $this->get_wp_optimize_logging_settings_data();
63 return WP_Optimize()->include_template('settings/settings-logging.php', true, array('loggers_data' => $loggers_data));
64 }
65
66 /**
67 * Get the database tabs information
68 *
69 * @return string database table optimization rendered content
70 */
71 public function get_optimizations_table() {
72
73 $optimization_data = $this->get_wp_optimize_data();
74
75 return WP_Optimize()->include_template('database/optimizations-table.php', true, $optimization_data);
76 }
77
78 /**
79 * [For UpdraftCentral] Returns the file content containing the list of unused images
80 *
81 * @return WP_Error|void
82 */
83 public function download_csv() {
84 if (!current_user_can(WP_Optimize()->capability_required())) {
85 return $this->request_error('insufficient_privilege');
86 }
87
88 WP_Optimize()->get_optimizer()->get_optimization('images')->output_csv();
89 }
90
91 /**
92 * [For UpdraftCentral] Retrieves the tabs and their corresponding contents, assets basing
93 * from the current page or section requested (e.g. database, images, cache, minify or settings)
94 *
95 * @param array $params Parameters needed for the requested action
96 * @return array|WP_Error
97 */
98 public function get_section($params) {
99 if (!current_user_can(WP_Optimize()->capability_required())) {
100 return $this->request_error('insufficient_privilege');
101 }
102
103 $section_id = $params['section'];
104 $section = $this->get_section_to_tab_name($section_id);
105 $tabs = WP_Optimize()->get_admin_instance()->get_tabs($section);
106
107 // We remove the UpdraftCentral management tab when managing WP-Optimize
108 // plugin from the UpdraftCentral dashboard if it exists.
109 if (isset($tabs['updraftcentral'])) unset($tabs['updraftcentral']);
110
111 $this->load_action_hooks_for_content($section_id);
112 return array(
113 'tabs' => $tabs,
114 'tabs_content' => $this->get_tab_contents($tabs, $section),
115 'assets' => $this->get_localized_variables(),
116 'wposmush' => $this->get_wposmush(),
117 'is_premium' => WP_Optimize::is_premium(),
118 'modal_template' => WP_Optimize()->include_template('modal.php', true),
119 );
120 }
121
122 /**
123 * [For UpdraftCentral] Retrieves the list of items to optimize from the current database
124 *
125 * @return array|WP_Error
126 */
127 public function get_database_tabs_info() {
128 if (!current_user_can(WP_Optimize()->capability_required())) {
129 return $this->request_error('insufficient_privilege');
130 }
131
132 return $this->get_database_tabs();
133 }
134
135 /**
136 * [For UpdraftCentral] Processes specific Smush commands from ajax requests
137 *
138 * @param array $params Parameters needed for the requested action
139 * @return array|WP_Error
140 */
141 public function updraft_smush_ajax($params) {
142 if (!current_user_can(WP_Optimize()->capability_required())) {
143 return $this->request_error('insufficient_privilege');
144 }
145
146 $subaction = $params['subaction'];
147 $data = $params['data'];
148
149 $allowed_commands = Updraft_Smush_Manager_Commands::get_allowed_ajax_commands();
150 if (in_array($subaction, $allowed_commands)) {
151 if (in_array($subaction, array('get_smush_logs', 'process_bulk_smush'))) {
152 switch ($subaction) {
153 case 'get_smush_logs':
154 $results = $this->get_smush_logs();
155 break;
156 case 'process_bulk_smush':
157 $results = $this->process_bulk_smush($data);
158 break;
159 default:
160 break;
161 }
162 } else {
163 if (!empty($data)) {
164 $results = call_user_func(array(Updraft_Smush_Manager()->commands, $subaction), $data);
165 } else {
166 $results = call_user_func(array(Updraft_Smush_Manager()->commands, $subaction));
167 }
168 }
169
170 if (is_wp_error($results)) {
171 return $this->request_error($results->get_error_code(), null, array(
172 'status' => true,
173 'error_message' => $results->get_error_message(),
174 'error_data' => $results->get_error_data(),
175 ));
176 } else {
177 return $results;
178 }
179 } else {
180 return $this->request_error('command_not_found');
181 }
182 }
183
184 /**
185 * [For UpdraftCentral] Processes general WP-Optimize commands from ajax requests
186 *
187 * @param array $params Parameters needed for the requested action
188 * @return array|WP_Error
189 */
190 public function handle_ajax_requests($params) {
191 if (!current_user_can(WP_Optimize()->capability_required())) {
192 return $this->request_error('insufficient_privilege');
193 }
194
195 $subaction = $params['subaction'];
196 $data = $params['data'];
197
198 $response = array();
199 if (is_multisite() && !current_user_can('manage_network_options')) {
200 $allowed_multisite_commands = apply_filters('wpo_multisite_allowed_commands', array('check_server_status', 'compress_single_image', 'restore_single_image'));
201
202 if (!in_array($subaction, $allowed_multisite_commands)) {
203 return $this->request_error('network_admin_only');
204 }
205 }
206
207 $dismiss_actions = array(
208 'dismiss_dash_notice_until',
209 'dismiss_season',
210 'dismiss_page_notice_until',
211 'dismiss_notice',
212 'dismiss_review_notice',
213 );
214
215 if (in_array($subaction, $dismiss_actions)) {
216 $options = WP_Optimize()->get_options();
217
218 // Some commands that are available via AJAX only.
219 if (in_array($subaction, array('dismiss_dash_notice_until', 'dismiss_season'))) {
220 $options->update_option($subaction, (time() + 366 * 86400));
221 } elseif (in_array($subaction, array('dismiss_page_notice_until', 'dismiss_notice'))) {
222 $options->update_option($subaction, (time() + 84 * 86400));
223 } elseif ('dismiss_review_notice' === $subaction) {
224 if (empty($data['dismiss_forever'])) {
225 $options->update_option($subaction, time() + 84 * 86400);
226 } else {
227 $options->update_option($subaction, 100 * (365.25 * 86400));
228 }
229 }
230
231 } else {
232 $commands = new WP_Optimize_Commands();
233
234 $minify_commands = new WP_Optimize_Minify_Commands();
235 if (!is_callable(array($commands, $subaction)) && is_callable(array($minify_commands, $subaction))) {
236 $commands = $minify_commands;
237 }
238
239 if (WP_Optimize::is_premium()) {
240 $cache_commands = new WP_Optimize_Cache_Commands_Premium();
241 } else {
242 $cache_commands = new WP_Optimize_Cache_Commands();
243 }
244
245 if (!is_callable(array($commands, $subaction)) && is_callable(array($cache_commands, $subaction))) {
246 $commands = $cache_commands;
247 }
248
249 // Check if command is valid
250 if (!is_callable(array($commands, $subaction))) {
251 return $this->request_error('command_not_found');
252 } else {
253 $response = call_user_func(array($commands, $subaction), $data);
254 if (is_wp_error($response)) {
255 return $this->request_error($response->get_error_code(), null, array(
256 'error_message' => $response->get_error_message(),
257 'error_data' => $response->get_error_data(),
258 ));
259 } elseif (empty($response)) {
260 $response = array(
261 'result' => null
262 );
263 } else {
264 if (isset($response['status_box_contents'])) {
265 $response['status_box_contents'] = str_replace(array("\n", "\t"), '', $response['status_box_contents']);
266 }
267 }
268 }
269 }
270
271 return $response;
272 }
273
274 /**
275 * [For UpdraftCentral] Retrieves a list of posts to purge as options to be displayed under
276 * cache - advanced settings
277 *
278 * @param array $params Parameters needed for the requested action
279 * @return array|WP_Error
280 */
281 public function get_posts_list($params) {
282 if (!current_user_can(WP_Optimize()->capability_required())) {
283 return $this->request_error('insufficient_privilege');
284 }
285
286 $response = array();
287 if (WP_Optimize::is_premium()) {
288 $commands = new WP_Optimize_Cache_Commands_Premium();
289 if (is_callable(array($commands, 'get_posts_list'))) {
290 $response = $commands->get_posts_list($params);
291 }
292 }
293
294 return $response;
295 }
296
297 /**
298 * [For UpdraftCentral] loads the settings page
299 *
300 * @return void
301 */
302 public function output_dashboard_settings_tab() {
303 $wpo_admin = WP_Optimize()->get_admin_instance();
304
305 if (WP_Optimize()->can_manage_options()) {
306 $loggers_data = $this->get_wp_optimize_logging_settings_data();
307 $settings_trackback_data = $this->get_wp_optimize_trackback_toggle_settings_data();
308 $settings_comments_data = $this->get_wp_optimize_comments_toggle_settings_data();
309 $settings_general_data = $this->get_wp_optimize_general_settings_data();
310
311 WP_Optimize()->include_template('settings/settings.php', false, array('loggers_data' => $loggers_data, 'settings_trackback_data' => $settings_trackback_data, 'settings_comments_data' => $settings_comments_data, 'settings_general_data' => $settings_general_data));
312 } else {
313 $wpo_admin->prevent_manage_options_info();
314 }
315 }
316
317 /**
318 * [For UpdraftCentral] Retrieves Smush JS variables
319 *
320 * @return array
321 */
322 private function get_wposmush() {
323 if (!class_exists('Updraft_Smush_Manager')) return array();
324
325 $js_variables = Updraft_Smush_Manager()->smush_js_translations();
326 $js_variables['ajaxurl'] = admin_url('admin-ajax.php');
327 $js_variables['features'] = Updraft_Smush_Manager()->get_features();
328
329 return $js_variables;
330 }
331
332 /**
333 * [For UpdraftCentral] Execute smush process in bulk
334 *
335 * @param array $data Parameters to be pass as argument for the requested action
336 * @return string
337 */
338 private function process_bulk_smush($data) {
339 ob_start();
340 Updraft_Smush_Manager()->commands->process_bulk_smush($data);
341 $content = ob_get_contents();
342 ob_end_clean();
343
344 return $content;
345 }
346
347 /**
348 * [For UpdraftCentral] Retrieves the content of a Smush log file
349 *
350 * @return string|false|WP_Error
351 */
352 private function get_smush_logs() {
353 $logfile = Updraft_Smush_Manager()->get_logfile_path();
354 if (!file_exists($logfile)) {
355 Updraft_Smush_Manager()->write_log_header();
356 }
357
358 if (is_file($logfile)) {
359 return file_get_contents($logfile);
360 } else {
361 return $this->request_error('log_file_not_exist');
362 }
363 }
364
365 /**
366 * [For UpdraftCentral] Loads the WP-Optimize hooks needed to pull the tab contents for
367 * the requested page/section
368 *
369 * @param string $section_id The id of the page or section where the content is to be pulled from
370 * @return void
371 */
372 private function load_action_hooks_for_content($section_id) {
373 $wpo = WP_Optimize();
374 $wpo_admin = $wpo->get_admin_instance();
375
376 // Database
377 if ('database' === $section_id) {
378 add_action('wp_optimize_admin_page_WP-Optimize_optimize', array($wpo_admin, 'output_database_optimize_tab'), 20);
379 add_action('wp_optimize_admin_page_WP-Optimize_tables', array($wpo_admin, 'output_database_tables_tab'), 20);
380 add_action('wp_optimize_admin_page_WP-Optimize_settings', array($wpo_admin, 'output_database_settings_tab'), 20);
381 }
382
383 // Images
384 if ('images' === $section_id) {
385 add_action('wp_optimize_admin_page_wpo_images_smush', array($wpo, 'admin_page_wpo_images_smush'));
386
387 if (!WP_Optimize::is_premium()) {
388 add_action('wp_optimize_admin_page_wpo_images_unused', array($wpo_admin, 'admin_page_wpo_images_unused'));
389 add_action('wp_optimize_admin_page_wpo_images_lazyload', array($wpo_admin, 'admin_page_wpo_images_lazyload'));
390 }
391 }
392
393 // Cache
394 if ('cache' === $section_id) {
395 add_action('wp_optimize_admin_page_wpo_cache_cache', array($wpo_admin, 'output_page_cache_tab'), 20);
396 add_action('wp_optimize_admin_page_wpo_cache_preload', array($wpo_admin, 'output_page_cache_preload_tab'), 20);
397 add_action('wp_optimize_admin_page_wpo_cache_advanced', array($wpo_admin, 'output_page_cache_advanced_tab'), 20);
398 add_action('wp_optimize_admin_page_wpo_cache_gzip', array($wpo_admin, 'output_cache_gzip_tab'), 20);
399 add_action('wp_optimize_admin_page_wpo_cache_settings', array($wpo_admin, 'output_cache_settings_tab'), 20);
400 }
401
402 // Minify
403 if ('minify' === $section_id) {
404 if (class_exists('WP_Optimize_Minify_Admin')) {
405 do_action('wp_optimize_register_admin_content');
406 }
407 }
408
409 // Settings
410 if ('settings' === $section_id) {
411 add_action('wp_optimize_admin_page_wpo_settings_settings', array($this, 'output_dashboard_settings_tab'), 20);
412 }
413 }
414
415 /**
416 * [For UpdraftCentral] Execute the hooks needed to pull the content of the tabs under the requested page/section
417 *
418 * @param array $tabs The list of tabs available under the current page/section
419 * @param string $section The id of the page or section
420 * @return array
421 */
422 private function get_tab_contents($tabs, $section) {
423 $contents = array();
424
425 foreach ($tabs as $tab_id => $tab_description) {
426 ob_start();
427 // output wrap div for tab with id #wp-optimize-nav-tab-contents-'.$section.'-'.$tab_id
428 echo '<div class="wp-optimize-nav-tab-contents" id="wp-optimize-nav-tab-'.esc_attr($section).'-'.esc_attr($tab_id).'-contents">';
429
430 echo '<div class="postbox wpo-tab-postbox">';
431
432 // call action for generate tab content.
433 do_action('wp_optimize_admin_page_'.$section.'_'.$tab_id);
434
435 // closes postbox.
436 echo '</div><!-- END .postbox -->';
437 // closes tab wrapper.
438 echo '</div><!-- END .wp-optimize-nav-tab-contents -->';
439 $tab_content = ob_get_contents();
440 ob_end_clean();
441
442 $contents[$tab_id] = $tab_content;
443 }
444
445 return $contents;
446 }
447
448 /**
449 * [For UpdraftCentral] Replaces the names/id used in UpdraftCentral with the actual name used in WP-Optimize
450 *
451 * @param string $section_id The id of the page or section
452 * @return string
453 */
454 private function get_section_to_tab_name($section_id) {
455 $tab = '';
456 switch ($section_id) {
457 case 'database':
458 $tab = 'WP-Optimize';
459 break;
460 default:
461 $tab = 'wpo_'.$section_id;
462 break;
463 }
464 return $tab;
465 }
466
467 /**
468 * [For UpdraftCentral] Retrieves the localized scripts/variables (e.g. translations, etc.) used by WP-Optimize
469 *
470 * @return array
471 */
472 private function get_localized_variables() {
473 $wpo = WP_Optimize();
474 $js_variables = $wpo->wpo_js_translations();
475 $js_variables['loggers_classes_info'] = $wpo->get_loggers_classes_info();
476 $js_variables['ajaxurl'] = admin_url('admin-ajax.php');
477
478 $localized_variables = array(
479 'wpoptimize' => $js_variables,
480 'wp_optimize_send_command_data' => array('nonce' => wp_create_nonce('wp-optimize-ajax-nonce')),
481 'wpo_heartbeat_ajax' => array(
482 'ajaxurl' => admin_url('admin-ajax.php'),
483 'nonce' => wp_create_nonce('heartbeat-nonce'),
484 'interval' => WPO_Ajax::HEARTBEAT_INTERVAL
485 ),
486 );
487
488 if (WP_Optimize::is_premium()) {
489 $localized_variables = array_merge($localized_variables, array(
490 'wp_optimize_minify_premium' => array(
491 'home_url' => home_url()
492 )
493 ));
494 }
495
496 return array(
497 'localize' => $localized_variables,
498 );
499 }
500
501 /**
502 * [For UpdraftCentral] Returns a WP_Error response for the current request
503 *
504 * @param string $code The error code
505 * @param ?string $message_key The key to use to query any translatable message if applicable
506 * @param array $additional_data Any additional data to return
507 * @return WP_Error
508 */
509 private function request_error($code, $message_key = null, $additional_data = array()) {
510 global $updraftcentral_host_plugin;
511
512 $error_message = $updraftcentral_host_plugin->retrieve_show_message($code);
513 if (!is_null($message_key) && $code !== $message_key) {
514 $error_message = $updraftcentral_host_plugin->retrieve_show_message($message_key);
515 }
516
517 $data = array(
518 'result' => false,
519 'error_code' => $code,
520 'error_message' => $error_message,
521 'error' => true,
522 'code' => $code,
523 'message' => $error_message,
524 );
525
526 if (!empty($additional_data)) {
527 $data = array_merge($data, $additional_data);
528 }
529
530 return new WP_Error($code, $error_message, $data);
531 }
532
533 /**
534 * Pulls and return the "WP Optimize" template contents. Primarily used for UpdraftCentral
535 * content display through ajax request.
536 *
537 * @return array An array containing the WPO translations and the "WP Optimize" tab's rendered contents
538 */
539 public function get_wp_optimize_contents() {
540 $status_data = $this->get_all_status_data();
541 $optimization_data = $this->get_wp_optimize_data();
542 $content = WP_Optimize()->include_template('database/optimize-table.php', true, array('optimize_db' => false, 'load_data' => WP_Optimize()->template_should_include_data(), 'does_server_allow_table_optimization' => WP_Optimize()->get_server_compatibility_instance()->does_server_allow_table_optimization(), 'optimizations_table_data' => $optimization_data, 'status_data' => $status_data));
543
544 if (WP_Optimize()->is_updraft_central_request()) {
545 $content .= $this->get_status_box_contents();
546 }
547
548 return array(
549 'content' => $content,
550 'translations' => $this->get_js_translation()
551 );
552 }
553
554 /**
555 * Pulls and return the "Table Information" template contents. Primarily used for UpdraftCentral
556 * content display through ajax request.
557 *
558 * @return array An array containing the WPO translations and the "Table Information" tab's rendered contents
559 */
560 public function get_table_information_contents() {
561 $table_list_data = $this->get_table_list_data();
562 $content = WP_Optimize()->include_template('database/tables.php', true, array('optimize_db' => false, 'load_data' => WP_Optimize()->template_should_include_data(), 'table_list_data' => $table_list_data['data']));
563
564 return array(
565 'content' => $content,
566 'translations' => $this->get_js_translation()
567 );
568 }
569
570 /**
571 * Pulls and return the "Settings" template contents. Primarily used for UpdraftCentral
572 * content display through ajax request.
573 *
574 * @return array An array containing the WPO translations and the "Settings" tab's rendered contents
575 */
576 public function get_settings_contents() {
577 $admin_settings = '<form action="#" method="post" enctype="multipart/form-data" name="settings_form" id="settings_form">';
578
579 $settings_general_data = $this->get_wp_optimize_general_settings_data();
580 $admin_settings .= WP_Optimize()->include_template('database/settings-general.php', true, $settings_general_data);
581
582 $settings_cleanup_data = $this->get_wp_optimize_schedule_cleanup_settings_data();
583 $admin_settings .= WP_Optimize()->include_template('database/settings-auto-cleanup.php', true, array('show_innodb_option' => WP_Optimize()->template_should_include_data() && $this->optimizer->show_innodb_force_optimize(), 'settings_cleanup_data' => $settings_cleanup_data));
584
585 $loggers_data = $this->get_wp_optimize_logging_settings_data();
586 $admin_settings .= WP_Optimize()->include_template('settings/settings-logging.php', true, array('loggers_data' => $loggers_data));
587
588 $admin_settings .= '<input id="wp-optimize-settings-save" class="button button-primary" type="submit" name="wp-optimize-settings" value="' . esc_attr__('Save settings', 'wp-optimize') .'" />';
589 $admin_settings .= '</form>';
590
591 $settings_trackback_data = $this->get_wp_optimize_trackback_toggle_settings_data();
592 $settings_comments_data = $this->get_wp_optimize_comments_toggle_settings_data();
593 $admin_settings .= WP_Optimize()->include_template('settings/settings-trackback-and-comments.php', true, array('settings_trackback_data' => $settings_trackback_data, 'settings_comments_data' => $settings_comments_data));
594
595 $content = $admin_settings;
596
597 return array(
598 'content' => $content,
599 'translations' => $this->get_js_translation()
600 );
601 }
602
603 /**
604 * Returns array of translations used by the WPO plugin. Primarily used for UpdraftCentral
605 * consumption.
606 *
607 * @param array $params Optional parameters for the translation request
608 * @return array The WPO translations
609 */
610 public function get_js_translation($params = array()) {
611 $translations = WP_Optimize()->wpo_js_translations();
612
613 // Make sure that we include the loggers classes info whenever applicable before
614 // returning the translations to UpdraftCentral.
615 if (is_callable(array(WP_Optimize(), 'get_loggers_classes_info'))) {
616 $translations['loggers_classes_info'] = WP_Optimize()->get_loggers_classes_info();
617 }
618
619 if (isset($params['return_formatted_response'])) {
620 return array(
621 'error' => false,
622 'data' => array(
623 'translations' => $translations,
624 )
625 );
626 }
627
628 return $translations;
629 }
630
631 /**
632 * Save settings command.
633 *
634 * @param string $data
635 * @return array
636 */
637 public function save_settings($data) {
638
639 parse_str(stripslashes($data), $posted_settings);
640
641 $saved_settings = $this->options->save_settings($posted_settings);
642 // We now have $posted_settings as an array.
643 return array(
644 'save_results' => $saved_settings,
645 'status_box_contents' => $this->get_status_box_contents(),
646 'optimizations_table' => $this->get_optimizations_table(),
647 'settings_auto_cleanup_contents' => $this->get_settings_auto_cleanup_contents(),
648 'logging_settings_contents' => $this->get_logging_settings_contents(),
649 );
650 }
651
652 /**
653 * Wipe settings command.
654 *
655 * @return bool|int
656 */
657 public function wipe_settings() {
658 $result = $this->options->wipe_settings();
659
660 $onboarding = WP_Optimize()->get_onboarding();
661 $onboarding->activate_onboarding_wizard();
662
663 return $result;
664 }
665
666 /**
667 * Save lazy load settings.
668 *
669 * @param string $data
670 * @return array
671 */
672 public function save_lazy_load_settings($data) {
673 parse_str(stripslashes($data), $posted_settings);
674
675 return array(
676 'save_result' => $this->options->save_lazy_load_settings($posted_settings)
677 );
678 }
679
680 /**
681 * This sends the selected tick value over to the save function
682 * within class-wp-optimize-options.php
683 *
684 * @param array $data An array of data that includes true or false for click option.
685 * @return array
686 */
687 public function save_auto_backup_option($data) {
688 return array('save_auto_backup_option' => $this->options->save_auto_backup_option($data));
689 }
690
691 /**
692 * Save option which sites to optimize in multisite mode.
693 *
694 * @param array $data Array of settings.
695 * @return bool
696 */
697 public function save_site_settings($data) {
698 if (!isset($data['wpo-sites'])) {
699 // this means no site selected
700 $data['wpo-sites'] = array();
701 }
702 return $this->options->save_wpo_sites_option($data['wpo-sites']);
703 }
704
705 /**
706 * Perform the requested optimization
707 *
708 * @param array $params Should have keys 'optimization_id' and 'data'.
709 * @return array
710 */
711 public function do_optimization($params) {
712
713 if (!isset($params['optimization_id'])) {
714 $results = array(
715 'result' => false,
716 'messages' => array(),
717 'errors' => array(
718 __('No optimization was indicated.', 'wp-optimize')
719 )
720 );
721 } else {
722 $optimization_id = $params['optimization_id'];
723 $data = $params['data'] ?? array();
724 $include_ui_elements = $data['include_ui_elements'] ?? false;
725
726 $optimization = $this->optimizer->get_optimization($optimization_id, $data);
727
728 $result = is_a($optimization, 'WP_Optimization') ? $optimization->do_optimization() : null;
729
730 $results = array(
731 'result' => $result,
732 'messages' => array(),
733 'errors' => array(),
734 );
735
736 if ($include_ui_elements) {
737 $results['status_box_contents'] = $this->get_status_box_contents();
738 }
739
740 if (is_wp_error($optimization)) {
741 $results['errors'][] = $optimization->get_error_message().' ('.$optimization->get_error_code().')';
742 }
743
744 if ($include_ui_elements && $optimization->get_changes_table_data()) {
745 $table_list = $this->get_table_list();
746 $results['table_list'] = $table_list['table_list'];
747 $results['total_size'] = $table_list['total_size'];
748 }
749 }
750 return $results;
751 }
752
753 /**
754 * Preview command, used to show information about data should be optimized in popup tool.
755 *
756 * @param array $params Should have keys 'optimization_id', 'offset' and 'limit'.
757 *
758 * @return array
759 */
760 public function preview($params) {
761 if (!isset($params['optimization_id'])) {
762 $results = array(
763 'result' => false,
764 'messages' => array(),
765 'errors' => array(
766 __('No optimization was indicated.', 'wp-optimize')
767 )
768 );
769 } else {
770 $optimization_id = $params['optimization_id'];
771 $data = $params['data'] ?? array();
772 $params['offset'] = isset($params['offset']) ? (int) $params['offset'] : 0;
773 $params['limit'] = isset($params['limit']) ? (int) $params['limit'] : 50;
774
775 $optimization = $this->optimizer->get_optimization($optimization_id, $data);
776
777 if (is_a($optimization, 'WP_Optimization')) {
778 if (isset($params['site_id'])) {
779 $optimization->switch_to_blog((int) $params['site_id']);
780 }
781 $result = $optimization->preview($params);
782 } else {
783 $result = null;
784 }
785
786 $results = array(
787 'result' => $result,
788 'messages' => array(),
789 'errors' => array()
790 );
791 }
792
793 return $results;
794 }
795
796 /**
797 * Get information about requested optimization.
798 *
799 * @param array $params Should have keys 'optimization_id' and 'data'.
800 * @return array
801 */
802 public function get_optimization_info($params) {
803 if (!isset($params['optimization_id'])) {
804 $results = array(
805 'result' => false,
806 'messages' => array(),
807 'errors' => array(
808 __('No optimization was indicated.', 'wp-optimize')
809 )
810 );
811 } else {
812 $optimization_id = $params['optimization_id'];
813 $data = $params['data'] ?? array();
814 $include_ui_elements = $data['include_ui_elements'] ?? false;
815
816 $optimization = $this->optimizer->get_optimization($optimization_id, $data);
817 $result = is_a($optimization, 'WP_Optimization') ? $optimization->get_optimization_info() : null;
818
819 $results = array(
820 'result' => $result,
821 'messages' => array(),
822 'errors' => array(),
823 );
824
825 if ($include_ui_elements) {
826 $results['status_box_contents'] = $this->get_status_box_contents();
827 }
828 }
829
830 return $results;
831 }
832
833 /**
834 * Get the data for the tables tab
835 *
836 * @param array $data
837 * @return array
838 */
839 public function get_table_list($data = array()) {
840 if (isset($data['refresh_plugin_json']) && filter_var($data['refresh_plugin_json'], FILTER_VALIDATE_BOOLEAN)) WP_Optimize()->get_db_info()->update_plugin_json();
841
842 $table_list_data = $this->get_table_list_data();
843
844 if (WP_Optimize()->is_updraft_central_request()) {
845 return $table_list_data;
846 }
847
848 $size = $this->optimizer->get_current_db_size();
849
850 $tables_data = array(
851 'table_list' => WP_Optimize()->include_template('database/tables-body.php', true, $table_list_data['data']),
852 'total_size' => $size[0],
853 );
854
855 $filtered_tables_data = apply_filters('wpo_get_tables_data', $tables_data);
856 if (!empty($filtered_tables_data) && is_array($filtered_tables_data)) return $filtered_tables_data;
857 return $tables_data;
858 }
859
860 /**
861 * Get the database tabs information
862 *
863 * @return array
864 */
865 public function get_database_tabs() {
866 return array_merge(array('optimizations' => $this->get_optimizations_table(), 'does_server_allow_table_optimization' => WP_Optimize()->get_server_compatibility_instance()->does_server_allow_table_optimization()), $this->get_table_list());
867 }
868
869 /**
870 * Do action wp_optimize_after_optimizations
871 * used in ajax request after all optimizations completed
872 *
873 * @return boolean
874 */
875 public function optimizations_done() {
876
877 $this->options->update_option('total-cleaned', 0);
878 // Run action after all optimizations completed.
879 do_action('wp_optimize_after_optimizations');
880
881 return true;
882 }
883
884 /**
885 * Return information about all optimizations.
886 *
887 * @param array $params
888 * @return array
889 */
890 public function get_optimizations_info($params) {
891 $this->wpo_sites = $params['wpo-sites'] ?? 0;
892
893 add_filter('get_optimization_blogs', array($this, 'get_optimization_blogs_filter'));
894
895 $results = array();
896 $optimizations = $this->optimizer->get_optimizations();
897
898 foreach ($optimizations as $optimization_id => $optimization) {
899 if (false === $optimization->display_in_optimizations_list()) continue;
900
901 $results[$optimization_id] = $optimization->get_settings_html();
902 }
903
904 return $results;
905 }
906
907 /**
908 * Filter for get_optimizations_blogs function, used in get_optimizations_info command.
909 * Not intended for direct usage as a command (is used internally as a WP filter)
910 *
911 * The class variable $wpo_sites is used for performing the filtering.
912 *
913 * @param array $sites - unfiltered list of sites
914 * @return array - after filtering
915 */
916 public function get_optimization_blogs_filter($sites) {
917 $sites = array();
918
919 if (!empty($this->wpo_sites)) {
920 foreach ($this->wpo_sites as $site) {
921 if ('all' !== $site) $sites[] = $site;
922 }
923 }
924
925 return $sites;
926 }
927
928 /**
929 * Checks overdue crons and return message
930 *
931 * @return array
932 */
933 public function check_overdue_crons() {
934 $overdue_crons = WP_Optimize()->howmany_overdue_crons();
935
936 if ($overdue_crons >= 4) {
937 return array('m' => WP_Optimize()->show_admin_warning_overdue_crons($overdue_crons));
938 }
939
940 return array();
941 }
942
943 /**
944 * Enable or disable Gzip compression.
945 *
946 * @param array $params - ['enable' => true|false]
947 * @return array
948 */
949 public function enable_gzip_compression($params) {
950 return WP_Optimize()->get_gzip_compression()->enable_gzip_command_handler($params);
951 }
952
953 /**
954 * Get the current gzip compression status
955 *
956 * @return array
957 */
958 public function get_gzip_compression_status() {
959 $status = WP_Optimize()->get_gzip_compression()->is_gzip_compression_enabled(true);
960 return is_wp_error($status) ? array('error' => __('We could not determine if Gzip compression is enabled.', 'wp-optimize'), 'code' => $status->get_error_code(), 'message' => $status->get_error_message()) : array('status' => $status);
961 }
962
963 /**
964 * Import WP-Optimize settings.
965 *
966 * @param array $params array with 'settings' item where 'settings' json-encoded string.
967 *
968 * @return array - the results of the import operation
969 */
970 public function import_settings($params) {
971 if (empty($params['settings'])) {
972 return array('errors' => array(__('Please upload a valid settings file.', 'wp-optimize')));
973 }
974
975 $settings = json_decode($params['settings'], true);
976
977 // check if valid json file posted
978 if (JSON_ERROR_NONE !== json_last_error() || empty($settings)) {
979 return array('errors' => array(__('Please upload a valid settings file.', 'wp-optimize')));
980 }
981
982 $cache_settings = $settings['cache_settings'];
983 $minify_settings = $settings['minify_settings'];
984 $smush_settings = $settings['smush_settings'];
985 $database_settings = $settings['database_settings'];
986
987 $cache = WP_Optimize()->get_page_cache();
988 $cache->create_folders();
989 $cache_enable_result = null;
990 if ($cache_settings['enable_page_caching']) {
991 $cache_enable_result = $cache->enable();
992 }
993
994 $wpo_browser_cache = WP_Optimize()->get_browser_cache();
995 if (isset($cache_settings['enable_browser_cache']) && $cache_settings['enable_browser_cache']) {
996 $browser_cache = array(
997 'browser_cache_expire_days' => $cache_settings['browser_cache_expire_days'],
998 'browser_cache_expire_hours' => $cache_settings['browser_cache_expire_hours']
999 );
1000 $wpo_browser_cache->enable_browser_cache_command_handler($browser_cache);
1001 }
1002
1003 $message = '';
1004 $cache_result = WP_Optimize()->get_page_cache()->config->update($cache_settings);
1005 $minify_result = WP_Optimize()->get_minify()->minify_commands->save_minify_settings($minify_settings);
1006 $smush_result = WP_Optimize()->get_task_manager()->commands->update_smush_options($smush_settings);
1007 $webp_result = WP_Optimize()->get_task_manager()->commands->update_webp_options($smush_settings);
1008 $this->save_settings($database_settings);
1009
1010 if (is_wp_error($cache_enable_result)) {
1011 $message .= $cache_enable_result->get_error_message() . PHP_EOL;
1012 }
1013
1014 if (is_wp_error($cache_result)) {
1015 $message .= $cache_result->get_error_message() . PHP_EOL;
1016 }
1017
1018 if (!$minify_result['success']) {
1019 $message .= isset($minify_result['message']) ? $minify_result['message'] . PHP_EOL : '';
1020 $message .= isset($minify_result['error']) ? $minify_result['error'] . PHP_EOL : '';
1021 }
1022
1023 if (is_wp_error($smush_result)) {
1024 $message .= $smush_result->get_error_message() . PHP_EOL;
1025 }
1026
1027 if (is_wp_error($webp_result)) {
1028 $message .= $webp_result->get_error_message() . PHP_EOL;
1029 }
1030
1031 return array(
1032 'success' => true,
1033 'message' => empty($message) ? __('The settings were imported successfully.', 'wp-optimize') : $message
1034 );
1035 }
1036
1037 /**
1038 * Dismiss install or updated notice
1039 *
1040 * @return array
1041 */
1042 public function dismiss_install_or_update_notice() {
1043 if (!is_a(WP_Optimize()->get_install_or_update_notice(), 'WP_Optimize_Install_Or_Update_Notice') || !is_callable(array(WP_Optimize()->get_install_or_update_notice(), 'dismiss'))) {
1044 return array('errors' => array('The notice could not be dismissed. The method "dismiss" on the object instance "install_or_update_notice" does not seem to exist.'));
1045 }
1046
1047 if (!WP_Optimize()->get_install_or_update_notice()->dismiss()) {
1048 return array('errors' => array('The notice could not be dismissed. The settings could not be updated'));
1049 }
1050
1051 return array();
1052 }
1053
1054 /**
1055 * Run images trash command.
1056 *
1057 * @param array $params
1058 *
1059 * @return array
1060 */
1061 public function images_trash_command($params) {
1062 if (!class_exists('WP_Optimize_Images_Trash_Manager_Commands')) {
1063 return array(
1064 'errors' => array('WP_Optimize_Images_Trash_Manager_Commands class not found'),
1065 );
1066 }
1067
1068 // get posted command.
1069 $trash_command = $params['images_trash_command'] ?? '';
1070 // check if command is allowed.
1071 $allowed_commands = WP_Optimize_Images_Trash_Manager_Commands::get_allowed_ajax_commands();
1072
1073 if (!in_array($trash_command, $allowed_commands)) {
1074 return array(
1075 'errors' => array('No such command found'),
1076 );
1077 }
1078
1079 $results = call_user_func(array(WP_Optimize_Images_Trash_Manager()->commands, $trash_command), $params);
1080
1081 if (is_wp_error($results)) {
1082 $results = array(
1083 'errors' => array($results->get_error_message()),
1084 );
1085 }
1086
1087 return $results;
1088 }
1089
1090 /**
1091 * Power tweak handling
1092 *
1093 * @param array $params
1094 * @return array
1095 */
1096 public function power_tweak($params) {
1097 global $wp_optimize_premium;
1098 if (!is_a($wp_optimize_premium, 'WP_Optimize_Premium') || !property_exists($wp_optimize_premium, 'power_tweaks') || !isset($params['sub_action'])) return array(
1099 'errors' => array(__('No such command found', 'wp-optimize')),
1100 );
1101
1102 $action = $params['sub_action'];
1103 $data = $params['data'] ?: array();
1104 if (!isset($data['tweak'])) return array(
1105 'errors' => array(__('No tweak provided', 'wp-optimize'))
1106 );
1107
1108 $tweak = sanitize_title($data['tweak']);
1109 $pt = $wp_optimize_premium->power_tweaks;
1110 switch($action) {
1111 case 'activate':
1112 $result = $pt->activate($tweak);
1113 break;
1114 case 'deactivate':
1115 $result = $pt->deactivate($tweak);
1116 break;
1117 case 'run':
1118 $result = $pt->run($tweak);
1119 break;
1120 }
1121 if ($result && !is_wp_error($result)) {
1122 return is_array($result) ? array_merge(array('success' => true), $result) : array('success' => true, 'message' => $result);
1123 } else {
1124 // translators: %s is an action/command
1125 $error_message = is_wp_error($result) ? $result->get_error_message() : sprintf(__('The command %s failed', 'wp-optimize'), $action);
1126 return array(
1127 'success' => false,
1128 'errors' => array($error_message)
1129 );
1130 }
1131 }
1132
1133 /**
1134 * Ignores the table deletion warning for the current user
1135 *
1136 * @return array
1137 */
1138 public function user_ignores_table_deletion_warning() {
1139 return array(
1140 'success' => update_user_meta(get_current_user_id(), 'wpo-ignores-table-deletion-warning', true)
1141 );
1142 }
1143
1144 /**
1145 * Ignores the post meta deletion warning for the current user
1146 *
1147 * @return array
1148 */
1149 public function user_ignores_post_meta_deletion_warning() {
1150 return array(
1151 'success' => update_user_meta(get_current_user_id(), 'wpo-ignores-post-meta-deletion-warning', true)
1152 );
1153 }
1154
1155 /**
1156 * Ignores the orphaned relationship data deletion warning for the current user
1157 *
1158 * @return array
1159 */
1160 public function user_ignores_orphaned_relationship_data_deletion_warning() {
1161 return array(
1162 'success' => update_user_meta(get_current_user_id(), 'wpo-ignores-orphaned-relationship-data-deletion-warning', true)
1163 );
1164 }
1165
1166 /**
1167 * Exports unused images as a CSV file to the `uploads` folder
1168 *
1169 * @return array
1170 */
1171 public function export_csv() {
1172 WP_Optimization_images::instance()->output_csv();
1173 return array(
1174 'success' => true
1175 );
1176 }
1177
1178 /**
1179 * Build the HTML for the status report tab
1180 *
1181 * @return array
1182 */
1183 public function generate_status_report() {
1184 $status_data = $this->get_wp_optimize_status_report_data();
1185
1186 $html = WP_Optimize()->include_template('status/status-page-ajax.php', true, array(
1187 'report_data' => $status_data['report_data']
1188 ));
1189
1190 return array(
1191 'success' => true,
1192 'html' => $html,
1193 'replaceable_md_tags' => $status_data['replaceable_md_tags']
1194 );
1195 }
1196
1197 /**
1198 * Gz compress text logs using `gzencode` to generate valid gzip files
1199 *
1200 * @return array
1201 */
1202 public function generate_logs_zip() {
1203 $wpo_server_information = new WP_Optimize_Server_Information();
1204
1205 $logs = $wpo_server_information->get_logs();
1206
1207 $gz_available = function_exists('gzencode');
1208 $data = array();
1209 foreach ($logs as $path => $content) {
1210 if ($gz_available) {
1211 $log_content = gzencode($content);
1212
1213 if (false === $log_content) {
1214 $log_content = $content;
1215 $gz_available = false;
1216 }
1217 } else {
1218 $log_content = $content;
1219 }
1220
1221 $data[] = array(
1222 'src' => base64_encode($log_content),
1223 'name' => basename($path),
1224 'compressed' => $gz_available
1225 );
1226 }
1227
1228 return array(
1229 'success' => true,
1230 'data' => $data
1231 );
1232 }
1233
1234 /**
1235 * Save images dimensions options
1236 *
1237 * @param array $settings Settings data
1238 * @return array
1239 */
1240 public function save_images_dimension_option($settings) {
1241 $options = WP_Optimize()->get_options();
1242
1243 if (!empty($settings["images_dimensions"]) && "true" === $settings["images_dimensions"]) {
1244 $is_updated = $options->update_option('image_dimensions', 1);
1245 } else {
1246 $is_updated = $options->update_option('image_dimensions', 0);
1247 }
1248
1249 if ($is_updated || $options->update_option('image_dimensions_ignore_classes', sanitize_text_field($settings['ignore_classes']))) {
1250 wpo_cache_flush();
1251 }
1252
1253 return array(
1254 'success' => true
1255 );
1256 }
1257
1258 /**
1259 * Truncate 404 Logs Table
1260 *
1261 * @return array
1262 */
1263 public function truncate_404_logs() {
1264 global $wpdb;
1265 $log_table_name = WP_Optimize_Table_404_Detector::get_instance()->get_table_name();
1266 $success = false;
1267 $message = __('No 404 logs found.', 'wp-optimize');
1268 // Check if the table has any rows
1269 $log_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM `" .esc_sql($log_table_name) . "`");
1270 if ($log_count > 0) {
1271 if ($wpdb->query("TRUNCATE TABLE `" .esc_sql($log_table_name) . "`")) {
1272 $success = true;
1273 // translators: %s is the number of logs deleted
1274 $message = sprintf(_n('%s entry deleted from the 404 error log.', '%s entries deleted from the 404 error log.', $log_count, 'wp-optimize'), $log_count);
1275 } else {
1276 $message = __('An error occurred while deleting the 404 logs.', 'wp-optimize');
1277 }
1278 }
1279
1280 return array(
1281 'success' => $success,
1282 'message' => $message
1283 );
1284 }
1285
1286 // UDC specific endpoints.
1287
1288 /**
1289 * Get multiple widgets data.
1290 *
1291 * @param array $args Args.
1292 *
1293 * @return array
1294 */
1295 public function get_widgets_data($args) {
1296 // Widgets.
1297 $widgets = isset($args['widgets']) ? $args['widgets'] : array();
1298
1299 // Return early if no widgets supplied.
1300 if (!is_array($widgets) || empty($widgets)) {
1301 return array('error' => false, 'data' => array());
1302 }
1303
1304 // Get the data for each widget.
1305 $data = array();
1306
1307 // Loop through the widgets and get their data.
1308 foreach ($widgets as $widget) {
1309 $method = 'get_' . $widget . '_data';
1310
1311 if (method_exists($this, $method)) {
1312 $data[$widget] = $this->$method($args);
1313 }
1314 }
1315
1316 return array('error' => false, 'data' => $data);
1317 }
1318
1319 // Helper functions.
1320
1321 /**
1322 * Get the data for tables.
1323 *
1324 * @return array
1325 */
1326 public function get_table_list_data() {
1327 $wp_optimize = WP_Optimize();
1328
1329 $size = $this->optimizer->get_current_db_size();
1330
1331 $table_list = array();
1332
1333 // Check for InnoDB tables.
1334 // Check for windows servers.
1335 $tablesstatus = $wp_optimize->get_optimizer()->get_tables();
1336 $is_multisite_mode = $wp_optimize->is_multisite_mode();
1337 $no = 0;
1338 $row_usage = 0;
1339 $data_usage = 0;
1340 $index_usage = 0;
1341 $overhead_usage = 0;
1342 $small_overhead_size = 1048576;
1343
1344 foreach ($tablesstatus as $tablestatus) {
1345 $table_info = array();
1346
1347 $table_info['index'] = ++$no;
1348 $table_info['table_name'] = $tablestatus->Name;
1349 $table_info['Engine'] = $tablestatus->Engine;
1350 $table_info['is_optimizable'] = $tablestatus->is_optimizable ? 1 : 0;
1351 $table_info['blog_id'] = $tablestatus->blog_id;
1352 $table_info['plugin_status'] = $tablestatus->plugin_status;
1353 $table_info['Rows'] = intval($tablestatus->Rows);
1354 $table_info['Data_length'] = intval($tablestatus->Data_length);
1355 $table_info['Formatted_Data_length'] = $wp_optimize->format_size($tablestatus->Data_length);
1356 $table_info['Index_length'] = $tablestatus->Index_length;
1357 $table_info['Formatted_Index_length'] = $wp_optimize->format_size($tablestatus->Index_length);
1358 $table_info['Data_free'] = intval($tablestatus->Data_free);
1359 $table_info['Formatted_Data_free'] = $wp_optimize->format_size($tablestatus->Data_free);
1360 $table_info['Data_should_be_cleared'] = intval($tablestatus->Data_free) > $small_overhead_size ? 1 : 0;
1361 $table_info['wp_core_table'] = $tablestatus->wp_core_table;
1362
1363 $table_list[] = $table_info;
1364
1365 $row_usage += $tablestatus->Rows;
1366 $data_usage += $tablestatus->Data_length;
1367 $index_usage += $tablestatus->Index_length;
1368 $overhead_usage += $tablestatus->Data_free;
1369 }
1370
1371 $db_info = $this->optimizer->get_current_db_size();
1372
1373 return array(
1374 'error' => false,
1375 'data' => array(
1376 'is_multisite_mode' => $is_multisite_mode,
1377 'closed_plugins' => array('404-monitor', 'redirections'),
1378 'database_name' => DB_NAME,
1379 'database_size' => $db_info[0],
1380 'optimize_db' => false,
1381 'table_list_object_format' => $tablesstatus,
1382 'load_data' => WP_Optimize()->template_should_include_data(),
1383 'table_list' => $table_list,
1384 'total_size' => $size[0],
1385 'small_overhead_size' => $small_overhead_size,
1386 'no' => $no,
1387 'no_fomatted' => number_format_i18n($no),
1388 'row_usage' => number_format_i18n($row_usage),
1389 'data_usage' => $wp_optimize->format_size($data_usage),
1390 'index_usage' => $wp_optimize->format_size($index_usage),
1391 'tables_count' => count($table_list),
1392 // translators: %s is the number of table(s).
1393 'formatted_tables_count' => sprintf(_n('%s Table', '%s Tables', count($table_list), 'wp-optimize'), number_format_i18n(count($table_list))),
1394 'overhead_usage' => $overhead_usage,
1395 'overhead_usage_formatted' => $wp_optimize->format_size($overhead_usage),
1396 'translations' => array(
1397 'database_name' => __('Database Name', 'wp-optimize'),
1398 'refresh_data' => __('Refresh Data', 'wp-optimize'),
1399 'refreshing' => __('Refreshing...', 'wp-optimize'),
1400 'number' => __('No.', 'wp-optimize'),
1401 'table' => __('Table', 'wp-optimize'),
1402 'records' => __('Records', 'wp-optimize'),
1403 'data_size' => __('Data Size', 'wp-optimize'),
1404 'index_size' => __('Index Size', 'wp-optimize'),
1405 'type' => __('Type', 'wp-optimize'),
1406 'overhead' => __('Overhead', 'wp-optimize'),
1407 'total' => __('Total', 'wp-optimize'),
1408 'search_tables' => __('Search tables', 'wp-optimize'),
1409 'total_size_of_database' => __('Total size of database', 'wp-optimize'),
1410 ),
1411 )
1412 );
1413 }
1414
1415 /**
1416 * Get the data of wp-optimize widget.
1417 *
1418 * @return array
1419 */
1420 private function get_wp_optimize_data() {
1421 $wp_optimize = WP_Optimize();
1422
1423 $optimizations = $this->optimizer->sort_optimizations($this->optimizer->get_optimizations());
1424 $does_server_allow_table_optimization = $wp_optimize->get_server_compatibility_instance()->does_server_allow_table_optimization();
1425
1426 $optimizations_data = array();
1427
1428 foreach ($optimizations as $id => $optimization) {
1429 if ('optimizetables' == $id && false === $does_server_allow_table_optimization) continue;
1430 // If we don't want to show optimization on the first tab.
1431 if (false === $optimization->display_in_optimizations_list()) continue;
1432 // This is an array, with attributes dom_id, activated, settings_label, info; all values are strings.
1433 $optimization_data = $optimization->get_settings_html();
1434
1435 $optimization_data['info_raw'] = $optimization_data['info'];
1436
1437 $optimization_data['info'] = '<div>' . preg_replace('/<a\b[^>]*>(.*?)<\/a>/i', '$1', $optimization_data['info']) . '</div>';
1438
1439 $optimization_data['disable_optimization_button'] = false;
1440 $optimization_data['run_sort_order'] = $optimization->get_run_sort_order();
1441
1442 // Check if the DOM is optimize-db to generate a list of tables.
1443 if ('optimize-db' == $optimization_data['dom_id']) {
1444 $table_list = $this->optimizer->get_table_information();
1445
1446 // Make sure that optimization_table_inno_db is set.
1447 if ($table_list['inno_db_tables'] > 0 && 0 === $table_list['is_optimizable'] && 0 === $table_list['non_inno_db_tables']) {
1448 $optimization_data['disable_optimization_button'] = true;
1449 $optimization_data['activated'] = '';
1450 }
1451 }
1452
1453 $optimization_data['id'] = $id;
1454 $optimizations_data[] = $optimization_data;
1455 }
1456
1457 // Backup checkbox name.
1458 $backup_checkbox_name = 'enable-auto-backup';
1459
1460 return array(
1461 'items' => $optimizations_data,
1462 'optimize_button_multiple_caption' => __('Optimize selected', 'wp-optimize'),
1463 'optimize_button_caption' => apply_filters('wpo_run_button_caption', __('Optimize all', 'wp-optimize')),
1464 'backup_checkbox_name' => $backup_checkbox_name,
1465 'backup_enabled' => 'true' == $this->options->get_option($backup_checkbox_name, 'false'),
1466 'backup_checkbox_label' => __('Take backup before optimize', 'wp-optimize'),
1467 );
1468 }
1469
1470 /**
1471 * Get wpo status data.
1472 *
1473 * @return array
1474 */
1475 private function get_status_data() {
1476 $status_data = $this->get_all_status_data();
1477
1478 $data = array(
1479 'statuses' => array(),
1480 'test' => $status_data,
1481 );
1482
1483 // Schedule optimization.
1484 $schedule_optimization_description = __('Scheduled optimization is currently disabled.', 'wp-optimize');
1485 $schedule_optimization_icon = 'error';
1486
1487 if (!empty($status_data['scheduled_optimizations_enabled'])) {
1488 if ('Never' === $status_data['last_optimized']) {
1489 $schedule_optimization_description = __('There was no scheduled optimization.', 'wp-optimize');
1490 $schedule_optimization_icon = 'warning';
1491 } else {
1492 $lastopt = $status_data['last_optimized'];
1493 if (is_numeric($status_data['last_optimized'])) {
1494 $lastopt = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $status_data['last_optimized'] + ( get_option('gmt_offset') * HOUR_IN_SECONDS ));
1495 }
1496 // translators: %s is the last schedule optimization run date.
1497 $schedule_optimization_description = sprintf(esc_html__('Last scheduled optimization was at %s', 'wp-optimize'), esc_html($lastopt));
1498 $schedule_optimization_icon = 'success';
1499 }
1500 }
1501
1502 $data['statuses'][] = array(
1503 'title' => __('Schedule Optimization', 'wp-optimize'),
1504 'description' => $schedule_optimization_description,
1505 'icon' => $schedule_optimization_icon,
1506 );
1507
1508 // Schedule cleaning.
1509 $data['statuses'][] = array(
1510 'title' => __('Schedule Cleaning', 'wp-optimize'),
1511 'description' => empty($status_data['scheduled_optimizations_enabled']) ? __('Scheduled cleaning is currently disabled.', 'wp-optimize') : __('Scheduled cleaning is enabled.', 'wp-optimize'),
1512 'icon' => empty($status_data['scheduled_optimizations_enabled']) ? 'warning' : 'success',
1513 );
1514
1515 // Data retention.
1516 $data['statuses'][] = array(
1517 'title' => __('Data Retention', 'wp-optimize'),
1518 'description' => empty($status_data['retention_enabled']) ? __('The system is not keeping recent data or any revisions.', 'wp-optimize') : __('Data retention enabled.', 'wp-optimize'),
1519 'icon' => empty($status_data['retention_enabled']) ? 'error' : 'success',
1520 );
1521
1522 return $data;
1523 }
1524
1525 /**
1526 * Get all status data.
1527 *
1528 * @return array
1529 */
1530 private function get_all_status_data() {
1531 $wp_optimize = WP_Optimize();
1532
1533 $retention_enabled = $this->options->get_option('retention-enabled', 'false') === 'true';
1534 $retention_period = $this->options->get_option('retention-period', '2');
1535 $admin_page_url = $this->options->admin_page_url();
1536
1537 $revisions_retention_enabled = $this->options->get_option('revisions-retention-enabled', 'false') === 'true';
1538 $revisions_retention_count = $this->options->get_option('revisions-retention-count', '2');
1539
1540 $last_optimized = $this->options->get_option('last-optimized', 'Never');
1541
1542 if (!empty($last_optimized) && is_numeric($last_optimized)) {
1543 $last_optimized = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $last_optimized + (get_option('gmt_offset') * HOUR_IN_SECONDS));
1544 }
1545
1546 $scheduled_optimizations_enabled = false;
1547
1548 if (WP_Optimize::is_premium()) {
1549 $wp_optimize_premium = WP_Optimize_Premium();
1550 $scheduled_optimizations = $wp_optimize_premium->get_scheduled_optimizations();
1551
1552 if (!empty($scheduled_optimizations)) {
1553 foreach ($scheduled_optimizations as $optimization) {
1554 if (isset($optimization['status']) && 1 === absint($optimization['status'])) {
1555 $scheduled_optimizations_enabled = true;
1556 break;
1557 }
1558 }
1559 }
1560 } else {
1561 $scheduled_optimizations_enabled = $this->options->get_option('schedule', 'false') == 'true';
1562 }
1563
1564 $total_cleaned = null;
1565 $total_cleanup_size = '';
1566 $corrupted_tables_count = null;
1567 $next_optimization_timestamp = 0;
1568
1569 if ($scheduled_optimizations_enabled) {
1570
1571 $next_optimization_timestamp = wp_next_scheduled('wpo_cron_event2');
1572 $filtered_next_optimization_timestamp = apply_filters('wpo_cron_next_event', $next_optimization_timestamp);
1573 $next_optimization_timestamp = is_int($filtered_next_optimization_timestamp) ? $filtered_next_optimization_timestamp : $next_optimization_timestamp;
1574
1575 if ($next_optimization_timestamp) {
1576
1577 $next_optimization_timestamp = $next_optimization_timestamp + 60 * 60 * get_option('gmt_offset');
1578
1579 $wp_optimize->cron_activate();
1580 }
1581
1582 $total_cleaned = $this->options->get_option('total-cleaned');
1583 $total_cleaned_num = floatval($total_cleaned);
1584
1585 if ($total_cleaned_num > 0) {
1586 $total_cleanup_size = $wp_optimize->format_size($total_cleaned);
1587 }
1588
1589 $corrupted_tables_count = $this->options->get_option('corrupted-tables-count', 0);
1590 }
1591
1592 return array(
1593 'last_optimized' => $last_optimized,
1594 'total_cleaned' => $total_cleaned,
1595 'total_cleanup_size' => $total_cleanup_size,
1596 'corrupted_tables_count' => $corrupted_tables_count,
1597 'admin_page_url' => $admin_page_url,
1598 'retention_enabled' => $retention_enabled,
1599 'retention_period' => $retention_period,
1600 'revisions_retention_enabled' => $revisions_retention_enabled,
1601 'revisions_retention_count' => $revisions_retention_count,
1602 'scheduled_optimizations_enabled' => $scheduled_optimizations_enabled,
1603 'next_optimization_timestamp' => $next_optimization_timestamp,
1604 );
1605 }
1606
1607 /**
1608 * Get wp-optimize tab top nav data.
1609 *
1610 * @return array
1611 */
1612 private function get_wp_optimize_top_nav_data() {
1613 return array(
1614 'title' => __('Performance Overview', 'wp-optimize'),
1615 'table_info' => __('Table Info', 'wp-optimize'),
1616 'performance_settings' => __('Performance Settings', 'wp-optimize'),
1617 );
1618 }
1619
1620 /**
1621 * Get wp-optimize tab top nav settings page data.
1622 *
1623 * @return array
1624 */
1625 private function get_wp_optimize_settings_top_nav_data() {
1626 return array(
1627 'title' => __('Performance Settings', 'wp-optimize'),
1628 'settings_saved_prompt' => __('Changes saved automatically', 'wp-optimize'),
1629 'settings_not_saved_prompt' => __('Changes not saved - please fill all the fields', 'wp-optimize'),
1630 );
1631 }
1632
1633 /**
1634 * Get if wp-optimize premium is installed.
1635 *
1636 * @return array
1637 */
1638 private function get_is_premium_data() {
1639 $is_premium = WP_Optimize::is_premium();
1640 $upgrade_to_premium_data = array();
1641
1642 if (false === $is_premium) {
1643 $upgrade_to_premium_data = array(
1644 'heading' => __('WP-Optimize premium', 'wp-optimize'),
1645 'checklist' => array(
1646 __('Optimize individual tables', 'wp-optimize'),
1647 __('Sophisticated scheduling', 'wp-optimize'),
1648 __('Lazy loading', 'wp-optimize'),
1649 __('Optimization preview', 'wp-optimize'),
1650 __('More caching options', 'wp-optimize'),
1651 __('Remove unwanted images', 'wp-optimize'),
1652 __('Multi language & currency support', 'wp-optimize'),
1653 ),
1654 'cta' => array(
1655 'text' => __('Upgrade Now', 'wp-optimize'),
1656 'url' => 'https://teamupdraft.com/wp-optimize/pricing/',
1657 ),
1658 );
1659 }
1660
1661 return array(
1662 'is_premium' => $is_premium,
1663 'upgrade_to_premium_data' => $upgrade_to_premium_data,
1664 );
1665 }
1666
1667 /**
1668 * WIP: Get system overview data.
1669 *
1670 * @return array
1671 */
1672 private function get_system_overview_data() {
1673 $wp_optimize = WP_Optimize();
1674 $status_data = $this->get_all_status_data();
1675
1676 // Data.
1677 $data = array(
1678 'data' => array(),
1679 );
1680
1681 // Lazy load.
1682 $lazy_load_settings = $this->options->get_option('lazyload', array(
1683 'images' => false,
1684 'iframes' => false,
1685 'skip_classes' => '',
1686 ));
1687
1688 $lazy_load_enabled = $lazy_load_settings['images'] || $lazy_load_settings['iframes'];
1689
1690 if (WP_Optimize::is_premium()) {
1691 $lazy_load_enabled = $lazy_load_enabled || $lazy_load_settings['backgrounds'];
1692 }
1693
1694 $data['data'][] = array(
1695 'title' => __('Lazy loading', 'wp-optimize'),
1696 'description' => $lazy_load_enabled ? __('Enabled', 'wp-optimize') : __('Disabled', 'wp-optimize'),
1697 'status' => $lazy_load_enabled ? 'success' : 'error',
1698 );
1699
1700 // Page caching.
1701 $cache = $wp_optimize->get_page_cache();
1702 $page_caching_enabled = $cache->is_enabled();
1703 $data['data'][] = array(
1704 'title' => __('Page caching', 'wp-optimize'),
1705 'description' => $page_caching_enabled ? __('Enabled', 'wp-optimize') : __('Disabled', 'wp-optimize'),
1706 'status' => $page_caching_enabled ? 'success' : 'error',
1707 );
1708
1709 // Schedule cleaning.
1710 $data['data'][] = array(
1711 'title' => __('Scheduled clean-up', 'wp-optimize'),
1712 'description' => empty($status_data['scheduled_optimizations_enabled']) ? __('Disabled', 'wp-optimize') : __('Enabled', 'wp-optimize'),
1713 'status' => empty($status_data['scheduled_optimizations_enabled']) ? 'error' : 'success',
1714 );
1715
1716 if (!empty($status_data['scheduled_optimizations_enabled'])) {
1717 $data['data'][] = array(
1718 'title' => __('Next scheduled date', 'wp-optimize'),
1719 'description' => esc_html(gmdate(get_option('date_format') . ' ' . get_option('time_format'), $status_data['next_optimization_timestamp'])),
1720 'status' => '',
1721 );
1722 }
1723
1724 return $data;
1725 }
1726
1727 /**
1728 * Get wp-optimize general settings data.
1729 *
1730 * @return array
1731 */
1732 private function get_wp_optimize_general_settings_data() {
1733 $retention_period = max((int) $this->options->get_option('retention-period', '2'), 1);
1734 $retention_enabled = 'true' === $this->options->get_option('retention-enabled');
1735
1736 $revisions_retention_count = (int) $this->options->get_option('revisions-retention-count', '2');
1737 $revisions_retention_enabled = 'true' === $this->options->get_option('revisions-retention-enabled');
1738
1739 $minify_or_cache_enabled = WP_Optimize()->get_page_cache()->is_enabled() || wp_optimize_minify_config()->get('enabled');
1740
1741 return array(
1742 'retention_period' => $retention_period,
1743 'retention_enabled' => $retention_enabled,
1744 'revisions_retention_count' => $revisions_retention_count,
1745 'revisions_retention_enabled' => $revisions_retention_enabled,
1746 'minify_or_cache_enabled' => $minify_or_cache_enabled,
1747 );
1748 }
1749
1750 /**
1751 * Get wp-optimize trackback settings data.
1752 *
1753 * @return array
1754 */
1755 private function get_wp_optimize_trackback_toggle_settings_data() {
1756 $wp_optimize = WP_Optimize();
1757
1758 $trackback_action_arr = $this->options->get_option('trackbacks_action', array());
1759
1760 $enabled = false;
1761 $last_action_timestamp = '';
1762 $empty = true;
1763
1764 if (!empty($trackback_action_arr)) {
1765 $empty = false;
1766 $last_action_timestamp = $wp_optimize->format_date_time($trackback_action_arr['timestamp']);
1767 if ($trackback_action_arr['action']) {
1768 $enabled = true;
1769 }
1770 }
1771
1772 return array(
1773 'enabled' => $enabled,
1774 'last_action_timestamp' => $last_action_timestamp,
1775 'empty' => $empty
1776 );
1777 }
1778
1779 /**
1780 * Get wp-optimize comments settings data.
1781 *
1782 * @return array
1783 */
1784 private function get_wp_optimize_comments_toggle_settings_data() {
1785 $wp_optimize = WP_Optimize();
1786
1787 $comments_action_arr = $this->options->get_option('comments_action', array());
1788
1789 $enabled = false;
1790 $last_action_timestamp = '';
1791 $empty = true;
1792
1793 if (!empty($comments_action_arr)) {
1794 $empty = false;
1795 $last_action_timestamp = $wp_optimize->format_date_time($comments_action_arr['timestamp']);
1796 if ($comments_action_arr['action']) {
1797 $enabled = true;
1798 }
1799 }
1800
1801 return array(
1802 'enabled' => $enabled,
1803 'last_action_timestamp' => $last_action_timestamp,
1804 'empty' => $empty
1805 );
1806 }
1807
1808 /**
1809 * Get wp-optimize logging settings.
1810 *
1811 * @return array
1812 */
1813 private function get_wp_optimize_logging_settings_data() {
1814 $wp_optimize = WP_Optimize();
1815
1816 $logger_classes_info = $wp_optimize->get_loggers_classes_info();
1817
1818 $logger_classes = array();
1819 $logger_classes_fields = array();
1820
1821 foreach ($logger_classes_info as $logger_class => $logger_class_data) {
1822 if (empty($logger_class_data['available'])) {
1823 continue;
1824 }
1825
1826 $logger_classes[] = array(
1827 'value' => $logger_class,
1828 'name' => $logger_class_data['description'],
1829 );
1830
1831 // For now we only have one option for all the fields, therefore taking only one.
1832 foreach ($logger_class_data['options'] as $name => $value) {
1833 $logger_class_field_data = array(
1834 'name' => $name,
1835 'validator' => '',
1836 'placeholder' => '',
1837 'controller_value' => $logger_class,
1838 );
1839
1840 if (is_array($value)) {
1841 $logger_class_field_data['validator'] = isset($value[1]) ? $value[1] : '';
1842 $logger_class_field_data['placeholder'] = isset($value[0]) ? $value[0] : '';
1843 } else {
1844 $logger_class_field_data['placeholder'] = $value;
1845 }
1846
1847 $logger_classes_fields[] = $logger_class_field_data;
1848 }
1849 }
1850
1851 $loggers_data = array(
1852 'loggers_classes_info' => $logger_classes_info,
1853 'logger_classes' => $logger_classes,
1854 'logger_classes_fields' => $logger_classes_fields,
1855 'existing_loggers' => array(),
1856 );
1857
1858 $loggers = $wp_optimize->wpo_loggers();
1859
1860 foreach ($loggers as $logger) {
1861 $logger_data = array(
1862 'id' => strtolower(get_class($logger)),
1863 'status' => ($logger->is_enabled() && $logger->is_available()) ? 'active' : 'inactive',
1864 'status_text' => ($logger->is_enabled() && $logger->is_available()) ? __('Active', 'wp-optimize') : __('Inactive', 'wp-optimize'),
1865 'existing_logger_classes' => array(),
1866 'existing_logger_classes_fields' => array(),
1867 'description' => $logger->get_description(),
1868 'options_text' => $logger->get_options_text(),
1869 'options_list' => array(),
1870 'is_enabled' => $logger->is_enabled(),
1871 'is_available' => $logger->is_available()
1872 );
1873
1874 $options_list = $logger->get_options_list();
1875 $options_values = $logger->get_options_values();
1876
1877 $options = array();
1878
1879 if (!empty($options_list)) {
1880 foreach ($options_list as $option_name => $placeholder) {
1881 // check if settings item defined as array.
1882 if (is_array($placeholder)) {
1883 $validate = $placeholder[1];
1884 $placeholder = $placeholder[0];
1885 } else {
1886 $validate = '';
1887 }
1888
1889 $data_validate_attr = ('' !== $validate ? 'data-validate="'.esc_attr($validate).'"' : '');
1890
1891 $options[$option_name] = array(
1892 'name' => $option_name,
1893 'placeholder' => $placeholder,
1894 'value' => $options_values[$option_name],
1895 'data_validate_attr' => $data_validate_attr,
1896 );
1897
1898 }
1899 $logger_data['options_list'] = $options;
1900 }
1901
1902 foreach ($loggers_data['logger_classes'] as $classes) {
1903 $logger_data['existing_logger_classes'][] = array(
1904 'value' => $classes['value'],
1905 'name' => $classes['name'],
1906 'selected' => $logger_data['id'] === $classes['value'],
1907 );
1908 }
1909
1910 foreach ($loggers_data['logger_classes_fields'] as $field) {
1911 // If the field has existing value fill it else add as it is.
1912 if (!empty($options[$field['name']])) {
1913 $field['value'] = $options[$field['name']]['value'];
1914 $field['selected'] = true;
1915 $logger_data['existing_logger_classes_fields'][] = $field;
1916 } else {
1917 $logger_data['existing_logger_classes_fields'][] = $field;
1918 }
1919 }
1920
1921 $loggers_data['existing_loggers'][] = $logger_data;
1922 }
1923
1924 return $loggers_data;
1925 }
1926
1927 /**
1928 * Get wp-optimize schedule cleanup settings data.
1929 *
1930 * @return array
1931 */
1932 private function get_wp_optimize_schedule_cleanup_settings_data() {
1933 $is_premium = WP_Optimize::is_premium();
1934
1935 $return_data = array(
1936 'is_premium' => $is_premium,
1937 'data' => array(),
1938 );
1939 $scheduled_optimizations_enabled = false;
1940 $wp_optimize = WP_Optimize();
1941
1942 if (!$is_premium) {
1943 $enabled = 'true' === $this->options->get_option('schedule');
1944
1945 $schedule_type_saved_id = $this->options->get_option('schedule-type', 'wpo_weekly');
1946
1947 // Backwards compatibility:
1948 if ('wpo_otherweekly' == $schedule_type_saved_id) $schedule_type_saved_id = 'wpo_fortnightly';
1949
1950 $schedule_types = WP_Optimize::get_schedule_types();
1951
1952 $schedule_options = array_map(
1953 function ($value, $key) use ($schedule_type_saved_id) {
1954 return array(
1955 'id' => $key,
1956 'label' => $value,
1957 'selected' => ($key === $schedule_type_saved_id)
1958 );
1959 },
1960 $schedule_types,
1961 array_keys($schedule_types)
1962 );
1963
1964 $wpo_auto_options = $this->options->get_option('auto');
1965
1966 $optimizations = $this->optimizer->sort_optimizations($this->optimizer->get_optimizations());
1967
1968 $optimizations_data = array();
1969
1970 $does_server_allow_table_optimization = WP_Optimize()->get_server_compatibility_instance()->does_server_allow_table_optimization();
1971
1972 foreach ($optimizations as $id => $optimization) {
1973 if (empty($optimization->available_for_auto)) continue;
1974
1975 if ('optimizetables' == $id && false === $does_server_allow_table_optimization) continue;
1976
1977 $auto_id = $optimization->get_auto_id();
1978
1979 $auto_dom_id = 'wp-optimize-auto-'.$auto_id;
1980
1981 $setting_activated = (empty($wpo_auto_options[$auto_id]) || 'false' == $wpo_auto_options[$auto_id]) ? false : true;
1982
1983 $optimizations_data[] = array(
1984 'id' => $auto_id,
1985 'dom_id' => $auto_dom_id,
1986 'activated' => $setting_activated,
1987 'label' => $optimization->get_auto_option_description(),
1988 );
1989 }
1990
1991 $next_optimization_timestamp = 0;
1992
1993 $scheduled_optimizations_enabled = $this->options->get_option('schedule', 'false') == 'true';
1994
1995 if ($scheduled_optimizations_enabled) {
1996 $next_optimization_timestamp = apply_filters('wpo_cron_next_event', wp_next_scheduled('wpo_cron_event2'));
1997
1998 if ($next_optimization_timestamp) {
1999
2000 $next_optimization_timestamp = $next_optimization_timestamp + 60 * 60 * get_option('gmt_offset');
2001 }
2002 }
2003
2004 $return_data['data'] = array(
2005 'enabled' => $enabled,
2006 'schedule_options' => $schedule_options,
2007 'schedule_type_saved_id' => $schedule_type_saved_id,
2008 'optimizations' => $optimizations_data,
2009 'next_optimization' => $next_optimization_timestamp ? esc_html(gmdate(get_option('date_format') . ' ' . get_option('time_format'), $next_optimization_timestamp)) : '',
2010 'premium_version_link' => $wp_optimize->premium_version_link,
2011 'enable_schedule' => $this->options->get_option('schedule'),
2012 );
2013 } else {
2014 $wp_optimize_premium = WP_Optimize_Premium();
2015 $auto_options = $wp_optimize_premium->get_scheduled_optimizations();
2016 $auto_optimizations = $wp_optimize_premium->get_auto_optimizations();
2017
2018 $next_optimization_timestamp = 0;
2019
2020 if (!empty($auto_options)) {
2021 foreach ($auto_options as $optimization) {
2022 if (isset($optimization['status']) && 1 == $optimization['status']) {
2023 $scheduled_optimizations_enabled = true;
2024 break;
2025 }
2026 }
2027 }
2028
2029 $all_provided_optimizations = array_values($auto_optimizations);
2030 $all_schedule_types = WP_Optimize::get_schedule_types();
2031 $week_days = WP_Optimize_Premium::get_week_days();
2032 $days = WP_Optimize_Premium::get_days();
2033 $weeks = array('1st' => __('1st', 'wp-optimize'), '2nd' => __('2nd', 'wp-optimize'));
2034
2035 $optimizations = array();
2036
2037 foreach ($auto_options as $index => $event) {
2038 $optimization = array(
2039 'index' => $index,
2040 );
2041 if (!isset($event['optimization'])) {
2042 $event['optimization'] = array();
2043 }
2044 foreach ($event as $key => $value) {
2045 switch ($key) {
2046 case 'optimization':
2047 $optimization['optimization'] = array();
2048 foreach ($all_provided_optimizations as $this_optimization) {
2049 if (in_array($this_optimization['id'], $value)) {
2050 $this_optimization['selected'] = true;
2051 }
2052 $optimization['optimization'][] = $this_optimization;
2053 }
2054 break;
2055 case 'schedule_type':
2056 $optimization['schedule_types'] = array();
2057 foreach ($all_schedule_types as $key => $this_schedule_value) {
2058 $this_schedule_type = array();
2059 $this_schedule_type['label'] = $this_schedule_value;
2060 $this_schedule_type['selected'] = $key === $value;
2061 $this_schedule_type['value'] = $key;
2062 $optimization['schedule_types'][] = $this_schedule_type;
2063 }
2064 break;
2065 case 'date':
2066 $optimization['date'] = $value;
2067 break;
2068 case 'time':
2069 $optimization['time'] = $value;
2070 break;
2071 case 'week':
2072 $optimization['weeks'] = array();
2073 foreach ($weeks as $key => $this_week_value) {
2074 $this_week = array();
2075 $this_week['label'] = $this_week_value;
2076 $this_week['selected'] = $key === $value;
2077 $this_week['value'] = $key;
2078 $optimization['weeks'][] = $this_week;
2079 }
2080 break;
2081 case 'day':
2082 $optimization['days'] = array();
2083 foreach ($week_days as $key => $this_week_day_value) {
2084 $this_week_day = array();
2085 $this_week_day['label'] = $this_week_day_value;
2086 $this_week_day['selected'] = $key === $value;
2087 $this_week_day['value'] = $key;
2088 $optimization['days'][] = $this_week_day;
2089 }
2090 break;
2091 case 'day_number':
2092 $optimization['day_numbers'] = array();
2093 foreach ($days as $key => $this_day_value) {
2094 $this_day = array();
2095 $this_day['label'] = $this_day_value;
2096 $this_day['selected'] = absint($key) === absint($value);
2097 $this_day['value'] = $key;
2098 $optimization['day_numbers'][] = $this_day;
2099 }
2100 break;
2101 case 'status':
2102 $optimization['status'] = '1' === $value;
2103 break;
2104 }
2105 }
2106 $optimizations[] = $optimization;
2107 }
2108
2109 if ($scheduled_optimizations_enabled) {
2110 $next_optimization_timestamp = apply_filters('wpo_cron_next_event', wp_next_scheduled('wpo_cron_event2'));
2111
2112 if ($next_optimization_timestamp) {
2113 $next_optimization_timestamp = $next_optimization_timestamp + 60 * 60 * get_option('gmt_offset');
2114 }
2115 }
2116
2117 $return_data['data'] = array(
2118 'optimizations' => $optimizations,
2119 'provided_optimizations' => $all_provided_optimizations,
2120 'provided_schedule_types' => $all_schedule_types,
2121 'today_date' => gmdate("Y-m-d"),
2122 'weeks' => $weeks,
2123 'week_days' => $week_days,
2124 'days' => $days,
2125 'next_optimization' => $next_optimization_timestamp ? esc_html(gmdate(get_option('date_format') . ' ' . get_option('time_format'), $next_optimization_timestamp)) : '',
2126 'is_auto_innodb' => $this->options->get_option('auto-innodb'),
2127 'scheduled_optimizations' => $auto_options,
2128 'auto_optimizations' => $auto_optimizations,
2129 'warning_url' => $wp_optimize->wp_optimize_url('https://teamupdraft.com/documentation/wp-optimize/topics/database-optimization/faqs/', __('Warning: you should read the FAQ about the risks of this operation first.', 'wp-optimize'), '', '', true)
2130 );
2131 }
2132
2133 // Add the translations.
2134 $return_data['data']['translations'] = array(
2135 'scheduled_optimization' => __('Scheduled Optimization', 'wp-optimize'),
2136 'next_schedule_run' => __('Next scheduled run', 'wp-optimize'),
2137 'no_scheduled_optimization' => __('No scheduled optimization', 'wp-optimize'),
2138 'add_optimization_tasks' => __('Add optimization tasks', 'wp-optimize'),
2139 'select_all' => __('Select all', 'wp-optimize'),
2140 'unselect_all' => __('Un-Select All', 'wp-optimize'),
2141 'select_schedule' => __('Select schedule', 'wp-optimize'),
2142 'run_an_optimization_every' => __('Run an optimization every', 'wp-optimize'),
2143 'add_optimization' => __('Add optimization', 'wp-optimize'),
2144 );
2145
2146 return $return_data;
2147 }
2148
2149 /**
2150 * Get wp-optimize status report data.
2151 *
2152 * @return array
2153 */
2154 private function get_wp_optimize_status_report_data() {
2155 $system_status = WP_Optimize_System_Status_Report::get_instance();
2156 $report_data = $system_status->generate_report();
2157 $replaceable_md_tags = $system_status->get_replaceable_md_tags();
2158
2159 return array('report_data' => $report_data, 'replaceable_md_tags' => $replaceable_md_tags);
2160 }
2161
2162 /**
2163 * Get data for the UDC reports.
2164 *
2165 * @return array
2166 */
2167 public function get_report_data() {
2168 $wp_optimize = WP_Optimize();
2169 $schedule_types = WP_Optimize::get_schedule_types();
2170 $scheduled_optimizations_enabled = $this->options->get_option('schedule', 'false') == 'true';
2171 $schedule_frequency = '';
2172 $unused_posts_images = 0;
2173 $optimized_images_percentage = 0;
2174
2175 if (WP_Optimize::is_premium()) {
2176 $wp_optimize_premium = WP_Optimize_Premium();
2177 $scheduled_optimizations = $wp_optimize_premium->get_scheduled_optimizations();
2178
2179 if (!empty($scheduled_optimizations)) {
2180 foreach ($scheduled_optimizations as $optimization) {
2181 if (isset($optimization['status']) && 1 === absint($optimization['status'])) {
2182 $scheduled_optimizations_enabled = true;
2183 $schedule_frequency = $schedule_types[$optimization['schedule_type']] ?? '';
2184 break;
2185 }
2186 }
2187 }
2188
2189 // Force calculate unused images.
2190 WP_Optimization_images::instance()->get_optimization_info();
2191 $unused_posts_images = WP_Optimization_images::instance()->get_unused_images_count();
2192 $optimized_images_percentage = WP_Optimize_Bulk_Smush::get_instance()->get_optimized_images_percentage();
2193
2194 } elseif ($scheduled_optimizations_enabled) {
2195 $schedule_type_saved_id = $this->options->get_option('schedule-type', 'wpo_weekly');
2196
2197 // Backwards compatibility:
2198 if ('wpo_otherweekly' == $schedule_type_saved_id) $schedule_type_saved_id = 'wpo_fortnightly';
2199
2200 $schedule_frequency = $schedule_types[$schedule_type_saved_id] ?? '';
2201 }
2202
2203 $total_cleaned = $this->options->get_option('total-cleaned-previous-month');
2204 $total_cleanup_size = $wp_optimize->format_size($total_cleaned);
2205
2206 $cache = $wp_optimize->get_page_cache();
2207 $page_caching_enabled = $cache->is_enabled();
2208
2209 $minification_enabled = wp_optimize_minify_config()->get('enabled') ?? false;
2210
2211 return array(
2212 'report_data' => array(
2213 'is_premium' => WP_Optimize::is_premium(),
2214 'scheduled_optimizations_enabled' => $scheduled_optimizations_enabled,
2215 'schedule_frequency' => $schedule_frequency,
2216 'total_cleaned' => $total_cleaned,
2217 'total_cleanup_size' => $total_cleanup_size,
2218 'unused_posts_images' => $unused_posts_images,
2219 'page_caching_enabled' => $page_caching_enabled,
2220 'minification_enabled' => $minification_enabled,
2221 'optimized_images_percentage' => $optimized_images_percentage . '%',
2222 ),
2223 'variables' => array(
2224 /* translators: %s is the cleaned up memory size. */
2225 'performance_highlights' => sprintf(__('%s saved', 'wp-optimize'), $total_cleanup_size),
2226 ),
2227 );
2228 }
2229 }
2230