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

1,085 lines 33.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 if (!defined('WPO_PLUGIN_MAIN_PATH')) 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 private $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 = (boolean) $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 return WP_Optimize()->include_template('database/status-box-contents.php', true, array('optimize_db' => false));
41 }
42
43 /**
44 * Get the database tabs information.
45 *
46 * @return string auto cleanup content.
47 */
48 public function get_settings_auto_cleanup_contents() {
49 return WP_Optimize()->include_template('database/settings-auto-cleanup.php', true, array('optimize_db' => false, 'show_innodb_option' => WP_Optimize()->template_should_include_data() && $this->optimizer->show_innodb_force_optimize()));
50 }
51
52 /**
53 * Get the settings tab information.
54 *
55 * @return string logging settings content.
56 */
57 public function get_logging_settings_contents() {
58 return WP_Optimize()->include_template('settings/settings-logging.php', true, array('optimize_db' => false));
59 }
60
61 /**
62 * Get the database tabs information
63 *
64 * @return string database table optimization rendered content
65 */
66 public function get_optimizations_table() {
67 return WP_Optimize()->include_template('database/optimizations-table.php', true, array('does_server_allows_table_optimization' => WP_Optimize()->does_server_allows_table_optimization()));
68 }
69
70 /**
71 * [For UpdraftCentral] Returns the file content containing the list of unused images
72 *
73 * @return array|void
74 */
75 public function download_csv() {
76 if (!current_user_can(WP_Optimize()->capability_required())) {
77 return $this->request_error('insufficient_privilege');
78 }
79
80 WP_Optimize()->get_optimizer()->get_optimization('images')->output_csv();
81 }
82
83 /**
84 * [For UpdraftCentral] Retrieves the tabs and their corresponding contents, assets basing
85 * from the current page or section requested (e.g. database, images, cache, minify or settings)
86 *
87 * @param array $params Parameters needed for the requested action
88 * @return array
89 */
90 public function get_section($params) {
91 if (!current_user_can(WP_Optimize()->capability_required())) {
92 return $this->request_error('insufficient_privilege');
93 }
94
95 $section_id = $params['section'];
96 $section = $this->get_section_to_tab_name($section_id);
97 $tabs = WP_Optimize()->get_admin_instance()->get_tabs($section);
98
99 // We remove the UpdraftCentral management tab when managing WP-Optimize
100 // plugin from the UpdraftCentral dashboard if it exists.
101 if (isset($tabs['updraftcentral'])) unset($tabs['updraftcentral']);
102
103 $this->load_action_hooks_for_content($section_id);
104 return array(
105 'tabs' => $tabs,
106 'tabs_content' => $this->get_tab_contents($tabs, $section),
107 'assets' => $this->get_localized_variables(),
108 'wposmush' => $this->get_wposmush(),
109 'is_premium' => WP_Optimize::is_premium(),
110 'modal_template' => WP_Optimize()->include_template('modal.php', true),
111 );
112 }
113
114 /**
115 * [For UpdraftCentral] Retrieves the list of items to optimize from the current database
116 *
117 * @return array
118 */
119 public function get_database_tabs_info() {
120 if (!current_user_can(WP_Optimize()->capability_required())) {
121 return $this->request_error('insufficient_privilege');
122 }
123
124 return $this->get_database_tabs();
125 }
126
127 /**
128 * [For UpdraftCentral] Processes specific Smush commands from ajax requests
129 *
130 * @param array $params Parameters needed for the requested action
131 * @return array
132 */
133 public function updraft_smush_ajax($params) {
134 if (!current_user_can(WP_Optimize()->capability_required())) {
135 return $this->request_error('insufficient_privilege');
136 }
137
138 $subaction = $params['subaction'];
139 $data = $params['data'];
140
141 $allowed_commands = Updraft_Smush_Manager_Commands::get_allowed_ajax_commands();
142 if (in_array($subaction, $allowed_commands)) {
143 if (in_array($subaction, array('get_smush_logs', 'process_bulk_smush'))) {
144 switch ($subaction) {
145 case 'get_smush_logs':
146 $results = $this->get_smush_logs();
147 break;
148 case 'process_bulk_smush':
149 $results = $this->process_bulk_smush($data);
150 break;
151 default:
152 break;
153 }
154 } else {
155 if (!empty($data)) {
156 $results = call_user_func(array(Updraft_Smush_Manager()->commands, $subaction), $data);
157 } else {
158 $results = call_user_func(array(Updraft_Smush_Manager()->commands, $subaction));
159 }
160 }
161
162 if (is_wp_error($results)) {
163 return $this->request_error($results->get_error_code(), null, array(
164 'status' => true,
165 'error_message' => $results->get_error_message(),
166 'error_data' => $results->get_error_data(),
167 ));
168 } else {
169 return $results;
170 }
171 } else {
172 return $this->request_error('command_not_found');
173 }
174 }
175
176 /**
177 * [For UpdraftCentral] Processes general WP-Optimize commands from ajax requests
178 *
179 * @param array $params Parameters needed for the requested action
180 * @return array
181 */
182 public function handle_ajax_requests($params) {
183 if (!current_user_can(WP_Optimize()->capability_required())) {
184 return $this->request_error('insufficient_privilege');
185 }
186
187 $subaction = $params['subaction'];
188 $data = $params['data'];
189
190 $response = array();
191 if (is_multisite() && !current_user_can('manage_network_options')) {
192 $allowed_multisite_commands = apply_filters('wpo_multisite_allowed_commands', array('check_server_status', 'compress_single_image', 'restore_single_image'));
193
194 if (!in_array($subaction, $allowed_multisite_commands)) {
195 return $this->request_error('network_admin_only');
196 }
197 }
198
199 $dismiss_actions = array(
200 'dismiss_dash_notice_until',
201 'dismiss_season',
202 'dismiss_page_notice_until',
203 'dismiss_notice',
204 'dismiss_review_notice',
205 );
206
207 if (in_array($subaction, $dismiss_actions)) {
208 $options = WP_Optimize()->get_options();
209
210 // Some commands that are available via AJAX only.
211 if (in_array($subaction, array('dismiss_dash_notice_until', 'dismiss_season'))) {
212 $options->update_option($subaction, (time() + 366 * 86400));
213 } elseif (in_array($subaction, array('dismiss_page_notice_until', 'dismiss_notice'))) {
214 $options->update_option($subaction, (time() + 84 * 86400));
215 } elseif ('dismiss_review_notice' == $subaction) {
216 if (empty($data['dismiss_forever'])) {
217 $options->update_option($subaction, time() + 84 * 86400);
218 } else {
219 $options->update_option($subaction, 100 * (365.25 * 86400));
220 }
221 }
222
223 } else {
224 $commands = new WP_Optimize_Commands();
225
226 $minify_commands = new WP_Optimize_Minify_Commands();
227 if (!is_callable(array($commands, $subaction)) && is_callable(array($minify_commands, $subaction))) {
228 $commands = $minify_commands;
229 }
230
231 if (WP_Optimize::is_premium()) {
232 $cache_commands = new WP_Optimize_Cache_Commands_Premium();
233 } else {
234 $cache_commands = new WP_Optimize_Cache_Commands();
235 }
236
237 if (!is_callable(array($commands, $subaction)) && is_callable(array($cache_commands, $subaction))) {
238 $commands = $cache_commands;
239 }
240
241 // Check if command is valid
242 if (!is_callable(array($commands, $subaction))) {
243 return $this->request_error('command_not_found');
244 } else {
245 $response = call_user_func(array($commands, $subaction), $data);
246 if (is_wp_error($response)) {
247 return $this->request_error($response->get_error_code(), null, array(
248 'error_message' => $response->get_error_message(),
249 'error_data' => $response->get_error_data(),
250 ));
251 } elseif (empty($response)) {
252 $response = array(
253 'result' => null
254 );
255 } else {
256 if (isset($response['status_box_contents'])) {
257 $response['status_box_contents'] = str_replace(array("\n", "\t"), '', $response['status_box_contents']);
258 }
259 }
260 }
261 }
262
263 return $response;
264 }
265
266 /**
267 * [For UpdraftCentral] Retrieves a list of posts to purge as options to be displayed under
268 * cache - advanced settings
269 *
270 * @param array $params Parameters needed for the requested action
271 * @return array
272 */
273 public function get_posts_list($params) {
274 if (!current_user_can(WP_Optimize()->capability_required())) {
275 return $this->request_error('insufficient_privilege');
276 }
277
278 $response = array();
279 if (WP_Optimize::is_premium()) {
280 $commands = new WP_Optimize_Cache_Commands_Premium();
281 if (is_callable(array($commands, 'get_posts_list'))) {
282 $response = $commands->get_posts_list($params);
283 }
284 }
285
286 return $response;
287 }
288
289 /**
290 * [For UpdraftCentral] loads the settings page
291 *
292 * @return void
293 */
294 public function output_dashboard_settings_tab() {
295 $wpo_admin = WP_Optimize()->get_admin_instance();
296
297 if (WP_Optimize()->can_manage_options()) {
298 WP_Optimize()->include_template('settings/settings.php');
299 } else {
300 $wpo_admin->prevent_manage_options_info();
301 }
302 }
303
304 /**
305 * [For UpdraftCentral] Retrieves Smush JS variables
306 *
307 * @return array
308 */
309 private function get_wposmush() {
310 if (!class_exists('Updraft_Smush_Manager')) return array();
311
312 $js_variables = Updraft_Smush_Manager()->smush_js_translations();
313 $js_variables['ajaxurl'] = admin_url('admin-ajax.php');
314 $js_variables['features'] = Updraft_Smush_Manager()->get_features();
315
316 return $js_variables;
317 }
318
319 /**
320 * [For UpdraftCentral] Execute smush process in bulk
321 *
322 * @param array $data Parameters to be pass as argument for the requested action
323 * @return string
324 */
325 private function process_bulk_smush($data) {
326 ob_start();
327 Updraft_Smush_Manager()->commands->process_bulk_smush($data);
328 $content = ob_get_contents();
329 ob_end_clean();
330
331 return $content;
332 }
333
334 /**
335 * [For UpdraftCentral] Retrieves the content of a Smush log file
336 *
337 * @return string|WP_Error
338 */
339 private function get_smush_logs() {
340 $logfile = Updraft_Smush_Manager()->get_logfile_path();
341 if (!file_exists($logfile)) {
342 Updraft_Smush_Manager()->write_log_header();
343 }
344
345 if (is_file($logfile)) {
346 return file_get_contents($logfile);
347 } else {
348 return $this->request_error('log_file_not_exist');
349 }
350 }
351
352 /**
353 * [For UpdraftCentral] Loads the WP-Optimize hooks needed to pull the tab contents for
354 * the requested page/section
355 *
356 * @param array $section_id The id of the page or section where the content is to be pulled from
357 * @return void
358 */
359 private function load_action_hooks_for_content($section_id) {
360 $wpo = WP_Optimize();
361 $wpo_admin = $wpo->get_admin_instance();
362
363 // Database
364 if ('database' == $section_id) {
365 add_action('wp_optimize_admin_page_WP-Optimize_optimize', array($wpo_admin, 'output_database_optimize_tab'), 20);
366 add_action('wp_optimize_admin_page_WP-Optimize_tables', array($wpo_admin, 'output_database_tables_tab'), 20);
367 add_action('wp_optimize_admin_page_WP-Optimize_settings', array($wpo_admin, 'output_database_settings_tab'), 20);
368 }
369
370 // Images
371 if ('images' == $section_id) {
372 add_action('wp_optimize_admin_page_wpo_images_smush', array($wpo, 'admin_page_wpo_images_smush'));
373
374 if (!WP_Optimize::is_premium()) {
375 add_action('wp_optimize_admin_page_wpo_images_unused', array($wpo_admin, 'admin_page_wpo_images_unused'));
376 add_action('wp_optimize_admin_page_wpo_images_lazyload', array($wpo_admin, 'admin_page_wpo_images_lazyload'));
377 }
378 }
379
380 // Cache
381 if ('cache' == $section_id) {
382 add_action('wp_optimize_admin_page_wpo_cache_cache', array($wpo_admin, 'output_page_cache_tab'), 20);
383 add_action('wp_optimize_admin_page_wpo_cache_preload', array($wpo_admin, 'output_page_cache_preload_tab'), 20);
384 add_action('wp_optimize_admin_page_wpo_cache_advanced', array($wpo_admin, 'output_page_cache_advanced_tab'), 20);
385 add_action('wp_optimize_admin_page_wpo_cache_gzip', array($wpo_admin, 'output_cache_gzip_tab'), 20);
386 add_action('wp_optimize_admin_page_wpo_cache_settings', array($wpo_admin, 'output_cache_settings_tab'), 20);
387 }
388
389 // Minify
390 if ('minify' == $section_id) {
391 if (class_exists('WP_Optimize_Minify_Admin')) {
392 do_action('wp_optimize_register_admin_content');
393 }
394 }
395
396 // Settings
397 if ('settings' == $section_id) {
398 add_action('wp_optimize_admin_page_wpo_settings_settings', array($this, 'output_dashboard_settings_tab'), 20);
399 }
400 }
401
402 /**
403 * [For UpdraftCentral] Execute the hooks needed to pull the content of the tabs under the requested page/section
404 *
405 * @param array $tabs The list of tabs available under the current page/section
406 * @param array $section_id The id of the page or section
407 * @return string
408 */
409 private function get_tab_contents($tabs, $section_id) {
410 $contents = array();
411
412 foreach ($tabs as $tab_id => $tab_description) {
413 ob_start();
414 // output wrap div for tab with id #wp-optimize-nav-tab-contents-'.$section.'-'.$tab_id
415 echo '<div class="wp-optimize-nav-tab-contents" id="wp-optimize-nav-tab-'.$section_id.'-'.$tab_id.'-contents">';
416
417 echo '<div class="postbox wpo-tab-postbox">';
418
419 // call action for generate tab content.
420 do_action('wp_optimize_admin_page_'.$section_id.'_'.$tab_id);
421
422 // closes postbox.
423 echo '</div><!-- END .postbox -->';
424 // closes tab wrapper.
425 echo '</div><!-- END .wp-optimize-nav-tab-contents -->';
426 $tab_content = ob_get_contents();
427 ob_end_clean();
428
429 $contents[$tab_id] = $tab_content;
430 }
431
432 return $contents;
433 }
434
435 /**
436 * [For UpdraftCentral] Replaces the names/id used in UpdraftCentral with the actual name used in WP-Optimize
437 *
438 * @param array $section_id The id of the page or section
439 * @return string
440 */
441 private function get_section_to_tab_name($section_id) {
442 $tab = '';
443 switch ($section_id) {
444 case 'database':
445 $tab = 'WP-Optimize';
446 break;
447 default:
448 $tab = 'wpo_'.$section_id;
449 break;
450 }
451 return $tab;
452 }
453
454 /**
455 * [For UpdraftCentral] Retrieves the localized scripts/variables (e.g. translations, etc.) used by WP-Optimize
456 *
457 * @return array
458 */
459 private function get_localized_variables() {
460 $wpo = WP_Optimize();
461 $js_variables = $wpo->wpo_js_translations();
462 $js_variables['loggers_classes_info'] = $wpo->get_loggers_classes_info();
463 $js_variables['ajaxurl'] = admin_url('admin-ajax.php');
464
465 $localized_variables = array(
466 'wpoptimize' => $js_variables,
467 'wp_optimize_send_command_data' => array('nonce' => wp_create_nonce('wp-optimize-ajax-nonce')),
468 'wpo_heartbeat_ajax' => array(
469 'ajaxurl' => admin_url('admin-ajax.php'),
470 'nonce' => wp_create_nonce('heartbeat-nonce'),
471 'interval' => WPO_Ajax::HEARTBEAT_INTERVAL
472 ),
473 );
474
475 if (WP_Optimize::is_premium()) {
476 $localized_variables = array_merge($localized_variables, array(
477 'wp_optimize_minify_premium' => array(
478 'home_url' => home_url()
479 )
480 ));
481 }
482
483 return array(
484 'localize' => $localized_variables,
485 );
486 }
487
488 /**
489 * [For UpdraftCentral] Returns a WP_Error response for the current request
490 *
491 * @param string $code The error code
492 * @param string $message_key The key to use to query any translatable message if applicable
493 * @param array $additional_data Any additional data to return
494 * @return WP_Error
495 */
496 private function request_error($code, $message_key = null, $additional_data = array()) {
497 global $updraftcentral_host_plugin;
498
499 $error_message = $updraftcentral_host_plugin->retrieve_show_message($code);
500 if (!is_null($message_key) && $code !== $message_key) {
501 $error_message = $updraftcentral_host_plugin->retrieve_show_message($message_key);
502 }
503
504 $data = array(
505 'result' => false,
506 'error_code' => $code,
507 'error_message' => $error_message,
508 'error' => true,
509 'code' => $code,
510 'message' => $error_message,
511 );
512
513 if (!empty($additional_data)) {
514 $data = array_merge($data, $additional_data);
515 }
516
517 return new WP_Error($code, $error_message, $data);
518 }
519
520 /**
521 * Pulls and return the "WP Optimize" template contents. Primarily used for UpdraftCentral
522 * content display through ajax request.
523 *
524 * @return array An array containing the WPO translations and the "WP Optimize" tab's rendered contents
525 */
526 public function get_wp_optimize_contents() {
527 $content = WP_Optimize()->include_template('database/optimize-table.php', true, array('optimize_db' => false, 'load_data' => WP_Optimize()->template_should_include_data(), 'does_server_allows_table_optimization' => WP_Optimize()->does_server_allows_table_optimization()));
528 if (WP_Optimize()->is_updraft_central_request()) {
529 $content .= $this->get_status_box_contents();
530 }
531
532 return array(
533 'content' => $content,
534 'translations' => $this->get_js_translation()
535 );
536 }
537
538 /**
539 * Pulls and return the "Table Information" template contents. Primarily used for UpdraftCentral
540 * content display through ajax request.
541 *
542 * @return array An array containing the WPO translations and the "Table Information" tab's rendered contents
543 */
544 public function get_table_information_contents() {
545 $content = WP_Optimize()->include_template('database/tables.php', true, array('optimize_db' => false, 'load_data' => WP_Optimize()->template_should_include_data()));
546
547 return array(
548 'content' => $content,
549 'translations' => $this->get_js_translation()
550 );
551 }
552
553 /**
554 * Pulls and return the "Settings" template contents. Primarily used for UpdraftCentral
555 * content display through ajax request.
556 *
557 * @return array An array containing the WPO translations and the "Settings" tab's rendered contents
558 */
559 public function get_settings_contents() {
560 $admin_settings = '<form action="#" method="post" enctype="multipart/form-data" name="settings_form" id="settings_form">';
561 $admin_settings .= WP_Optimize()->include_template('database/settings-general.php', true, array('optimize_db' => false));
562 $admin_settings .= WP_Optimize()->include_template('database/settings-auto-cleanup.php', true, array('optimize_db' => false, 'show_innodb_option' => WP_Optimize()->template_should_include_data() && $this->optimizer->show_innodb_force_optimize()));
563 $admin_settings .= WP_Optimize()->include_template('settings/settings-logging.php', true, array('optimize_db' => false));
564 $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') .'" />';
565 $admin_settings .= '</form>';
566 $admin_settings .= WP_Optimize()->include_template('settings/settings-trackback-and-comments.php', true, array('optimize_db' => false));
567 $content = $admin_settings;
568
569 return array(
570 'content' => $content,
571 'translations' => $this->get_js_translation()
572 );
573 }
574
575 /**
576 * Returns array of translations used by the WPO plugin. Primarily used for UpdraftCentral
577 * consumption.
578 *
579 * @return array The WPO translations
580 */
581 public function get_js_translation() {
582 $translations = WP_Optimize()->wpo_js_translations();
583
584 // Make sure that we include the loggers classes info whenever applicable before
585 // returning the translations to UpdraftCentral.
586 if (is_callable(array(WP_Optimize(), 'get_loggers_classes_info'))) {
587 $translations['loggers_classes_info'] = WP_Optimize()->get_loggers_classes_info();
588 }
589
590 return $translations;
591 }
592
593 /**
594 * Save settings command.
595 *
596 * @param string $data
597 * @return array
598 */
599 public function save_settings($data) {
600
601 parse_str(stripslashes($data), $posted_settings);
602
603 $saved_settings = $this->options->save_settings($posted_settings);
604 // We now have $posted_settings as an array.
605 return array(
606 'save_results' => $saved_settings,
607 'status_box_contents' => $this->get_status_box_contents(),
608 'optimizations_table' => $this->get_optimizations_table(),
609 'settings_auto_cleanup_contents' => $this->get_settings_auto_cleanup_contents(),
610 'logging_settings_contents' => $this->get_logging_settings_contents(),
611 );
612 }
613
614 /**
615 * Wipe settings command.
616 *
617 * @return bool|false|int
618 */
619 public function wipe_settings() {
620 return $this->options->wipe_settings();
621 }
622
623 /**
624 * Save lazy load settings.
625 *
626 * @param string $data
627 * @return array
628 */
629 public function save_lazy_load_settings($data) {
630 parse_str(stripslashes($data), $posted_settings);
631
632 return array(
633 'save_result' => $this->options->save_lazy_load_settings($posted_settings)
634 );
635 }
636
637 /**
638 * This sends the selected tick value over to the save function
639 * within class-wp-optimize-options.php
640 *
641 * @param array $data An array of data that includes true or false for click option.
642 * @return array
643 */
644 public function save_auto_backup_option($data) {
645 return array('save_auto_backup_option' => $this->options->save_auto_backup_option($data));
646 }
647
648 /**
649 * Save option which sites to optimize in multisite mode.
650 *
651 * @param array $data Array of settings.
652 * @return bool
653 */
654 public function save_site_settings($data) {
655 return $this->options->save_wpo_sites_option($data['wpo-sites']);
656 }
657
658 /**
659 * Perform the requested optimization
660 *
661 * @param array $params Should have keys 'optimization_id' and 'data'.
662 * @return array
663 */
664 public function do_optimization($params) {
665
666 if (!isset($params['optimization_id'])) {
667 $results = array(
668 'result' => false,
669 'messages' => array(),
670 'errors' => array(
671 __('No optimization was indicated.', 'wp-optimize')
672 )
673 );
674 } else {
675 $optimization_id = $params['optimization_id'];
676 $data = isset($params['data']) ? $params['data'] : array();
677 $include_ui_elements = isset($data['include_ui_elements']) ? $data['include_ui_elements'] : false;
678
679 $optimization = $this->optimizer->get_optimization($optimization_id, $data);
680
681 $result = is_a($optimization, 'WP_Optimization') ? $optimization->do_optimization() : null;
682
683 $results = array(
684 'result' => $result,
685 'messages' => array(),
686 'errors' => array(),
687 );
688
689 if ($include_ui_elements) {
690 $results['status_box_contents'] = $this->get_status_box_contents();
691 }
692
693 if (is_wp_error($optimization)) {
694 $results['errors'][] = $optimization->get_error_message().' ('.$optimization->get_error_code().')';
695 }
696
697 if ($include_ui_elements && $optimization->get_changes_table_data()) {
698 $table_list = $this->get_table_list();
699 $results['table_list'] = $table_list['table_list'];
700 $results['total_size'] = $table_list['total_size'];
701 }
702 }
703 return $results;
704 }
705
706 /**
707 * Preview command, used to show information about data should be optimized in popup tool.
708 *
709 * @param array $params Should have keys 'optimization_id', 'offset' and 'limit'.
710 *
711 * @return array
712 */
713 public function preview($params) {
714 if (!isset($params['optimization_id'])) {
715 $results = array(
716 'result' => false,
717 'messages' => array(),
718 'errors' => array(
719 __('No optimization was indicated.', 'wp-optimize')
720 )
721 );
722 } else {
723 $optimization_id = $params['optimization_id'];
724 $data = isset($params['data']) ? $params['data'] : array();
725 $params['offset'] = isset($params['offset']) ? (int) $params['offset'] : 0;
726 $params['limit'] = isset($params['limit']) ? (int) $params['limit'] : 50;
727
728 $optimization = $this->optimizer->get_optimization($optimization_id, $data);
729
730 if (is_a($optimization, 'WP_Optimization')) {
731 if (isset($params['site_id'])) {
732 $optimization->switch_to_blog((int) $params['site_id']);
733 }
734 $result = $optimization->preview($params);
735 } else {
736 $result = null;
737 }
738
739 $results = array(
740 'result' => $result,
741 'messages' => array(),
742 'errors' => array()
743 );
744 }
745
746 return $results;
747 }
748
749 /**
750 * Get information about requested optimization.
751 *
752 * @param array $params Should have keys 'optimization_id' and 'data'.
753 * @return array
754 */
755 public function get_optimization_info($params) {
756 if (!isset($params['optimization_id'])) {
757 $results = array(
758 'result' => false,
759 'messages' => array(),
760 'errors' => array(
761 __('No optimization was indicated.', 'wp-optimize')
762 )
763 );
764 } else {
765 $optimization_id = $params['optimization_id'];
766 $data = isset($params['data']) ? $params['data'] : array();
767 $include_ui_elements = isset($data['include_ui_elements']) ? $data['include_ui_elements'] : false;
768
769 $optimization = $this->optimizer->get_optimization($optimization_id, $data);
770 $result = is_a($optimization, 'WP_Optimization') ? $optimization->get_optimization_info() : null;
771
772 $results = array(
773 'result' => $result,
774 'messages' => array(),
775 'errors' => array(),
776 );
777
778 if ($include_ui_elements) {
779 $results['status_box_contents'] = $this->get_status_box_contents();
780 }
781 }
782
783 return $results;
784 }
785
786 /**
787 * Get the data for the tables tab
788 *
789 * @param array $data
790 * @return array
791 */
792 public function get_table_list($data = array()) {
793 if (isset($data['refresh_plugin_json']) && filter_var($data['refresh_plugin_json'], FILTER_VALIDATE_BOOLEAN)) WP_Optimize()->get_db_info()->update_plugin_json();
794
795 $size = $this->optimizer->get_current_db_size();
796
797 return apply_filters('wpo_get_tables_data', array(
798 'table_list' => WP_Optimize()->include_template('database/tables-body.php', true, array('optimize_db' => false)),
799 'total_size' => $size[0]
800 ));
801 }
802
803 /**
804 * Get the database tabs information
805 *
806 * @return array
807 */
808 public function get_database_tabs() {
809 return array_merge(array('optimizations' => $this->get_optimizations_table(), 'does_server_allows_table_optimization' => WP_Optimize()->does_server_allows_table_optimization()), $this->get_table_list());
810 }
811
812 /**
813 * Do action wp_optimize_after_optimizations
814 * used in ajax request after all optimizations completed
815 *
816 * @return boolean
817 */
818 public function optimizations_done() {
819
820 $this->options->update_option('total-cleaned', 0);
821 // Run action after all optimizations completed.
822 do_action('wp_optimize_after_optimizations');
823
824 return true;
825 }
826
827 /**
828 * Return information about all optimizations.
829 *
830 * @param array $params
831 * @return array
832 */
833 public function get_optimizations_info($params) {
834 $this->wpo_sites = isset($params['wpo-sites']) ? $params['wpo-sites'] : 0;
835
836 add_filter('get_optimization_blogs', array($this, 'get_optimization_blogs_filter'));
837
838 $results = array();
839 $optimizations = $this->optimizer->get_optimizations();
840
841 foreach ($optimizations as $optimization_id => $optimization) {
842 if (false === $optimization->display_in_optimizations_list()) continue;
843
844 $results[$optimization_id] = $optimization->get_settings_html();
845 }
846
847 return $results;
848 }
849
850 /**
851 * Filter for get_optimizations_blogs function, used in get_optimizations_info command.
852 * Not intended for direct usage as a command (is used internally as a WP filter)
853 *
854 * The class variable $wpo_sites is used for performing the filtering.
855 *
856 * @param array $sites - unfiltered list of sites
857 * @return array - after filtering
858 */
859 public function get_optimization_blogs_filter($sites) {
860 $sites = array();
861
862 if (!empty($this->wpo_sites)) {
863 foreach ($this->wpo_sites as $site) {
864 if ('all' !== $site) $sites[] = $site;
865 }
866 }
867
868 return $sites;
869 }
870
871 /**
872 * Checks overdue crons and return message
873 */
874 public function check_overdue_crons() {
875 $overdue_crons = WP_Optimize()->howmany_overdue_crons();
876
877 if ($overdue_crons >= 4) {
878 return array('m' => WP_Optimize()->show_admin_warning_overdue_crons($overdue_crons));
879 }
880 }
881
882 /**
883 * Enable or disable Gzip compression.
884 *
885 * @param array $params - ['enable' => true|false]
886 * @return array
887 */
888 public function enable_gzip_compression($params) {
889 return WP_Optimize()->get_gzip_compression()->enable_gzip_command_handler($params);
890 }
891
892 /**
893 * Get the current gzip compression status
894 *
895 * @return array
896 */
897 public function get_gzip_compression_status() {
898 $status = WP_Optimize()->get_gzip_compression()->is_gzip_compression_enabled(true);
899 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);
900 }
901
902 /**
903 * Import WP-Optimize settings.
904 *
905 * @param array $params array with 'settings' item where 'settings' json-encoded string.
906 *
907 * @return Array - the results of the import operation
908 */
909 public function import_settings($params) {
910 if (empty($params['settings'])) {
911 return array('errors' => array(__('Please upload a valid settings file.', 'wp-optimize')));
912 }
913
914 $settings = json_decode($params['settings'], true);
915
916 // check if valid json file posted (requires PHP 5.3+)
917 if ((function_exists('json_last_error') && 0 != json_last_error()) || empty($settings)) {
918 return array('errors' => array(__('Please upload a valid settings file.', 'wp-optimize')));
919 }
920
921 $cache_settings = $settings['cache_settings'];
922 $minify_settings = $settings['minify_settings'];
923 $smush_settings = $settings['smush_settings'];
924 $database_settings = $settings['database_settings'];
925
926 $cache = WP_Optimize()->get_page_cache();
927 $cache->create_folders();
928 if ($cache_settings['enable_page_caching']) {
929 $cache->enable();
930 }
931
932 $wpo_browser_cache = WP_Optimize()->get_browser_cache();
933 if (isset($cache_settings['enable_browser_cache']) && $cache_settings['enable_browser_cache']) {
934 $browser_cache = array(
935 'browser_cache_expire_days' => $cache_settings['browser_cache_expire_days'],
936 'browser_cache_expire_hours' => $cache_settings['browser_cache_expire_hours']
937 );
938 $wpo_browser_cache->enable_browser_cache_command_handler($browser_cache);
939 }
940
941 $message = '';
942 $cache_result = WP_Optimize()->get_page_cache()->config->update($cache_settings);
943 $minify_result = WP_Optimize()->get_minify()->minify_commands->save_minify_settings($minify_settings);
944 $smush_result = WP_Optimize()->get_task_manager()->commands->update_smush_options($smush_settings);
945 $webp_result = WP_Optimize()->get_task_manager()->commands->update_webp_options($smush_settings);
946 $this->save_settings($database_settings);
947
948 if (is_wp_error($cache_result)) {
949 $message .= $cache_result->get_error_message() . PHP_EOL;
950 }
951
952 if (!$minify_result['success']) {
953 $message .= isset($minify_result['message']) ? $minify_result['message'] . PHP_EOL : '';
954 $message .= isset($minify_result['error']) ? $minify_result['error'] . PHP_EOL : '';
955 }
956
957 if (is_wp_error($smush_result)) {
958 $message .= $smush_result->get_error_message() . PHP_EOL;
959 }
960
961 if (is_wp_error($webp_result)) {
962 $message .= $webp_result->get_error_message() . PHP_EOL;
963 }
964
965 return array(
966 'success' => true,
967 'message' => empty($message) ? __('The settings were imported successfully.', 'wp-optimize') : $message
968 );
969 }
970
971 /**
972 * Dismiss install or updated notice
973 *
974 * @return mixed
975 */
976 public function dismiss_install_or_update_notice() {
977 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'))) {
978 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.'));
979 }
980
981 if (!WP_Optimize()->get_install_or_update_notice()->dismiss()) {
982 return array('errors' => array('The notice could not be dismissed. The settings could not be updated'));
983 }
984
985 return true;
986 }
987
988 /**
989 * Run images trash command.
990 */
991 public function images_trash_command($params) {
992 if (!class_exists('WP_Optimize_Images_Trash_Manager_Commands')) {
993 return array(
994 'errors' => array('WP_Optimize_Images_Trash_Manager_Commands class not found'),
995 );
996 }
997
998 // get posted command.
999 $trash_command = isset($params['images_trash_command']) ? $params['images_trash_command'] : '';
1000 // check if command is allowed.
1001 $allowed_commands = WP_Optimize_Images_Trash_Manager_Commands::get_allowed_ajax_commands();
1002
1003 if (!in_array($trash_command, $allowed_commands)) {
1004 return array(
1005 'errors' => array('No such command found'),
1006 );
1007 }
1008
1009 $results = call_user_func(array(WP_Optimize_Images_Trash_Manager()->commands, $trash_command), $params);
1010
1011 if (is_wp_error($results)) {
1012 $results = array(
1013 'errors' => array($results->get_error_message()),
1014 );
1015 }
1016
1017 return $results;
1018 }
1019
1020 /**
1021 * Power tweak handling
1022 *
1023 * @param array $params
1024 * @return mixed
1025 */
1026 public function power_tweak($params) {
1027 global $wp_optimize_premium;
1028 if (!is_a($wp_optimize_premium, 'WP_Optimize_Premium') || !property_exists($wp_optimize_premium, 'power_tweaks') || !isset($params['sub_action'])) return array(
1029 'errors' => array(__('No such command found', 'wp-optimize')),
1030 );
1031
1032 $action = $params['sub_action'];
1033 $data = $params['data'] ? $params['data'] : array();
1034 if (!isset($data['tweak'])) return array(
1035 'errors' => array(__('No tweak provided', 'wp-optimize'))
1036 );
1037
1038 $tweak = sanitize_title($data['tweak']);
1039 $pt = $wp_optimize_premium->power_tweaks;
1040 switch($action) {
1041 case 'activate':
1042 $result = $pt->activate($tweak);
1043 break;
1044 case 'deactivate':
1045 $result = $pt->deactivate($tweak);
1046 break;
1047 case 'run':
1048 $result = $pt->run($tweak);
1049 break;
1050 }
1051 if ($result && !is_wp_error($result)) {
1052 return is_array($result) ? array_merge(array('success' => true), $result) : array('success' => true, 'message' => $result);
1053 } else {
1054 $error_message = is_wp_error($result) ? $result->get_error_message() : sprintf(__('The command %s failed', 'wp-optimize'), $action);
1055 return array(
1056 'success' => false,
1057 'errors' => array($error_message)
1058 );
1059 }
1060 }
1061
1062 /**
1063 * Ignores the table delete warning for the current user
1064 *
1065 * @return boolean
1066 */
1067 public function user_ignores_table_delete_warning() {
1068 return array(
1069 'success' => update_user_meta(get_current_user_id(), 'wpo-ignores-table-delete-warning', true)
1070 );
1071 }
1072
1073 /**
1074 * Exports unused images as a CSV file to the `uploads` folder
1075 *
1076 * @return array
1077 */
1078 public function export_csv() {
1079 WP_Optimization_images::instance()->output_csv();
1080 return array(
1081 'success' => true
1082 );
1083 }
1084 }
1085