PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.6.0
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.6.0
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.6.0, at includes/class-wp-optimize-commands.php

2,382 lines 76.8 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 (!WP_Optimize()->current_user_can()) {
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 (!WP_Optimize()->current_user_can()) {
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 (!WP_Optimize()->current_user_can()) {
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 (!WP_Optimize()->current_user_can()) {
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 (!WP_Optimize()->current_user_can()) {
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() && !WP_Optimize()->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 (!WP_Optimize()->current_user_can()) {
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 * [For UpdraftCentral] Returns selected WP-Optimize toggleable settings optimized for quick access
1417 *
1418 * @return WP_Error|array
1419 */
1420 private function get_quick_settings_data() {
1421 if (!WP_Optimize()->current_user_can()) {
1422 return $this->request_error('insufficient_privilege');
1423 }
1424
1425 $options = WP_Optimize()->get_options();
1426 $default_lazyload_settings = array(
1427 'images' => false,
1428 'backgrounds' => false,
1429 'iframes' => false,
1430 'youtube_preview' => false,
1431 'skip_classes' => '',
1432 );
1433
1434 $lazyload = wp_parse_args($options->get_option('lazyload', array()), $default_lazyload_settings);
1435 foreach ($lazyload as $key => $value) {
1436 if ('skip_classes' !== $key) {
1437 $lazyload[$key] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
1438 }
1439 }
1440
1441 $trackbacks = $options->get_option('trackbacks_action', array());
1442 $comments = $options->get_option('comments_action', array());
1443
1444 $gzip_compression_enabled = WP_Optimize()->get_gzip_compression()->is_gzip_compression_enabled(true);
1445
1446 $settings = array(
1447 'scheduled_cleanup' => 'true' === $options->get_option('schedule'),
1448 'backup_enabled' => 'true' === $options->get_option('enable-auto-backup', 'false'),
1449 'comments' => (!empty($comments) && $comments['action']) ? true : false,
1450 'trackbacks' => (!empty($trackbacks) && $trackbacks['action']) ? true : false,
1451 'autosmush' => $options->get_option('autosmush'),
1452 'page_caching' => WP_Optimize()->get_page_cache()->is_enabled(),
1453 'minify' => wp_optimize_minify_config()->get('enabled'),
1454 'image_dimensions' => $options->get_option('image_dimensions'),
1455 '404_detector' => $options->get_option('404_detector'),
1456 'webp_conversion' => $options->get_option('webp_conversion'),
1457 'gzip_compression' => (!is_wp_error($gzip_compression_enabled) && $gzip_compression_enabled) ? true : false,
1458 );
1459
1460 $settings = array_map(function($value) {
1461 return filter_var($value, FILTER_VALIDATE_BOOLEAN);
1462 }, $settings);
1463
1464 return array_merge($settings, array('lazyload' => $lazyload));
1465 }
1466
1467 /**
1468 * [For UpdraftCentral] Saves the selected WP-Optimize toggleable settings
1469 *
1470 * @param array $settings Parameters required for the requested action
1471 *
1472 * @return WP_Error|array
1473 */
1474 public function save_quick_settings($settings) {
1475 if (!WP_Optimize()->current_user_can()) {
1476 return $this->request_error('insufficient_privilege');
1477 }
1478
1479 if (!empty($settings) && is_array($settings)) {
1480 $settings = array_map(function($value) {
1481 return filter_var($value, FILTER_VALIDATE_BOOLEAN);
1482 }, $settings);
1483 }
1484
1485 try {
1486
1487 if (isset($settings['enable-404-detector'])) {
1488 WP_Optimize()->get_options()->update_option('404_detector', (int) $settings['enable-404-detector']);
1489 }
1490
1491 if (isset($settings['enable-auto-backup'])) {
1492 WP_Optimize()->get_options()->update_option('enable-auto-backup', $settings['enable-auto-backup'] ? 'true' : 'false');
1493
1494 WP_Optimize()->get_options()->update_option('enable-auto-backup-scheduled', $settings['enable-auto-backup'] ? 'true' : 'false');
1495 }
1496
1497 if (isset($settings['enable-auto-compression'])) {
1498 Updraft_Smush_Manager()->update_smush_options(array('autosmush' => (int) $settings['enable-auto-compression']));
1499 }
1500
1501 if (isset($settings['enable-comments'])) {
1502 $this->enable_or_disable_feature(array(
1503 'type' => 'comments',
1504 'enable' => $settings['enable-comments'],
1505 ));
1506 }
1507
1508 if (isset($settings['enable-trackbacks'])) {
1509 $this->enable_or_disable_feature(array(
1510 'type' => 'trackbacks',
1511 'enable' => $settings['enable-trackbacks'],
1512 ));
1513 }
1514
1515 if (isset($settings['enable-minify'])) {
1516 wp_optimize_minify_config()->update(array('enabled' => $settings['enable-minify']));
1517 }
1518
1519 if (isset($settings['enable-page-caching'])) {
1520 $wpo_page_cache = WP_Optimize()->get_page_cache();
1521
1522 if ($settings['enable-page-caching']) {
1523 $wpo_page_cache->enable(true);
1524 } else {
1525 $wpo_page_cache->disable();
1526 }
1527 }
1528
1529 if (isset($settings['enable-scheduled-cleanup'])) {
1530 WP_Optimize()->get_options()->update_option('schedule', $settings['enable-scheduled-cleanup'] ? 'true' : 'false');
1531 }
1532
1533 if (isset($settings['enable-webp-conversion'])) {
1534 WP_Optimize()->get_webp_instance()->save_webp_settings(array('webp_conversion' => $settings['enable-webp-conversion']));
1535 }
1536
1537 if (isset($settings['enable-images-dimensions'])) {
1538 WP_Optimize()->get_options()->update_option('image_dimensions', (int) $settings['enable-images-dimensions']);
1539 }
1540
1541 if (isset($settings['enable-lazy-loading'])) {
1542 $value = (int) $settings['enable-lazy-loading'];
1543 $options = WP_Optimize()->get_options();
1544
1545 $lazyload = $options->get_option('lazyload');
1546 $lazy_settings = array(
1547 'images' => $value,
1548 'iframes' => $value,
1549 'backgrounds' => $value,
1550 'youtube_preview' => $value,
1551 'skip_classes' => !empty($lazyload['skip_classes']) ? $lazyload['skip_classes'] : '',
1552 );
1553 $options->save_lazy_load_settings(array('lazyload' => $lazy_settings));
1554 }
1555
1556 if (isset($settings['enable-gzip-compression'])) {
1557 $this->enable_gzip_compression(array('enable' => $settings['enable-gzip-compression']));
1558 }
1559
1560 } catch (Throwable $e) {
1561 return $this->request_error('quick_settings_save_error', null, array('message' => $e->getMessage(), 'settings' => $this->get_quick_settings_data()));
1562 }
1563
1564 return array('settings' => $this->get_quick_settings_data());
1565 }
1566
1567 /**
1568 * Get the data of wp-optimize widget.
1569 *
1570 * @return array
1571 */
1572 private function get_wp_optimize_data() {
1573 $wp_optimize = WP_Optimize();
1574
1575 $optimizations = $this->optimizer->sort_optimizations($this->optimizer->get_optimizations());
1576 $does_server_allow_table_optimization = $wp_optimize->get_server_compatibility_instance()->does_server_allow_table_optimization();
1577
1578 $optimizations_data = array();
1579
1580 foreach ($optimizations as $id => $optimization) {
1581 if ('optimizetables' == $id && false === $does_server_allow_table_optimization) continue;
1582 // If we don't want to show optimization on the first tab.
1583 if (false === $optimization->display_in_optimizations_list()) continue;
1584 // This is an array, with attributes dom_id, activated, settings_label, info; all values are strings.
1585 $optimization_data = $optimization->get_settings_html();
1586
1587 $optimization_data['info_raw'] = $optimization_data['info'];
1588
1589 $optimization_data['info'] = '<div>' . preg_replace('/<a\b[^>]*>(.*?)<\/a>/i', '$1', $optimization_data['info']) . '</div>';
1590
1591 $optimization_data['disable_optimization_button'] = false;
1592 $optimization_data['run_sort_order'] = $optimization->get_run_sort_order();
1593
1594 // Check if the DOM is optimize-db to generate a list of tables.
1595 if ('optimize-db' == $optimization_data['dom_id']) {
1596 $table_list = $this->optimizer->get_table_information();
1597
1598 // Make sure that optimization_table_inno_db is set.
1599 if ($table_list['inno_db_tables'] > 0 && 0 === $table_list['is_optimizable'] && 0 === $table_list['non_inno_db_tables']) {
1600 $optimization_data['disable_optimization_button'] = true;
1601 $optimization_data['activated'] = '';
1602 }
1603 }
1604
1605 $optimization_data['id'] = $id;
1606 $optimizations_data[] = $optimization_data;
1607 }
1608
1609 // Backup checkbox name.
1610 $backup_checkbox_name = 'enable-auto-backup';
1611
1612 return array(
1613 'items' => $optimizations_data,
1614 'optimize_button_multiple_caption' => __('Optimize selected', 'wp-optimize'),
1615 'optimize_button_caption' => apply_filters('wpo_run_button_caption', __('Optimize all', 'wp-optimize')),
1616 'backup_checkbox_name' => $backup_checkbox_name,
1617 'backup_enabled' => 'true' == $this->options->get_option($backup_checkbox_name, 'false'),
1618 'backup_checkbox_label' => __('Take backup before optimize', 'wp-optimize'),
1619 );
1620 }
1621
1622 /**
1623 * Get wpo status data.
1624 *
1625 * @return array
1626 */
1627 private function get_status_data() {
1628 $status_data = $this->get_all_status_data();
1629
1630 $data = array(
1631 'statuses' => array(),
1632 'test' => $status_data,
1633 );
1634
1635 // Schedule optimization.
1636 $schedule_optimization_description = __('Scheduled optimization is currently disabled.', 'wp-optimize');
1637 $schedule_optimization_icon = 'error';
1638
1639 if (!empty($status_data['scheduled_optimizations_enabled'])) {
1640 if ('Never' === $status_data['last_optimized']) {
1641 $schedule_optimization_description = __('There was no scheduled optimization.', 'wp-optimize');
1642 $schedule_optimization_icon = 'warning';
1643 } else {
1644 $lastopt = $status_data['last_optimized'];
1645 if (is_numeric($status_data['last_optimized'])) {
1646 $lastopt = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $status_data['last_optimized'] + ( get_option('gmt_offset') * HOUR_IN_SECONDS ));
1647 }
1648 // translators: %s is the last schedule optimization run date.
1649 $schedule_optimization_description = sprintf(esc_html__('Last scheduled optimization was at %s', 'wp-optimize'), esc_html($lastopt));
1650 $schedule_optimization_icon = 'success';
1651 }
1652 }
1653
1654 $data['statuses'][] = array(
1655 'title' => __('Schedule Optimization', 'wp-optimize'),
1656 'description' => $schedule_optimization_description,
1657 'icon' => $schedule_optimization_icon,
1658 );
1659
1660 // Schedule cleaning.
1661 $data['statuses'][] = array(
1662 'title' => __('Schedule Cleaning', 'wp-optimize'),
1663 'description' => empty($status_data['scheduled_optimizations_enabled']) ? __('Scheduled cleaning is currently disabled.', 'wp-optimize') : __('Scheduled cleaning is enabled.', 'wp-optimize'),
1664 'icon' => empty($status_data['scheduled_optimizations_enabled']) ? 'warning' : 'success',
1665 );
1666
1667 // Data retention.
1668 $data['statuses'][] = array(
1669 'title' => __('Data Retention', 'wp-optimize'),
1670 'description' => empty($status_data['retention_enabled']) ? __('The system is not keeping recent data or any revisions.', 'wp-optimize') : __('Data retention enabled.', 'wp-optimize'),
1671 'icon' => empty($status_data['retention_enabled']) ? 'error' : 'success',
1672 );
1673
1674 return $data;
1675 }
1676
1677 /**
1678 * Get all status data.
1679 *
1680 * @return array
1681 */
1682 private function get_all_status_data() {
1683 $wp_optimize = WP_Optimize();
1684
1685 $retention_enabled = $this->options->get_option('retention-enabled', 'false') === 'true';
1686 $retention_period = $this->options->get_option('retention-period', '2');
1687 $admin_page_url = $this->options->admin_page_url();
1688
1689 $revisions_retention_enabled = $this->options->get_option('revisions-retention-enabled', 'false') === 'true';
1690 $revisions_retention_count = $this->options->get_option('revisions-retention-count', '2');
1691
1692 $last_optimized = $this->options->get_option('last-optimized', 'Never');
1693
1694 if (!empty($last_optimized) && is_numeric($last_optimized)) {
1695 $last_optimized = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $last_optimized + (get_option('gmt_offset') * HOUR_IN_SECONDS));
1696 }
1697
1698 $scheduled_optimizations_enabled = false;
1699
1700 if (WP_Optimize::is_premium()) {
1701 $wp_optimize_premium = WP_Optimize_Premium();
1702 $scheduled_optimizations = $wp_optimize_premium->get_scheduled_optimizations();
1703
1704 if (!empty($scheduled_optimizations)) {
1705 foreach ($scheduled_optimizations as $optimization) {
1706 if (isset($optimization['status']) && 1 === absint($optimization['status'])) {
1707 $scheduled_optimizations_enabled = true;
1708 break;
1709 }
1710 }
1711 }
1712 } else {
1713 $scheduled_optimizations_enabled = $this->options->get_option('schedule', 'false') == 'true';
1714 }
1715
1716 $total_cleaned = null;
1717 $total_cleanup_size = '';
1718 $corrupted_tables_count = null;
1719 $next_optimization_timestamp = 0;
1720
1721 if ($scheduled_optimizations_enabled) {
1722
1723 $next_optimization_timestamp = wp_next_scheduled('wpo_cron_event2');
1724 $filtered_next_optimization_timestamp = apply_filters('wpo_cron_next_event', $next_optimization_timestamp);
1725 $next_optimization_timestamp = is_int($filtered_next_optimization_timestamp) ? $filtered_next_optimization_timestamp : $next_optimization_timestamp;
1726
1727 if ($next_optimization_timestamp) {
1728
1729 $next_optimization_timestamp = $next_optimization_timestamp + 60 * 60 * get_option('gmt_offset');
1730
1731 $wp_optimize->cron_activate();
1732 }
1733
1734 $total_cleaned = $this->options->get_option('total-cleaned');
1735 $total_cleaned_num = floatval($total_cleaned);
1736
1737 if ($total_cleaned_num > 0) {
1738 $total_cleanup_size = $wp_optimize->format_size($total_cleaned);
1739 }
1740
1741 $corrupted_tables_count = $this->options->get_option('corrupted-tables-count', 0);
1742 }
1743
1744 return array(
1745 'last_optimized' => $last_optimized,
1746 'total_cleaned' => $total_cleaned,
1747 'total_cleanup_size' => $total_cleanup_size,
1748 'corrupted_tables_count' => $corrupted_tables_count,
1749 'admin_page_url' => $admin_page_url,
1750 'retention_enabled' => $retention_enabled,
1751 'retention_period' => $retention_period,
1752 'revisions_retention_enabled' => $revisions_retention_enabled,
1753 'revisions_retention_count' => $revisions_retention_count,
1754 'scheduled_optimizations_enabled' => $scheduled_optimizations_enabled,
1755 'next_optimization_timestamp' => $next_optimization_timestamp,
1756 );
1757 }
1758
1759 /**
1760 * Get wp-optimize tab top nav data.
1761 *
1762 * @return array
1763 */
1764 private function get_wp_optimize_top_nav_data() {
1765 return array(
1766 'title' => __('Performance Overview', 'wp-optimize'),
1767 'table_info' => __('Table Info', 'wp-optimize'),
1768 'performance_settings' => __('Performance Settings', 'wp-optimize'),
1769 );
1770 }
1771
1772 /**
1773 * Get wp-optimize tab top nav settings page data.
1774 *
1775 * @return array
1776 */
1777 private function get_wp_optimize_settings_top_nav_data() {
1778 return array(
1779 'title' => __('Performance Settings', 'wp-optimize'),
1780 'settings_saved_prompt' => __('Changes saved automatically', 'wp-optimize'),
1781 'settings_not_saved_prompt' => __('Changes not saved - please fill all the fields', 'wp-optimize'),
1782 );
1783 }
1784
1785 /**
1786 * Get if wp-optimize premium is installed.
1787 *
1788 * @return array
1789 */
1790 private function get_is_premium_data() {
1791 $is_premium = WP_Optimize::is_premium();
1792 $upgrade_to_premium_data = array();
1793
1794 if (false === $is_premium) {
1795 $upgrade_to_premium_data = array(
1796 'heading' => __('WP-Optimize premium', 'wp-optimize'),
1797 'checklist' => array(
1798 __('Optimize individual tables', 'wp-optimize'),
1799 __('Sophisticated scheduling', 'wp-optimize'),
1800 __('Lazy loading', 'wp-optimize'),
1801 __('Optimization preview', 'wp-optimize'),
1802 __('More caching options', 'wp-optimize'),
1803 __('Remove unwanted images', 'wp-optimize'),
1804 __('Multi language & currency support', 'wp-optimize'),
1805 ),
1806 'cta' => array(
1807 'text' => __('Upgrade Now', 'wp-optimize'),
1808 'url' => 'https://teamupdraft.com/wp-optimize/pricing/',
1809 ),
1810 );
1811 }
1812
1813 return array(
1814 'is_premium' => $is_premium,
1815 'upgrade_to_premium_data' => $upgrade_to_premium_data,
1816 );
1817 }
1818
1819 /**
1820 * WIP: Get system overview data.
1821 *
1822 * @return array
1823 */
1824 private function get_system_overview_data() {
1825 $wp_optimize = WP_Optimize();
1826 $status_data = $this->get_all_status_data();
1827
1828 // Data.
1829 $data = array(
1830 'data' => array(),
1831 );
1832
1833 // Lazy load.
1834 $lazy_load_settings = $this->options->get_option('lazyload', array(
1835 'images' => false,
1836 'iframes' => false,
1837 'skip_classes' => '',
1838 ));
1839
1840 $lazy_load_enabled = $lazy_load_settings['images'] || $lazy_load_settings['iframes'];
1841
1842 if (WP_Optimize::is_premium()) {
1843 $lazy_load_enabled = $lazy_load_enabled || $lazy_load_settings['backgrounds'];
1844 }
1845
1846 $data['data'][] = array(
1847 'title' => __('Lazy loading', 'wp-optimize'),
1848 'description' => $lazy_load_enabled ? __('Enabled', 'wp-optimize') : __('Disabled', 'wp-optimize'),
1849 'status' => $lazy_load_enabled ? 'success' : 'error',
1850 );
1851
1852 // Page caching.
1853 $cache = $wp_optimize->get_page_cache();
1854 $page_caching_enabled = $cache->is_enabled();
1855 $data['data'][] = array(
1856 'title' => __('Page caching', 'wp-optimize'),
1857 'description' => $page_caching_enabled ? __('Enabled', 'wp-optimize') : __('Disabled', 'wp-optimize'),
1858 'status' => $page_caching_enabled ? 'success' : 'error',
1859 );
1860
1861 // Schedule cleaning.
1862 $data['data'][] = array(
1863 'title' => __('Scheduled clean-up', 'wp-optimize'),
1864 'description' => empty($status_data['scheduled_optimizations_enabled']) ? __('Disabled', 'wp-optimize') : __('Enabled', 'wp-optimize'),
1865 'status' => empty($status_data['scheduled_optimizations_enabled']) ? 'error' : 'success',
1866 );
1867
1868 if (!empty($status_data['scheduled_optimizations_enabled'])) {
1869 $data['data'][] = array(
1870 'title' => __('Next scheduled date', 'wp-optimize'),
1871 'description' => esc_html(gmdate(get_option('date_format') . ' ' . get_option('time_format'), $status_data['next_optimization_timestamp'])),
1872 'status' => '',
1873 );
1874 }
1875
1876 return $data;
1877 }
1878
1879 /**
1880 * Get wp-optimize general settings data.
1881 *
1882 * @return array
1883 */
1884 private function get_wp_optimize_general_settings_data() {
1885 $retention_period = max((int) $this->options->get_option('retention-period', '2'), 1);
1886 $retention_enabled = 'true' === $this->options->get_option('retention-enabled');
1887
1888 $revisions_retention_count = (int) $this->options->get_option('revisions-retention-count', '2');
1889 $revisions_retention_enabled = 'true' === $this->options->get_option('revisions-retention-enabled');
1890
1891 $minify_or_cache_enabled = WP_Optimize()->get_page_cache()->is_enabled() || wp_optimize_minify_config()->get('enabled');
1892
1893 return array(
1894 'retention_period' => $retention_period,
1895 'retention_enabled' => $retention_enabled,
1896 'revisions_retention_count' => $revisions_retention_count,
1897 'revisions_retention_enabled' => $revisions_retention_enabled,
1898 'minify_or_cache_enabled' => $minify_or_cache_enabled,
1899 );
1900 }
1901
1902 /**
1903 * Get wp-optimize trackback settings data.
1904 *
1905 * @return array
1906 */
1907 private function get_wp_optimize_trackback_toggle_settings_data() {
1908 $wp_optimize = WP_Optimize();
1909
1910 $trackback_action_arr = $this->options->get_option('trackbacks_action', array());
1911
1912 $enabled = false;
1913 $last_action_timestamp = '';
1914 $empty = true;
1915
1916 if (!empty($trackback_action_arr)) {
1917 $empty = false;
1918 $last_action_timestamp = $wp_optimize->format_date_time($trackback_action_arr['timestamp']);
1919 if ($trackback_action_arr['action']) {
1920 $enabled = true;
1921 }
1922 }
1923
1924 return array(
1925 'enabled' => $enabled,
1926 'last_action_timestamp' => $last_action_timestamp,
1927 'empty' => $empty
1928 );
1929 }
1930
1931 /**
1932 * Get wp-optimize comments settings data.
1933 *
1934 * @return array
1935 */
1936 private function get_wp_optimize_comments_toggle_settings_data() {
1937 $wp_optimize = WP_Optimize();
1938
1939 $comments_action_arr = $this->options->get_option('comments_action', array());
1940
1941 $enabled = false;
1942 $last_action_timestamp = '';
1943 $empty = true;
1944
1945 if (!empty($comments_action_arr)) {
1946 $empty = false;
1947 $last_action_timestamp = $wp_optimize->format_date_time($comments_action_arr['timestamp']);
1948 if ($comments_action_arr['action']) {
1949 $enabled = true;
1950 }
1951 }
1952
1953 return array(
1954 'enabled' => $enabled,
1955 'last_action_timestamp' => $last_action_timestamp,
1956 'empty' => $empty
1957 );
1958 }
1959
1960 /**
1961 * Get wp-optimize logging settings.
1962 *
1963 * @return array
1964 */
1965 private function get_wp_optimize_logging_settings_data() {
1966 $wp_optimize = WP_Optimize();
1967
1968 $logger_classes_info = $wp_optimize->get_loggers_classes_info();
1969
1970 $logger_classes = array();
1971 $logger_classes_fields = array();
1972
1973 foreach ($logger_classes_info as $logger_class => $logger_class_data) {
1974 if (empty($logger_class_data['available'])) {
1975 continue;
1976 }
1977
1978 $logger_classes[] = array(
1979 'value' => $logger_class,
1980 'name' => $logger_class_data['description'],
1981 );
1982
1983 // For now we only have one option for all the fields, therefore taking only one.
1984 foreach ($logger_class_data['options'] as $name => $value) {
1985 $logger_class_field_data = array(
1986 'name' => $name,
1987 'validator' => '',
1988 'placeholder' => '',
1989 'controller_value' => $logger_class,
1990 );
1991
1992 if (is_array($value)) {
1993 $logger_class_field_data['validator'] = isset($value[1]) ? $value[1] : '';
1994 $logger_class_field_data['placeholder'] = isset($value[0]) ? $value[0] : '';
1995 } else {
1996 $logger_class_field_data['placeholder'] = $value;
1997 }
1998
1999 $logger_classes_fields[] = $logger_class_field_data;
2000 }
2001 }
2002
2003 $loggers_data = array(
2004 'loggers_classes_info' => $logger_classes_info,
2005 'logger_classes' => $logger_classes,
2006 'logger_classes_fields' => $logger_classes_fields,
2007 'existing_loggers' => array(),
2008 );
2009
2010 $loggers = $wp_optimize->wpo_loggers();
2011
2012 foreach ($loggers as $logger) {
2013 $logger_data = array(
2014 'id' => strtolower(get_class($logger)),
2015 'status' => ($logger->is_enabled() && $logger->is_available()) ? 'active' : 'inactive',
2016 'status_text' => ($logger->is_enabled() && $logger->is_available()) ? __('Active', 'wp-optimize') : __('Inactive', 'wp-optimize'),
2017 'existing_logger_classes' => array(),
2018 'existing_logger_classes_fields' => array(),
2019 'description' => $logger->get_description(),
2020 'options_text' => $logger->get_options_text(),
2021 'options_list' => array(),
2022 'is_enabled' => $logger->is_enabled(),
2023 'is_available' => $logger->is_available()
2024 );
2025
2026 $options_list = $logger->get_options_list();
2027 $options_values = $logger->get_options_values();
2028
2029 $options = array();
2030
2031 if (!empty($options_list)) {
2032 foreach ($options_list as $option_name => $placeholder) {
2033 // check if settings item defined as array.
2034 if (is_array($placeholder)) {
2035 $validate = $placeholder[1];
2036 $placeholder = $placeholder[0];
2037 } else {
2038 $validate = '';
2039 }
2040
2041 $data_validate_attr = ('' !== $validate ? 'data-validate="'.esc_attr($validate).'"' : '');
2042
2043 $options[$option_name] = array(
2044 'name' => $option_name,
2045 'placeholder' => $placeholder,
2046 'value' => $options_values[$option_name],
2047 'data_validate_attr' => $data_validate_attr,
2048 );
2049
2050 }
2051 $logger_data['options_list'] = $options;
2052 }
2053
2054 foreach ($loggers_data['logger_classes'] as $classes) {
2055 $logger_data['existing_logger_classes'][] = array(
2056 'value' => $classes['value'],
2057 'name' => $classes['name'],
2058 'selected' => $logger_data['id'] === $classes['value'],
2059 );
2060 }
2061
2062 foreach ($loggers_data['logger_classes_fields'] as $field) {
2063 // If the field has existing value fill it else add as it is.
2064 if (!empty($options[$field['name']])) {
2065 $field['value'] = $options[$field['name']]['value'];
2066 $field['selected'] = true;
2067 $logger_data['existing_logger_classes_fields'][] = $field;
2068 } else {
2069 $logger_data['existing_logger_classes_fields'][] = $field;
2070 }
2071 }
2072
2073 $loggers_data['existing_loggers'][] = $logger_data;
2074 }
2075
2076 return $loggers_data;
2077 }
2078
2079 /**
2080 * Get wp-optimize schedule cleanup settings data.
2081 *
2082 * @return array
2083 */
2084 private function get_wp_optimize_schedule_cleanup_settings_data() {
2085 $is_premium = WP_Optimize::is_premium();
2086
2087 $return_data = array(
2088 'is_premium' => $is_premium,
2089 'data' => array(),
2090 );
2091 $scheduled_optimizations_enabled = false;
2092 $wp_optimize = WP_Optimize();
2093
2094 if (!$is_premium) {
2095 $enabled = 'true' === $this->options->get_option('schedule');
2096
2097 $schedule_type_saved_id = $this->options->get_option('schedule-type', 'wpo_weekly');
2098
2099 // Backwards compatibility:
2100 if ('wpo_otherweekly' == $schedule_type_saved_id) $schedule_type_saved_id = 'wpo_fortnightly';
2101
2102 $schedule_types = WP_Optimize::get_schedule_types();
2103
2104 $schedule_options = array_map(
2105 function ($value, $key) use ($schedule_type_saved_id) {
2106 return array(
2107 'id' => $key,
2108 'label' => $value,
2109 'selected' => ($key === $schedule_type_saved_id)
2110 );
2111 },
2112 $schedule_types,
2113 array_keys($schedule_types)
2114 );
2115
2116 $wpo_auto_options = $this->options->get_option('auto');
2117
2118 $optimizations = $this->optimizer->sort_optimizations($this->optimizer->get_optimizations());
2119
2120 $optimizations_data = array();
2121
2122 $does_server_allow_table_optimization = WP_Optimize()->get_server_compatibility_instance()->does_server_allow_table_optimization();
2123
2124 foreach ($optimizations as $id => $optimization) {
2125 if (empty($optimization->available_for_auto)) continue;
2126
2127 if ('optimizetables' == $id && false === $does_server_allow_table_optimization) continue;
2128
2129 $auto_id = $optimization->get_auto_id();
2130
2131 $auto_dom_id = 'wp-optimize-auto-'.$auto_id;
2132
2133 $setting_activated = (empty($wpo_auto_options[$auto_id]) || 'false' == $wpo_auto_options[$auto_id]) ? false : true;
2134
2135 $optimizations_data[] = array(
2136 'id' => $auto_id,
2137 'dom_id' => $auto_dom_id,
2138 'activated' => $setting_activated,
2139 'label' => $optimization->get_auto_option_description(),
2140 );
2141 }
2142
2143 $next_optimization_timestamp = 0;
2144
2145 $scheduled_optimizations_enabled = $this->options->get_option('schedule', 'false') == 'true';
2146
2147 if ($scheduled_optimizations_enabled) {
2148 $next_optimization_timestamp = apply_filters('wpo_cron_next_event', wp_next_scheduled('wpo_cron_event2'));
2149
2150 if ($next_optimization_timestamp) {
2151
2152 $next_optimization_timestamp = $next_optimization_timestamp + 60 * 60 * get_option('gmt_offset');
2153 }
2154 }
2155
2156 $return_data['data'] = array(
2157 'enabled' => $enabled,
2158 'schedule_options' => $schedule_options,
2159 'schedule_type_saved_id' => $schedule_type_saved_id,
2160 'optimizations' => $optimizations_data,
2161 'next_optimization' => $next_optimization_timestamp ? esc_html(gmdate(get_option('date_format') . ' ' . get_option('time_format'), $next_optimization_timestamp)) : '',
2162 'premium_version_link' => $wp_optimize->premium_version_link,
2163 'enable_schedule' => $this->options->get_option('schedule'),
2164 );
2165 } else {
2166 $wp_optimize_premium = WP_Optimize_Premium();
2167 $auto_options = $wp_optimize_premium->get_scheduled_optimizations();
2168 $auto_optimizations = $wp_optimize_premium->get_auto_optimizations();
2169
2170 $next_optimization_timestamp = 0;
2171
2172 if (!empty($auto_options)) {
2173 foreach ($auto_options as $optimization) {
2174 if (isset($optimization['status']) && 1 == $optimization['status']) {
2175 $scheduled_optimizations_enabled = true;
2176 break;
2177 }
2178 }
2179 }
2180
2181 $all_provided_optimizations = array_values($auto_optimizations);
2182 $all_schedule_types = WP_Optimize::get_schedule_types();
2183 $week_days = WP_Optimize_Premium::get_week_days();
2184 $days = WP_Optimize_Premium::get_days();
2185 $weeks = array('1st' => __('1st', 'wp-optimize'), '2nd' => __('2nd', 'wp-optimize'));
2186
2187 $optimizations = array();
2188
2189 foreach ($auto_options as $index => $event) {
2190 $optimization = array(
2191 'index' => $index,
2192 );
2193 if (!isset($event['optimization'])) {
2194 $event['optimization'] = array();
2195 }
2196 foreach ($event as $key => $value) {
2197 switch ($key) {
2198 case 'optimization':
2199 $optimization['optimization'] = array();
2200 foreach ($all_provided_optimizations as $this_optimization) {
2201 if (in_array($this_optimization['id'], $value)) {
2202 $this_optimization['selected'] = true;
2203 }
2204 $optimization['optimization'][] = $this_optimization;
2205 }
2206 break;
2207 case 'schedule_type':
2208 $optimization['schedule_types'] = array();
2209 foreach ($all_schedule_types as $key => $this_schedule_value) {
2210 $this_schedule_type = array();
2211 $this_schedule_type['label'] = $this_schedule_value;
2212 $this_schedule_type['selected'] = $key === $value;
2213 $this_schedule_type['value'] = $key;
2214 $optimization['schedule_types'][] = $this_schedule_type;
2215 }
2216 break;
2217 case 'date':
2218 $optimization['date'] = $value;
2219 break;
2220 case 'time':
2221 $optimization['time'] = $value;
2222 break;
2223 case 'week':
2224 $optimization['weeks'] = array();
2225 foreach ($weeks as $key => $this_week_value) {
2226 $this_week = array();
2227 $this_week['label'] = $this_week_value;
2228 $this_week['selected'] = $key === $value;
2229 $this_week['value'] = $key;
2230 $optimization['weeks'][] = $this_week;
2231 }
2232 break;
2233 case 'day':
2234 $optimization['days'] = array();
2235 foreach ($week_days as $key => $this_week_day_value) {
2236 $this_week_day = array();
2237 $this_week_day['label'] = $this_week_day_value;
2238 $this_week_day['selected'] = $key === $value;
2239 $this_week_day['value'] = $key;
2240 $optimization['days'][] = $this_week_day;
2241 }
2242 break;
2243 case 'day_number':
2244 $optimization['day_numbers'] = array();
2245 foreach ($days as $key => $this_day_value) {
2246 $this_day = array();
2247 $this_day['label'] = $this_day_value;
2248 $this_day['selected'] = absint($key) === absint($value);
2249 $this_day['value'] = $key;
2250 $optimization['day_numbers'][] = $this_day;
2251 }
2252 break;
2253 case 'status':
2254 $optimization['status'] = '1' === $value;
2255 break;
2256 }
2257 }
2258 $optimizations[] = $optimization;
2259 }
2260
2261 if ($scheduled_optimizations_enabled) {
2262 $next_optimization_timestamp = apply_filters('wpo_cron_next_event', wp_next_scheduled('wpo_cron_event2'));
2263
2264 if ($next_optimization_timestamp) {
2265 $next_optimization_timestamp = $next_optimization_timestamp + 60 * 60 * get_option('gmt_offset');
2266 }
2267 }
2268
2269 $return_data['data'] = array(
2270 'optimizations' => $optimizations,
2271 'provided_optimizations' => $all_provided_optimizations,
2272 'provided_schedule_types' => $all_schedule_types,
2273 'today_date' => gmdate("Y-m-d"),
2274 'weeks' => $weeks,
2275 'week_days' => $week_days,
2276 'days' => $days,
2277 'next_optimization' => $next_optimization_timestamp ? esc_html(gmdate(get_option('date_format') . ' ' . get_option('time_format'), $next_optimization_timestamp)) : '',
2278 'is_auto_innodb' => $this->options->get_option('auto-innodb'),
2279 'scheduled_optimizations' => $auto_options,
2280 'auto_optimizations' => $auto_optimizations,
2281 '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)
2282 );
2283 }
2284
2285 // Add the translations.
2286 $return_data['data']['translations'] = array(
2287 'scheduled_optimization' => __('Scheduled Optimization', 'wp-optimize'),
2288 'next_schedule_run' => __('Next scheduled run', 'wp-optimize'),
2289 'no_scheduled_optimization' => __('No scheduled optimization', 'wp-optimize'),
2290 'add_optimization_tasks' => __('Add optimization tasks', 'wp-optimize'),
2291 'select_all' => __('Select all', 'wp-optimize'),
2292 'unselect_all' => __('Un-Select All', 'wp-optimize'),
2293 'select_schedule' => __('Select schedule', 'wp-optimize'),
2294 'run_an_optimization_every' => __('Run an optimization every', 'wp-optimize'),
2295 'add_optimization' => __('Add optimization', 'wp-optimize'),
2296 );
2297
2298 return $return_data;
2299 }
2300
2301 /**
2302 * Get wp-optimize status report data.
2303 *
2304 * @return array
2305 */
2306 private function get_wp_optimize_status_report_data() {
2307 $system_status = WP_Optimize_System_Status_Report::get_instance();
2308 $report_data = $system_status->generate_report();
2309 $replaceable_md_tags = $system_status->get_replaceable_md_tags();
2310
2311 return array('report_data' => $report_data, 'replaceable_md_tags' => $replaceable_md_tags);
2312 }
2313
2314 /**
2315 * Get data for the UDC reports.
2316 *
2317 * @return array
2318 */
2319 public function get_report_data() {
2320 $wp_optimize = WP_Optimize();
2321 $schedule_types = WP_Optimize::get_schedule_types();
2322 $scheduled_optimizations_enabled = $this->options->get_option('schedule', 'false') == 'true';
2323 $schedule_frequency = '';
2324 $unused_posts_images = 0;
2325 $optimized_images_percentage = 0;
2326
2327 if (WP_Optimize::is_premium()) {
2328 $wp_optimize_premium = WP_Optimize_Premium();
2329 $scheduled_optimizations = $wp_optimize_premium->get_scheduled_optimizations();
2330
2331 if (!empty($scheduled_optimizations)) {
2332 foreach ($scheduled_optimizations as $optimization) {
2333 if (isset($optimization['status']) && 1 === absint($optimization['status'])) {
2334 $scheduled_optimizations_enabled = true;
2335 $schedule_frequency = $schedule_types[$optimization['schedule_type']] ?? '';
2336 break;
2337 }
2338 }
2339 }
2340
2341 // Force calculate unused images.
2342 WP_Optimization_images::instance()->get_optimization_info();
2343 $unused_posts_images = WP_Optimization_images::instance()->get_unused_images_count();
2344 $optimized_images_percentage = WP_Optimize_Bulk_Smush::get_instance()->get_optimized_images_percentage();
2345
2346 } elseif ($scheduled_optimizations_enabled) {
2347 $schedule_type_saved_id = $this->options->get_option('schedule-type', 'wpo_weekly');
2348
2349 // Backwards compatibility:
2350 if ('wpo_otherweekly' == $schedule_type_saved_id) $schedule_type_saved_id = 'wpo_fortnightly';
2351
2352 $schedule_frequency = $schedule_types[$schedule_type_saved_id] ?? '';
2353 }
2354
2355 $total_cleaned = $this->options->get_option('total-cleaned-previous-month');
2356 $total_cleanup_size = $wp_optimize->format_size($total_cleaned);
2357
2358 $cache = $wp_optimize->get_page_cache();
2359 $page_caching_enabled = $cache->is_enabled();
2360
2361 $minification_enabled = wp_optimize_minify_config()->get('enabled') ?? false;
2362
2363 return array(
2364 'report_data' => array(
2365 'is_premium' => WP_Optimize::is_premium(),
2366 'scheduled_optimizations_enabled' => $scheduled_optimizations_enabled,
2367 'schedule_frequency' => $schedule_frequency,
2368 'total_cleaned' => $total_cleaned,
2369 'total_cleanup_size' => $total_cleanup_size,
2370 'unused_posts_images' => $unused_posts_images,
2371 'page_caching_enabled' => $page_caching_enabled,
2372 'minification_enabled' => $minification_enabled,
2373 'optimized_images_percentage' => $optimized_images_percentage . '%',
2374 ),
2375 'variables' => array(
2376 /* translators: %s is the cleaned up memory size. */
2377 'performance_highlights' => sprintf(__('%s saved', 'wp-optimize'), $total_cleanup_size),
2378 ),
2379 );
2380 }
2381 }
2382