PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 3.7.1
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v3.7.1
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-updraft-smush-manager-commands.php

class-updraft-smush-manager-commands.php in WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance 3.7.1, at includes/class-updraft-smush-manager-commands.php

735 lines 25.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * A Smush Task manager class
4 */
5
6 if (!defined('ABSPATH')) die('Access denied.');
7
8 if (!class_exists('Updraft_Task_Manager_Commands_1_0')) require_once(WPO_PLUGIN_MAIN_PATH . 'vendor/team-updraft/common-libs/src/updraft-tasks/class-updraft-task-manager-commands.php');
9
10 if (!class_exists('Updraft_Smush_Manager_Commands')) :
11
12 class Updraft_Smush_Manager_Commands extends Updraft_Task_Manager_Commands_1_0 {
13
14 /**
15 * Stores the bulk of images to be processed
16 *
17 * @var array
18 */
19 private $images = array();
20
21 /**
22 * Flag to return a valid envelope on AJAX calls
23 *
24 * @var bool
25 */
26 public $background_command = false;
27
28 /**
29 * Flag to return a valid envelope on heartbeat AJAX calls
30 *
31 * @var bool
32 */
33 public $heartbeat_command = false;
34
35 /**
36 * Store the response to be sent at shutdown
37 *
38 * @var array
39 */
40 public $final_response = array();
41
42 /**
43 * The commands constructor
44 *
45 * @param mixed $task_manager - A task manager instance
46 */
47 public function __construct($task_manager) {
48 parent::__construct($task_manager);
49 }
50
51 /**
52 * Returns a list of commands available for smush related operations
53 */
54 public static function get_allowed_ajax_commands() {
55
56 $commands = parent::get_allowed_ajax_commands();
57
58 $smush_commands = array(
59 'compress_single_image',
60 'restore_single_image',
61 'process_bulk_smush',
62 'update_smush_options',
63 'get_ui_update',
64 'process_pending_images',
65 'clear_pending_images',
66 'clear_smush_stats',
67 'check_server_status',
68 'get_smush_logs',
69 'mark_as_compressed',
70 'mark_all_as_uncompressed',
71 'clean_all_backup_images',
72 'reset_webp_serving_method',
73 'convert_to_webp_format',
74 'update_webp_options',
75 'get_smush_details',
76 'get_smush_settings_form',
77 );
78
79 return array_merge($commands, $smush_commands);
80 }
81
82 /**
83 * Process the compression of a single image
84 *
85 * @param mixed $data - sent in via AJAX
86 * @return WP_Error|array - information about the operation or WP_Error object on failure
87 */
88 public function compress_single_image($data) {
89
90 $options = !empty($data['smush_options']) ? $data['smush_options'] : $this->task_manager->get_smush_options();
91 $image = isset($data['selected_image']) ? filter_var($data['selected_image']['attachment_id'], FILTER_SANITIZE_NUMBER_INT) : false;
92 $blog = isset($data['selected_image']) ? filter_var($data['selected_image']['blog_id'], FILTER_SANITIZE_NUMBER_INT) : false;
93
94 // A subsite administrator can only compress their own image. If the blog ID isn't theirs, return an error.
95 if ($blog && is_multisite() && get_current_blog_id() != $blog && !current_user_can('manage_network_options')) {
96 return new WP_Error('compression_not_permitted', __('The blog ID provided does not match the current blog.', 'wp-optimize'));
97 }
98
99 $server = sanitize_text_field($options['compression_server']);
100
101 $lossy = filter_var($options['lossy_compression'], FILTER_VALIDATE_BOOLEAN) ? true : false;
102 $backup = filter_var($options['back_up_original'], FILTER_VALIDATE_BOOLEAN) ? true : false;
103 $exif = filter_var($options['preserve_exif'], FILTER_VALIDATE_BOOLEAN) ? true : false;
104 $quality = filter_var($options['image_quality'], FILTER_SANITIZE_NUMBER_INT);
105
106 $options = array(
107 'attachment_id' => $image,
108 'blog_id' => $blog,
109 'image_quality' => $quality,
110 'keep_original' => $backup,
111 'lossy_compression' => $lossy,
112 'preserve_exif' => $exif
113 );
114
115 if (filesize(get_attached_file($image)) > 5242880) {
116 $options['request_timeout'] = 180;
117 }
118
119 $success = $this->task_manager->compress_single_image($image, $options, $server);
120
121 if (!$success) {
122 return new WP_Error('compress_failed', get_post_meta($image, 'smush-info', true));
123 }
124
125 $response = array();
126 $response['status'] = true;
127 $response['operation'] = 'compress';
128 $response['options'] = $options;
129 $response['server'] = $server;
130 $response['success'] = $success;
131 $response['restore_possible'] = $backup;
132 $response['summary'] = get_post_meta($image, 'smush-info', true);
133
134 $smush_stats = get_post_meta($image, 'smush-stats', true);
135 if (isset($smush_stats['sizes-info'])) {
136 $response['sizes-info'] = WP_Optimize()->include_template('images/smush-details.php', true, array('sizes_info' => $smush_stats['sizes-info']));
137 }
138
139 $response['media_column_html'] = $this->get_smush_media_column_content($blog, $image);
140
141 return $response;
142 }
143
144 /**
145 * Restores a single image, if backup is available
146 *
147 * @param mixed $data - Sent in via AJAX
148 * @return WP_Error|array - information about the operation or a WP_Error object on failure
149 */
150 public function restore_single_image($data) {
151
152 $blog_id = isset($data['blog_id']) ? $data['blog_id'] : false;
153 $image_id = isset($data['selected_image']) ? $data['selected_image'] : false;
154
155 $success = $this->task_manager->restore_single_image($image_id, $blog_id);
156
157 if (is_wp_error($success)) {
158 return $success;
159 }
160
161 $response = array();
162 $response['status'] = true;
163 $response['operation'] = 'restore';
164 $response['blog_id'] = $blog_id;
165 $response['image'] = $image_id;
166 $response['success'] = $success;
167 $response['summary'] = __('The image was restored successfully', 'wp-optimize');
168
169 $response['media_column_html'] = $this->get_smush_media_column_content($blog_id, $image_id);
170
171 return $response;
172 }
173
174 /**
175 * Process the compression of multiple images
176 *
177 * @param mixed $data - Sent in via AJAX
178 * @return array
179 */
180 public function process_bulk_smush($data = array()) {
181 $images = isset($data['selected_images']) ? $data['selected_images'] : array();
182
183 $this->images = $images;
184
185 $this->background_command = true;
186
187 $this->final_response = $this->get_ui_update($this->images);
188
189 add_action('shutdown', array($this, 'process_bulk_smush_shutdown'));
190
191 return $this->final_response;
192 }
193
194 /**
195 * Close request connection at the `shutdown` hook and start processing the bulk
196 *
197 * @return void
198 */
199 public function process_bulk_smush_shutdown() {
200 WP_Optimize()->close_browser_connection(json_encode($this->final_response));
201
202 $this->task_manager->process_bulk_smush($this->images);
203 exit;
204 }
205
206 /**
207 * Returns useful information for the UI and closes the connection
208 *
209 * @param mixed $data - Sent in via AJAX
210 *
211 * @return array - Information for the UI
212 */
213 public function get_ui_update($data) {
214 $ui_update = array();
215 $ui_update['status'] = true;
216 $ui_update['is_multisite'] = is_multisite() ? 1 : 0;
217 $pending_tasks = $this->task_manager->get_pending_tasks();
218
219 $ui_update['pending_tasks'] = is_array($pending_tasks) ? count($this->task_manager->get_pending_tasks()) : 0;
220 $ui_update['unsmushed_images'] = $this->task_manager->get_uncompressed_images(isset($data['use_cache']) ? $data['use_cache'] : "true");
221 $ui_update['admin_urls'] = $this->task_manager->get_admin_urls();
222 $ui_update['completed_task_count'] = $this->task_manager->options->get_option('completed_task_count', 0);
223 $ui_update['bytes_saved'] = WP_Optimize()->format_size($this->task_manager->options->get_option('total_bytes_saved', 0));
224 $ui_update['percent_saved'] = number_format($this->task_manager->options->get_option('total_percent_saved', 1), 2).'%';
225 $ui_update['failed_task_count'] = $this->task_manager->get_failed_task_count();
226
227 if (is_multisite()) {
228 $ui_update['summary'] = sprintf(__('Since the last reset of compression statistics on this multisite, a total of %d image(s) were compressed across the network.', 'wp-optimize').' '.__('This saved approximately %s of space at an average of %02d percent per image.', 'wp-optimize'), $ui_update['completed_task_count'], $ui_update['bytes_saved'], $ui_update['percent_saved']);
229 } else {
230 $ui_update['summary'] = sprintf(__('Since your compression statistics were last reset, a total of %d image(s) were compressed on this site.', 'wp-optimize').' '.__('This saved approximately %s of space at an average of %02d percent per image.', 'wp-optimize'), $ui_update['completed_task_count'], $ui_update['bytes_saved'], $ui_update['percent_saved']);
231 }
232 $ui_update['failed'] = sprintf(__("%d image(s) could not be compressed.", 'wp-optimize'), $ui_update['failed_task_count']) . ' ' . __('Please see the logs for more information, or try again later.', 'wp-optimize');
233 $ui_update['pending'] = sprintf(__("%d image(s) images were selected for compressing previously, but were not all processed.", 'wp-optimize'), $ui_update['pending_tasks']) . ' ' . __('You can either complete them now or cancel and retry later.', 'wp-optimize');
234 $ui_update['smush_complete'] = $this->task_manager->is_queue_processed();
235
236 if (isset($data['image_list'])) {
237 $images = $data['image_list'];
238 $stats = $this->task_manager->get_session_stats($images);
239 $ui_update['session_stats'] = "";
240
241 if (!empty($stats['success'])) {
242 $ui_update['session_stats'] .= sprintf(__("A total of %d image(s) were successfully compressed in this iteration.", 'wp-optimize'), $stats['success']);
243 }
244
245 if (!empty($stats['fail'])) {
246 $ui_update['session_stats'] .= sprintf(__("%d selected image(s) could not be compressed.", 'wp-optimize'), $stats['fail']) . ' ' . __('Please see the logs for more information, you may try again later.', 'wp-optimize');
247 }
248 }
249
250 return $ui_update;
251
252 }
253
254 /**
255 * Updates webp related options
256 *
257 * @param mixed $data - Sent in via AJAX
258 * @return WP_Error|array - information about the operation or WP_Error object on failure
259 */
260 public function update_webp_options($data) {
261 $webp_instance = WP_Optimize()->get_webp_instance();
262 $options = array();
263 $options['webp_conversion'] = filter_var($data['webp_conversion'], FILTER_VALIDATE_BOOLEAN);
264
265 // Only run checks when trying to enable WebP
266 if ($options['webp_conversion']) {
267 //Run checks if we are enabling webp conversion
268 if (!$webp_instance->shell_functions_available()) {
269 $webp_instance->disable_webp_conversion();
270 $webp_instance->log("Required WebP shell functions are not available on the server, disabling WebP conversion");
271 return new WP_Error('update_failed_no_shell_functions', __('Required WebP shell functions are not available on the server.', 'wp-optimize'));
272 }
273
274 // Run conversion test if not already done and set necessary option value
275 if ($webp_instance->should_run_webp_conversion_test()) {
276 $converter_status = WPO_WebP_Test_Run::get_converter_status();
277
278 if (!$webp_instance->is_webp_conversion_successful()) {
279 $webp_instance->disable_webp_conversion();
280 $webp_instance->log("No working WebP converter was found on the server when updating WebP options, disabling WebP conversion");
281 return new WP_Error('update_failed_no_working_webp_converter', __('No working WebP converter was found on the server.', 'wp-optimize'));
282 }
283
284 $options['webp_conversion_test'] = true;
285 $options['webp_converters'] = $converter_status['working_converters'];
286 }
287
288 // Run serving methods tests and set necessary option values
289 // Not possible to test alter html since test is browser based
290 $webp_instance->save_htaccess_rules();
291 if (!$webp_instance->is_webp_redirection_possible()) {
292 $webp_instance->empty_htaccess_file();
293 $options['redirection_possible'] = 'false';
294 } else {
295 $options['redirection_possible'] = 'true';
296 }
297 }
298
299 $success = $this->task_manager->update_smush_options($options);
300
301 if (!$success) {
302 $webp_instance->disable_webp_conversion();
303 $webp_instance->log("WebP options could not be updated");
304 return new WP_Error('update_failed', __('WebP options could not be updated.', 'wp-optimize'));
305 }
306
307 // Setup daily CRON only when enabling WebP and Delete daily CRON when disabling WebP
308 if ($options['webp_conversion']) {
309 $webp_instance->init_webp_cron_scheduler();
310 } else {
311 $webp_instance->remove_webp_cron_schedules();
312 $webp_instance->empty_htaccess_file();
313 }
314
315 do_action('wpo_save_images_settings');
316
317 $response = array();
318 $response['status'] = true;
319 $response['saved'] = $success;
320 $response['summary'] = __('WebP options updated successfully.', 'wp-optimize');
321
322 return $response;
323 }
324
325 /**
326 * Updates smush related options
327 *
328 * @param mixed $data - Sent in via AJAX
329 * @return WP_Error|array - information about the operation or WP_Error object on failure
330 */
331 public function update_smush_options($data) {
332 $options = array();
333 $options['compression_server'] = sanitize_text_field($data['compression_server']);
334 $options['lossy_compression'] = filter_var($data['lossy_compression'], FILTER_VALIDATE_BOOLEAN) ? true : false;
335 $options['back_up_original'] = filter_var($data['back_up_original'], FILTER_VALIDATE_BOOLEAN) ? true : false;
336 $options['back_up_delete_after'] = filter_var($data['back_up_delete_after'], FILTER_VALIDATE_BOOLEAN) ? true : false;
337 $options['back_up_delete_after_days'] = filter_var($data['back_up_delete_after_days'], FILTER_SANITIZE_NUMBER_INT);
338 $options['preserve_exif'] = filter_var($data['preserve_exif'], FILTER_VALIDATE_BOOLEAN) ? true : false;
339 $options['autosmush'] = filter_var($data['autosmush'], FILTER_VALIDATE_BOOLEAN) ? true : false;
340 $options['image_quality'] = filter_var($data['image_quality'], FILTER_SANITIZE_NUMBER_INT);
341 $options['show_smush_metabox'] = filter_var($data['show_smush_metabox'], FILTER_VALIDATE_BOOLEAN) ? 'show' : 'hide';
342
343 $success = $this->task_manager->update_smush_options($options);
344
345 if (!$success) {
346 return new WP_Error('update_failed', __('Smush options could not be updated', 'wp-optimize'));
347 }
348
349 do_action('wpo_save_images_settings');
350
351 $response = array();
352 $response['status'] = true;
353 $response['saved'] = $success;
354 $response['summary'] = __('Options updated successfully', 'wp-optimize');
355
356 return $response;
357 }
358
359 /**
360 * Clears any smush related stats
361 *
362 * @return WP_Error|array - information about the operation or WP_Error object on failure
363 */
364 public function clear_smush_stats() {
365
366 $success = $this->task_manager->clear_smush_stats();
367
368 if (!$success) {
369 return new WP_Error('update_failed', __('Stats could not be cleared', 'wp-optimize'));
370 }
371
372 $response = array();
373 $response['status'] = true;
374 $response['summary'] = __('Stats cleared successfully', 'wp-optimize');
375
376 return $response;
377 }
378
379 /**
380 * Checks if the selected server is online
381 *
382 * @param mixed $data - Sent in via AJAX
383 */
384 public function check_server_status($data) {
385 $server = sanitize_text_field($data['server']);
386 $response = array();
387 $response['status'] = true;
388 $response['online'] = $this->task_manager->check_server_online($server);
389
390 if (!$response['online']) {
391 $response['error'] = get_option($this->task_manager->get_associated_task($server));
392 }
393
394 return $response;
395 }
396
397 /**
398 * Completes any pending tasks
399 *
400 * @return array
401 */
402 public function process_pending_images() {
403 return $this->process_bulk_smush();
404 }
405
406 /**
407 * Deletes and removes any pending tasks from queue
408 *
409 * @param array $data - in 'restore_images' index passed an array with ids of images to restore
410 * @return WP_Error|array - information about the operation or WP_Error object on failure
411 */
412 public function clear_pending_images($data) {
413
414 if (!empty($data['restore_images'])) {
415 foreach ($data['restore_images'] as $image) {
416 $this->task_manager->restore_single_image($image['attachment_id'], $image['blog_id']);
417 }
418 }
419
420 $success = $this->task_manager->clear_pending_images();
421
422 if (!$success) {
423 return new WP_Error('error_deleting_tasks', __('Pending tasks could not be cleared', 'wp-optimize'));
424 }
425
426 $response = array();
427 $response['status'] = true;
428 $response['summary'] = __('Pending tasks cleared successfully', 'wp-optimize');
429
430 return $response;
431 }
432
433 /**
434 * Mark selected images as already compressed.
435 *
436 * @param array $data
437 * @return array
438 */
439 public function mark_as_compressed($data) {
440 $response = array();
441 $selected_images = array();
442
443 $unmark = isset($data['unmark']) && $data['unmark'];
444
445 foreach ($data['selected_images'] as $image) {
446 if (!array_key_exists($image['blog_id'], $selected_images)) $selected_images[$image['blog_id']] = array();
447
448 $selected_images[$image['blog_id']][] = $image['attachment_id'];
449 }
450
451 $info = __('This image is marked as already compressed by another tool.', 'wp-optimize');
452
453 foreach (array_keys($selected_images) as $blog_id) {
454 if (is_multisite()) switch_to_blog($blog_id);
455
456 foreach ($selected_images[$blog_id] as $attachment_id) {
457 if ($unmark) {
458 delete_post_meta($attachment_id, 'smush-complete');
459 delete_post_meta($attachment_id, 'smush-marked');
460 delete_post_meta($attachment_id, 'smush-info');
461 } else {
462 update_post_meta($attachment_id, 'smush-complete', true);
463 update_post_meta($attachment_id, 'smush-marked', true);
464 update_post_meta($attachment_id, 'smush-info', $info);
465 }
466 }
467
468 if (is_multisite()) restore_current_blog();
469 }
470
471 $response['status'] = true;
472
473 if ($unmark) {
474 $response['summary'] = _n('The selected image was successfully marked as uncompressed', 'The selected images were successfully marked as uncompressed', count($data['selected_images']), 'wp-optimize');
475 } else {
476 $response['summary'] = _n('The selected image was successfully marked as compressed', 'The selected images were successfully marked as compressed', count($data['selected_images']), 'wp-optimize');
477 }
478
479 $response['info'] = $info;
480
481 if (1 === count($data['selected_images'])) {
482 $selected_image = reset($data['selected_images']);
483 $response['media_column_html'] = $this->get_smush_media_column_content($selected_image['blog_id'], $selected_image['attachment_id']);
484 }
485
486 return $response;
487 }
488
489 /**
490 * Mark all images as uncompressed and if posted restore_backup argument
491 * then try to restore images form backup.
492 *
493 * @param array $data
494 * @return array
495 */
496 public function mark_all_as_uncompressed($data) {
497
498 $restore_backup = isset($data['restore_backup']) && $data['restore_backup'];
499 $images_per_request = apply_filters('mark_all_as_uncompressed_images_per_request', 100);
500 $delete_only_backups_meta = isset($data['delete_only_backups_meta']) && $data['delete_only_backups_meta'];
501
502 if (is_multisite()) {
503 // option where we store last completed blog id
504 $option_name = 'mark_as_uncompressed_last_blog_id';
505 $smushed_images_total_option_name = 'smushed_images_total';
506 // set default value for response
507 $response = array(
508 'completed' => true,
509 'message' => __('All the compressed images were successfully restored.', 'wp-optimize'),
510 );
511
512 // get all blogs ids
513 $blogs = WP_Optimize()->get_sites();
514 $blogs_ids = wp_list_pluck($blogs, 'blog_id');
515 sort($blogs_ids);
516
517 // select the blog for processing
518 $last_completed_blog_id = $this->task_manager->options->get_option($option_name, false);
519 $index = $last_completed_blog_id ? array_search($last_completed_blog_id, $blogs_ids) + 1 : 0;
520
521 if ($index < count($blogs_ids)) {
522 $blog_id = $blogs_ids[$index];
523 $response = $this->task_manager->bulk_restore_compressed_images($restore_backup, $blog_id, $images_per_request, $delete_only_backups_meta);
524 $smushed_images_total = $this->task_manager->options->get_option($smushed_images_total_option_name, 0) + $response['smushed_images_count'];
525 // if we get completed the current blog then update last completed blog option value
526 // and if we have other blogs for processing then set complete to false as we have not
527 // processed all blogs
528 if ($response['completed']) {
529 if ($index + 1 < count($blogs_ids)) {
530 $response['completed'] = false;
531 $this->task_manager->options->update_option($option_name, $blog_id);
532 $this->task_manager->options->update_option($smushed_images_total_option_name, $smushed_images_total);
533 } else {
534 if ($delete_only_backups_meta) {
535 if ($smushed_images_total > 0) {
536 $response['message'] = __('All the compressed images with backup copies of their original files were successfully restored.', 'wp-optimize');
537 $response['message'] .= ' '.sprintf(_n('Unable to restore %s image without backup files.', 'Unable to restore %s images without backup files.', $smushed_images_total, 'wp-optimize'), $smushed_images_total);
538 } else {
539 $response['message'] = __('All the compressed images were successfully restored.', 'wp-optimize');
540 }
541 } else {
542 $response['message'] = __('All the compressed images were successfully marked as uncompressed.', 'wp-optimize');
543 }
544 }
545 }
546 }
547
548 // if we get an error or completed the work then delete option with last completed blog id.
549 if ($response['completed'] || isset($response['error'])) {
550 $this->task_manager->options->delete_option($option_name);
551 $this->task_manager->options->delete_option($smushed_images_total_option_name);
552 }
553 } else {
554 $response = $this->task_manager->bulk_restore_compressed_images($restore_backup, 0, $images_per_request, $delete_only_backups_meta);
555 }
556
557 return $response;
558 }
559
560 /**
561 * Returns the log file
562 *
563 * @return WP_Error|file - logfile or WP_Error object on failure
564 */
565 public function get_smush_logs() {
566
567 $logfile = $this->task_manager->get_logfile_path();
568
569 if (!file_exists($logfile)) {
570 $this->task_manager->write_log_header();
571 }
572
573 if (is_file($logfile)) {
574 if ($this->heartbeat_command) {
575 // The response will be inside the heartbeat response envelope, as each response of a heartbeat goes in its own unique ID key
576 readfile($logfile);
577 } else {
578 // Headers are needed for the `Download logs` link, which will run this command and just prompt a file download
579 header('Content-Description: File Transfer');
580 header('Content-Type: application/octet-stream');
581 header('Content-Disposition: attachment; filename="'.basename($logfile).'"');
582 header('Expires: 0');
583 header('Cache-Control: must-revalidate');
584 header('Pragma: public');
585 header('Content-Length: ' . filesize($logfile));
586 readfile($logfile);
587 exit;
588 }
589 } else {
590 return new WP_Error('log_file_error', __('Log file does not exist or could not be read', 'wp-optimize'));
591 }
592 }
593
594 /**
595 * Clean all backup images command.
596 *
597 * @return array
598 */
599 public function clean_all_backup_images() {
600 $upload_dir = wp_upload_dir(null, false);
601 $base_dir = $upload_dir['basedir'];
602
603 $this->task_manager->clear_backup_images_directory($base_dir, 0);
604
605 return array(
606 'status' => true,
607 );
608 }
609
610 /**
611 * Resets webp serving method
612 *
613 * @return array|WP_Error
614 */
615 public function reset_webp_serving_method() {
616 $webp_instance = WP_Optimize()->get_webp_instance();
617 //Run checks before calling reset_webp_serving_method
618 if (!$webp_instance->shell_functions_available()) {
619 $webp_instance->disable_webp_conversion();
620 $webp_instance->log("The WebP serving method cannot be reset because required WebP shell functions are not available on the server");
621 return new WP_Error('reset_failed_no_shell_functions', __('The WebP serving method cannot be reset because required WebP shell functions are not available on the server', 'wp-optimize'));
622 } elseif (!$webp_instance->is_webp_conversion_enabled()) {
623 $webp_instance->disable_webp_conversion();
624 $webp_instance->log("The WebP serving method cannot be reset because WebP conversion is currently disabled");
625 return new WP_Error('reset_failed_webp_conversion_disabled', __('The WebP serving method cannot be reset because WebP conversion is currently disabled', 'wp-optimize'));
626 }
627
628 $webp_instance->reset_webp_serving_method();
629 return array(
630 'success' => true,
631 );
632 }
633
634 /**
635 * Convert the image to webp format
636 *
637 * @param array $data
638 * @return array
639 */
640 public function convert_to_webp_format($data) {
641 $attachment_id = isset($data['attachment_id']) ? $data['attachment_id'] : 0;
642 if (0 === $attachment_id) return $this->image_not_found_response();
643
644 $images = WPO_Image_Utils::get_attachment_files($attachment_id);
645 if (empty($images)) return $this->image_not_found_response();
646
647 $images['original'] = get_attached_file($attachment_id);
648 foreach ($images as $image) {
649 WPO_WebP_Utils::do_webp_conversion($image);
650 }
651
652 return array(
653 'success' => __('Image is converted to WebP format.', 'wp-optimize'),
654 );
655 }
656
657 /**
658 * Get Smush settings form
659 *
660 * @param array $data
661 * @return array
662 */
663 public function get_smush_settings_form($data) {
664 $attachment_id = isset($data['attachment_id']) ? $data['attachment_id'] : 0;
665 if (0 === $attachment_id) return $this->image_not_found_response();
666
667 $compressed = get_post_meta($attachment_id, 'smush-complete', true) ? true : false;
668
669 $smush_options = Updraft_Smush_Manager()->get_smush_options();
670
671 $extract = array(
672 'post_id' => $attachment_id,
673 'smush_options' => $smush_options,
674 'custom' => 90 >= $smush_options['image_quality'] && 65 <= $smush_options['image_quality'],
675 'smush_display' => $compressed ? "display:none;" : "display:block;",
676 );
677
678 return array(
679 'success' => true,
680 'html' => WP_Optimize()->include_template('admin-metabox-smush-settings.php', true, $extract),
681 );
682 }
683
684 /**
685 * Get content for Media Library column content
686 *
687 * @param {int} $blog_id
688 * @param {int} $attachment_id
689 *
690 * @return string
691 */
692 private function get_smush_media_column_content($blog_id, $attachment_id) {
693 if (is_multisite()) switch_to_blog($blog_id);
694
695 $content = Updraft_Smush_Manager()->get_smush_details($attachment_id);
696
697 if (is_multisite()) restore_current_blog();
698
699 return $content;
700 }
701
702 /**
703 * Returns image not found response
704 *
705 * @return array
706 */
707 private function image_not_found_response() {
708 return array(
709 'error' => __('Image not found', 'wp-optimize'),
710 );
711 }
712
713 /**
714 * Get smush details of given image IDs
715 *
716 * @param array $data
717 *
718 * @return array
719 */
720 public function get_smush_details($data) {
721 $selected_images = isset($data['selected_images']) ? $data['selected_images'] : array();
722 $smush_details = array();
723 foreach ($selected_images as $attachment_id) {
724 $smush_details[$attachment_id] = $this->task_manager->get_smush_details($attachment_id);
725 }
726
727 return array(
728 'success' => true,
729 'smush_details' => $smush_details,
730 );
731 }
732 }
733
734 endif;
735