PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.7.0
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.7.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
← All changes | includes/class-updraft-smush-manager.php +211 -186 3.7.0 → 4.7.0 View file →
@@ -74,11 +74,10 @@
74 74 add_action('ud_task_completed', array($this, 'record_stats'));
75 75 add_action('ud_task_failed', array($this, 'record_stats'));
76 76 add_action('prune_smush_logs', array($this, 'prune_smush_logs'));
77 77 add_action('process_smush_tasks', array($this, 'process_smush_tasks'));
78 - if ('show' == $this->options->get_option('show_smush_metabox', 'show')) {
78 + if ('show' === $this->options->get_option('show_smush_metabox', 'show')) {
79 79 add_action('add_meta_boxes_attachment', array($this, 'add_smush_metabox'), 10, 2);
80 - add_filter('attachment_fields_to_edit', array($this, 'add_compress_button_to_media_modal' ), 10, 2);
81 80 }
82 81 add_action('delete_attachment', array($this, 'unscheduled_original_file_deletion'));
83 82
84 83 add_filter('manage_media_columns', array($this, 'manage_media_columns'));
@@ -89,9 +88,9 @@
89 88
90 89 // add filter for already compressed images by EWWW Image Optimizer.
91 90 add_filter('wpo_get_uncompressed_images_args', array($this, 'ewww_image_optimizer_compressed_images_args'));
92 91
93 - // schedule or unschedule clear backup images cron if need
92 + // schedule or unschedule clear backup images cron, if needed
94 93 $scheduled = wp_next_scheduled('wpo_smush_clear_backup_images');
95 94 if ($this->options->get_option('back_up_delete_after', true)) {
96 95 if (!$scheduled) {
97 96 wp_schedule_event(time(), 'daily', 'wpo_smush_clear_backup_images');
@@ -112,9 +111,9 @@
112 111 /**
113 112 * Add custom column to Media Library.
114 113 *
115 114 * @param array $columns
116 - * @return mixed
115 + * @return array
117 116 */
118 117 public function manage_media_columns($columns) {
119 118 $columns['wpo_smush'] = 'WP-Optimize';
120 119
@@ -155,17 +154,20 @@
155 154 * @return string
156 155 */
157 156 public function get_media_smush_column_content($attachment_id) {
158 157 $file = get_attached_file($attachment_id);
158 + if (false === $file) {
159 + return '';
160 + }
159 161 $ext = WPO_Image_Utils::get_extension($file);
160 162 $allowed_extensions = WPO_Image_Utils::get_allowed_extensions();
161 163
162 - $compressed = get_post_meta($attachment_id, 'smush-complete', true) ? true : false;
163 - $has_backup = get_post_meta($attachment_id, 'original-file', true) ? true : false;
164 + $compressed = get_post_meta($attachment_id, '_wpo-smush-complete', true) ? true : false;
165 + $has_backup = get_post_meta($attachment_id, '_wpo-original-file', true) ? true : false;
164 166
165 - $smush_info = get_post_meta($attachment_id, 'smush-info', true);
166 - $smush_stats = get_post_meta($attachment_id, 'smush-stats', true);
167 - $marked = get_post_meta($attachment_id, 'smush-marked', false);
167 + $smush_info = get_post_meta($attachment_id, '_wpo-smush-info', true);
168 + $smush_stats = get_post_meta($attachment_id, '_wpo-smush-stats', true);
169 + $marked = get_post_meta($attachment_id, '_wpo-smush-marked');
168 170
169 171 $extract = array(
170 172 'blog_id' => get_current_blog_id(),
171 173 'post_id' => $attachment_id,
@@ -174,9 +176,9 @@
174 176 'before_smush_sep' => !$compressed ? '<span class="wpo-action-separator"> | </span>' : '',
175 177 'restore_action' => $has_backup && $compressed ? "display:block;" : "display:none;",
176 178 'smush_mark' => !$compressed && !$marked ? "display:inline-block;" : "display:none;",
177 179 'smush_unmark' => $marked ? "display:inline-block;" : "display:none;",
178 - 'smush_info' => $smush_info ? $smush_info : ' ',
180 + 'smush_info' => $smush_info ?: ' ',
179 181 'smush_details' => '',
180 182 'restore_tooltip' => $this->get_restore_image_tooltip_text(),
181 183 'smush_marked' => $marked,
182 184 );
@@ -199,8 +201,9 @@
199 201
200 202 if (WPO_Image_Utils::is_supported_extension($ext, array_diff($allowed_extensions, array('gif'))) && file_exists($file) && !file_exists($file . '.webp')) {
201 203 if (WPO_WebP_Utils::can_do_webp_conversion()) {
202 204 $link_text = __('Convert to WebP', 'wp-optimize');
205 + $output .= '<span class="wpo-action-separator"> | </span>';
203 206 $output .= sprintf('<a href="#" class="convert-to-webp" data-attachment-id="%d">%s</a><br>', esc_attr($attachment_id), esc_html($link_text));
204 207 }
205 208 }
206 209
@@ -211,25 +214,25 @@
211 214 * The Task Manager AJAX handler
212 215 */
213 216 public function updraft_smush_ajax() {
214 217
215 - $nonce = empty($_REQUEST['nonce']) ? '' : $_REQUEST['nonce'];
218 + $nonce = TeamUpdraft\WP_Optimize\Includes\Fragments\verify_nonce('nonce', 'updraft-task-manager-ajax-nonce');
219 + $subaction = TeamUpdraft\WP_Optimize\Includes\Fragments\fetch_superglobal('request', 'subaction', null, 'sanitize_key');
220 + $data = TeamUpdraft\WP_Optimize\Includes\Fragments\fetch_superglobal('request', 'data');
216 221
217 - if (!wp_verify_nonce($nonce, 'updraft-task-manager-ajax-nonce') || empty($_REQUEST['subaction']))
222 + if (empty($nonce) || empty($subaction)) {
218 223 die('Security check failed');
224 + }
219 225
220 - if (!current_user_can(WP_Optimize()->capability_required())) {
226 + if (!WP_Optimize()->current_user_can()) {
221 227 die('You are not allowed to run this command.');
222 228 }
223 229
224 - $subaction = $_REQUEST['subaction'];
225 -
226 230 $allowed_commands = Updraft_Smush_Manager_Commands::get_allowed_ajax_commands();
227 231
228 232 if (in_array($subaction, $allowed_commands)) {
229 233
230 - if (isset($_REQUEST['data'])) {
231 - $data = $_REQUEST['data'];
234 + if ($data) {
232 235 $results = call_user_func(array($this->commands, $subaction), $data);
233 236 } else {
234 237 $results = call_user_func(array($this->commands, $subaction));
235 238 }
@@ -243,11 +246,11 @@
243 246 'error_data' => $results->get_error_data(),
244 247 );
245 248 }
246 249
247 - echo json_encode($results);
250 + echo wp_json_encode($results);
248 251 } else {
249 - echo json_encode(array('error' => 'No such command found'));
252 + echo wp_json_encode(array('error' => 'No such command found'));
250 253 }
251 254 die();
252 255 }
253 256
@@ -264,28 +267,22 @@
264 267 $allowed_extensions = WPO_Image_Utils::get_allowed_extensions();
265 268
266 269 if(!in_array($ext, $allowed_extensions)) return;
267 270
268 - if (!$this->options->get_option('autosmush', false))
271 + if (!$this->options->get_option('autosmush'))
269 272 return;
270 273
271 - if (!'image' == substr($post->post_mime_type, 0, 5))
274 + if ('image' !== substr($post->post_mime_type, 0, 5))
272 275 return;
273 276
274 277 if ($this->task_exists($post_id))
275 278 return;
276 -
277 - $options = array(
278 - 'attachment_id' => $post_id,
279 - 'blog_id' => get_current_blog_id(),
280 - 'image_quality' => $this->options->get_option('image_quality', 92),
281 - 'keep_original' => $this->options->get_option('back_up_original', true),
282 - 'preserve_exif' => $this->options->get_option('preserve_exif', true),
283 - 'lossy_compression' => $this->options->get_option('lossy_compression', false)
284 - );
285 279
280 + $task_options = $this->get_smush_options();
281 + $task_options = array_merge($task_options, array('attachment_id' => $post_id, 'blog_id' => get_current_blog_id()));
282 +
286 283 if (filesize($file) > 5242880) {
287 - $options['request_timeout'] = 180;
284 + $task_options['request_timeout'] = 180;
288 285 }
289 286
290 287 $server = $this->options->get_option('compression_server', $this->webservice);
291 288 $task_name = $this->get_associated_task($server);
@@ -290,11 +287,11 @@
290 287 $server = $this->options->get_option('compression_server', $this->webservice);
291 288 $task_name = $this->get_associated_task($server);
292 289
293 290 $blog_info = is_multisite() ? ', blog ID : '.get_current_blog_id() : '';
294 - $description = "$task_name with attachment ID : ".$post_id . $blog_info .", autocreated on : ".date("F d, Y h:i:s", time());
291 + $description = "$task_name with attachment ID : ".$post_id . $blog_info .", auto created on : ".gmdate("F d, Y h:i:s", time());
295 292
296 - $task = call_user_func(array($task_name, 'create_task'), 'smush', $description, $options, $task_name);
293 + $task = call_user_func(array($task_name, 'create_task'), 'smush', $description, $task_options, $task_name);
297 294
298 295 if ($task) $this->set_task_logger($task);
299 296 $this->log($description);
300 297
@@ -341,14 +338,14 @@
341 338 * @param int $image - ID of image
342 339 * @param array $options - options to use
343 340 * @param string $server - the server to process with
344 341 *
345 - * @return boolean - Status of the task
342 + * @return bool | WP_Error - Status of the task
346 343 */
347 344 public function compress_single_image($image, $options, $server) {
348 345 $task_name = $this->get_associated_task($server);
349 346 $blog_info = is_multisite() ? ', blog ID : '.get_current_blog_id() : '';
350 - $description = "$task_name - attachment ID : ". $image . $blog_info. ", started on : ". date("F d, Y h:i:s", time());
347 + $description = "$task_name - attachment ID : ". $image . $blog_info. ", started on : ". gmdate("F d, Y h:i:s", time());
351 348
352 349 $task = call_user_func(array($task_name, 'create_task'), 'smush', $description, $options, $task_name);
353 350 if ($task) $this->set_task_logger($task);
354 351 $this->clear_cached_data();
@@ -370,9 +367,9 @@
370 367 */
371 368 public function restore_single_image($image_id, $blog_id) {
372 369
373 370 $switched_blog = false;
374 - if (is_multisite() && current_user_can('manage_network_options')) {
371 + if (is_multisite() && WP_Optimize()->current_user_can('manage_network_options')) {
375 372 switch_to_blog($blog_id);
376 373 $switched_blog = true;
377 374 } elseif (is_multisite() && get_current_blog_id() != $blog_id) {
378 375 return new WP_Error('restore_backup_wrong_blog_id', __('The blog ID provided does not match the current blog.', 'wp-optimize'));
@@ -380,15 +377,23 @@
380 377
381 378 $error = false;
382 379
383 380 $image_path = get_attached_file($image_id);
384 - $backup_path = get_post_meta($image_id, 'original-file', true);
385 -
381 + $backup_path = get_post_meta($image_id, '_wpo-original-file', true);
382 + $uploads_dir = wp_upload_dir();
383 + $uploads_basedir = realpath($uploads_dir['basedir']);
384 +
385 + if (false === $uploads_basedir) {
386 + if ($switched_blog) {
387 + restore_current_blog();
388 + }
389 + return new WP_Error('restore_backup_issue', __('The uploads base directory is not correct.', 'wp-optimize'));
390 + }
391 +
392 + $uploads_basedir = trailingslashit($uploads_basedir);
393 +
386 394 // If the file doesn't exist, check if it's relative
387 395 if (!is_file($backup_path)) {
388 - $uploads_dir = wp_upload_dir();
389 - $uploads_basedir = trailingslashit($uploads_dir['basedir']);
390 -
391 396 if (is_file($uploads_basedir . $backup_path)) {
392 397 $backup_path = $uploads_basedir . $backup_path;
393 398 }
394 399 }
@@ -417,17 +422,27 @@
417 422 $backup_path = $uploads_basedir . $backup_path;
418 423 }
419 424 }
420 425
426 + $backup_path = realpath($backup_path);
427 + if (!$backup_path || 0 !== strpos(trailingslashit(dirname($backup_path)), $uploads_basedir)) {
428 + if ($switched_blog) {
429 + restore_current_blog();
430 + }
431 + return new WP_Error('restore_failed', __('The backup file path seems suspicious, and could not be deleted.', 'wp-optimize'));
432 + }
433 +
434 +
421 435 if (!is_file($backup_path)) {
422 436 // Delete information about backup.
423 - delete_post_meta($image_id, 'original-file');
437 + delete_post_meta($image_id, '_wpo-original-file');
424 438 $error = new WP_Error('restore_backup_not_found', __('The backup was not found; it may have been deleted or was already restored', 'wp-optimize'));
425 - } elseif (!is_writable($image_path)) {
426 - $error = new WP_Error('restore_failed', __('The destination could not be written to.', 'wp-optimize').' '.__("Please check your folder's permissions", 'wp-optimize'));
439 + } elseif (!wp_is_writable($image_path)) {
440 + $error = new WP_Error('restore_failed', __('The destination could not be written to.', 'wp-optimize').' '.__("Please check your folder's permissions", 'wp-optimize'));
427 441 } elseif (!copy($backup_path, $image_path)) {
428 - $error = new WP_Error('restore_failed', __('The file could not be copied; check your PHP error logs for details', 'wp-optimize'));
429 - } elseif (!unlink($backup_path)) {
442 + $error = new WP_Error('restore_failed', __('The file could not be copied; check your PHP error logs for details', 'wp-optimize'));
443 + } elseif (!WP_Optimize_Utils::wp_delete_file($backup_path)) {
444 + // translators: %s is the backup file path
430 445 $error = new WP_Error('restore_failed', sprintf(__('The backup file %s could not be deleted.', 'wp-optimize'), $backup_path));
431 446 }
432 447
433 448 if (!$error) {
@@ -432,12 +447,12 @@
432 447
433 448 if (!$error) {
434 449 // if backup image deleted successfully
435 450 // then delete from attachment meta associated smush data
436 - delete_post_meta($image_id, 'smush-complete');
437 - delete_post_meta($image_id, 'smush-stats');
438 - delete_post_meta($image_id, 'original-file');
439 - delete_post_meta($image_id, 'smush-info');
451 + delete_post_meta($image_id, '_wpo-smush-complete');
452 + delete_post_meta($image_id, '_wpo-smush-stats');
453 + delete_post_meta($image_id, '_wpo-original-file');
454 + delete_post_meta($image_id, '_wpo-smush-info');
440 455 }
441 456
442 457 if ($switched_blog) {
443 458 restore_current_blog();
@@ -459,9 +474,9 @@
459 474 *
460 475 * @param bool $restore_backup if true then restore images from backup otherwise just delete meta.
461 476 * @param int $blog_id blog id.
462 477 * @param int $images_limit how many images process per time.
463 - * @param bool $delete_only_backups_meta meta fields will deleted only for images those will restored from backup.
478 + * @param bool $delete_only_backups_meta meta fields will be deleted only for images those will be restored from backup.
464 479 *
465 480 * @return array ['completed' => (bool), 'message' => (string), 'error' => (string)]
466 481 */
467 482 public function bulk_restore_compressed_images($restore_backup, $blog_id = 1, $images_limit = 100, $delete_only_backups_meta = false) {
@@ -480,9 +495,9 @@
480 495 $processed = 0;
481 496
482 497 if ($restore_backup) {
483 498 // get post ids those have backup meta field.
484 - $image_ids = $wpdb->get_results($wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'original-file' LIMIT %d;", $images_limit), ARRAY_A);
499 + $image_ids = $wpdb->get_results($wpdb->prepare("SELECT post_id FROM `{$wpdb->postmeta}` WHERE meta_key = '_wpo-original-file' LIMIT %d;", $images_limit), ARRAY_A);
485 500
486 501 if (!empty($image_ids)) {
487 502 // run restore function for each found image.
488 503 foreach ($image_ids as $image) {
@@ -487,9 +502,9 @@
487 502 // run restore function for each found image.
488 503 foreach ($image_ids as $image) {
489 504 $restore_result = $this->restore_single_image($image['post_id'], $blog_id);
490 505
491 - // if we get an error then we stop the work, except situation when "backup already restored'.
506 + // if we get an error then we stop the work, except situation when "backup already restored".
492 507 if (is_wp_error($restore_result) && 'restore_backup_not_found' != $restore_result->get_error_code()) {
493 508 // we need to stop the work as we haven't restored the backup.
494 509 $result['error'] = $restore_result->get_error_message();
495 510 $this->options->delete_option('smush_images_restored');
@@ -502,9 +517,9 @@
502 517
503 518 $images_count = count($image_ids);
504 519
505 520 // if all images processed then set flag completed to true.
506 - if ($processed == $images_count && $images_count < $images_limit) {
521 + if ($processed === $images_count && $images_count < $images_limit) {
507 522 $this->options->delete_option('smush_images_restored');
508 523 $result['completed'] = true;
509 524 } else {
510 525 // save into options total processed count.
@@ -511,10 +526,12 @@
511 526 $processed += $this->options->get_option('smush_images_restored', 0);
512 527 $this->options->update_option('smush_images_restored', $processed);
513 528
514 529 if (is_multisite()) {
515 - $result['message'] = sprintf(__('%s compressed images were restored from their backup for the site %s', 'wp-optimize'), $processed, get_site_url($blog_id));
530 + // translators: %1$s is the number of restored images, %2$s is the site url.
531 + $result['message'] = sprintf(__('%1$s compressed images were restored from their backup for the site %2$s', 'wp-optimize'), $processed, get_site_url($blog_id));
516 532 } else {
533 + // translators: %s is the number of restored images.
517 534 $result['message'] = sprintf(__('%s compressed images were restored from their backup', 'wp-optimize'), $processed);
518 535 }
519 536 }
520 537
@@ -524,22 +541,26 @@
524 541 }
525 542
526 543 if ($result['completed']) {
527 544
528 - $smushed_images_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key='smush-complete' AND meta_value=1");
545 + $smushed_images_count = $wpdb->get_var("SELECT COUNT(*) FROM `{$wpdb->postmeta}` WHERE meta_key='_wpo-smush-complete' AND meta_value=1");
529 546 $result['smushed_images_count'] = $smushed_images_count;
530 547
531 548 if ($delete_only_backups_meta) {
532 549 if (is_multisite()) {
533 550 if ($smushed_images_count > 0) {
551 + // translators: %s is the site url
534 552 $result['message'] = sprintf(__('All the compressed images for site %s with backup copies of their original files were successfully restored.', 'wp-optimize'), get_site_url($blog_id));
553 + // translators: %s is the number of images
535 554 $result['message'] .= ' '.sprintf(_n('Unable to restore %s image without backup files.', 'Unable to restore %s images without backup files.', $smushed_images_count, 'wp-optimize'), $smushed_images_count);
536 555 } else {
556 + // translators: %s is the site url
537 557 $result['message'] = sprintf(__('All the compressed images for the site %s were successfully restored.', 'wp-optimize'), get_site_url($blog_id));
538 558 }
539 559 } else {
540 560 if ($smushed_images_count > 0) {
541 561 $result['message'] = __('All the compressed images with backup copies of their original files were successfully restored.', 'wp-optimize');
562 + // translators: %s is the number of images
542 563 $result['message'] .= ' '.sprintf(_n('Unable to restore %s image without backup files.', 'Unable to restore %s images without backup files.', $smushed_images_count, 'wp-optimize'), $smushed_images_count);
543 564 } else {
544 565 $result['message'] = __('All the compressed images were successfully restored.', 'wp-optimize');
545 566 }
@@ -545,8 +566,9 @@
545 566 }
546 567 }
547 568 } else {
548 569 if (is_multisite()) {
570 + // translators: %s is the site url
549 571 $result['message'] = sprintf(__('All the compressed images for the site %s were successfully marked as uncompressed.', 'wp-optimize'), get_site_url($blog_id));
550 572 } else {
551 573 $result['message'] = __('All the compressed images were successfully marked as uncompressed.', 'wp-optimize');
552 574 }
@@ -553,11 +575,11 @@
553 575 }
554 576
555 577 // clear all metas for smushed images after work completed.
556 578 // if $delete_only_backup_meta set to true then all meta fields was deleted in restore_single_image()
557 - // and we don't need delete metas for other images.
579 + // and we don't need to delete metas for other images.
558 580 if (!$delete_only_backups_meta) {
559 - $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key IN ('smush-complete', 'smush-stats', 'original-file', 'smush-info');");
581 + $wpdb->query("DELETE FROM `{$wpdb->postmeta}` WHERE meta_key IN ('_wpo-smush-complete', '_wpo-smush-stats', '_wpo-original-file', '_wpo-smush-info');");
560 582 }
561 583 }
562 584
563 585 if (is_multisite()) {
@@ -588,28 +610,20 @@
588 610 'blog_id' => $task->get_option('blog_id')
589 611 );
590 612 }
591 613 }
592 -
614 + $default_task_options = $this->get_smush_options();
593 615 foreach ($images as $image) {
594 616 // Skip if already in the queue
595 617 if (in_array($image, $queued_images)) continue;
596 618
597 - $options = array(
598 - 'attachment_id' => intval($image['attachment_id']),
599 - 'blog_id' => intval($image['blog_id']),
600 - 'image_quality' => $this->options->get_option('image_quality', 92),
601 - 'keep_original' => $this->options->get_option('back_up_original', true),
602 - 'preserve_exif' => $this->options->get_option('preserve_exif', true),
603 - 'lossy_compression' => $this->options->get_option('lossy_compression', false)
604 - );
605 -
619 + $task_options = array_merge($default_task_options, array('attachment_id' => intval($image['attachment_id']), 'blog_id' => intval($image['blog_id'])));
606 620 $server = $this->options->get_option('compression_server', $this->webservice);
607 621 $task_name = $this->get_associated_task($server);
608 622
609 623 $blog_info = is_multisite() ? ', Blog ID : '.intval($image['blog_id']) : '';
610 - $description = "$task_name - Attachment ID : ". intval($image['attachment_id']) . $blog_info . ", Started on : ". date("F d, Y h:i:s", time());
611 - $task = call_user_func(array($task_name, 'create_task'), 'smush', $description, $options, $task_name);
624 + $description = "$task_name - Attachment ID : ". intval($image['attachment_id']) . $blog_info . ", Started on : ". gmdate("F d, Y h:i:s", time());
625 + $task = call_user_func(array($task_name, 'create_task'), 'smush', $description, $task_options, $task_name);
612 626 if ($task) $this->set_task_logger($task);
613 627 }
614 628
615 629 $this->process_smush_tasks();
@@ -662,19 +676,19 @@
662 676 */
663 677 public function record_stats($task) {
664 678
665 679 $attachment_id = $task->get_option('attachment_id');
666 - $completed_task_count = $this->options->get_option('completed_task_count', false);
680 + $completed_task_count = $this->options->get_option('completed_task_count');
667 681 $failed_task_count = $this->options->get_option('failed_task_count', 0);
668 - $total_bytes_saved = $this->options->get_option('total_bytes_saved', false);
682 + $total_bytes_saved = $this->options->get_option('total_bytes_saved');
669 683 $total_percent_saved = $this->options->get_option('total_percent_saved', 0);
670 684
671 - if ('ud_task_failed' == current_action()) {
685 + if ('ud_task_failed' === current_action()) {
672 686 $this->options->update_option('failed_task_count', ++$failed_task_count);
673 687 return;
674 688 }
675 689
676 - if (false === $completed_task_count) {
690 + if (empty($completed_task_count)) {
677 691 $completed_task_count = $total_bytes_saved = 0;
678 692 }
679 693
680 694 if (!$total_bytes_saved) {
@@ -682,12 +696,12 @@
682 696 }
683 697
684 698 if (is_multisite()) {
685 699 switch_to_blog($task->get_option('blog_id', 1));
686 - $stats = get_post_meta($attachment_id, 'smush-stats', true);
700 + $stats = get_post_meta($attachment_id, '_wpo-smush-stats', true);
687 701 restore_current_blog();
688 702 } else {
689 - $stats = get_post_meta($attachment_id, 'smush-stats', true);
703 + $stats = get_post_meta($attachment_id, '_wpo-smush-stats', true);
690 704 }
691 705
692 706 if (isset($stats['sizes-info'])) {
693 707
@@ -700,11 +714,11 @@
700 714 }
701 715
702 716 $percent = round((($original_size - $compressed_size) / $original_size * 100), 2);
703 717 } else {
704 - $original_size = isset($stats['original-size']) ? $stats['original-size'] : 0;
705 - $compressed_size = isset($stats['smushed-size']) ? $stats['smushed-size'] : 0;
706 - $percent = isset($stats['savings-percent']) ? $stats['savings-percent'] : 0;
718 + $original_size = $stats['original-size'] ?? 0;
719 + $compressed_size = $stats['smushed-size'] ?? 0;
720 + $percent = $stats['savings-percent'] ?? 0;
707 721 }
708 722
709 723 $saved = $original_size - $compressed_size;
710 724 $completed_task_count++;
@@ -727,16 +741,17 @@
727 741 if (empty($smush_options)) {
728 742 $smush_options = array(
729 743 'compression_server' => $this->options->get_option('compression_server', $this->get_default_webservice()),
730 744 'image_quality' => $this->options->get_option('image_quality', 92),
731 - 'lossy_compression' => $this->options->get_option('lossy_compression', false),
745 + 'lossy_compression' => $this->options->get_option('lossy_compression'),
746 + 'keep_original' => $this->options->get_option('back_up_original', true),//repeated below
732 747 'back_up_original' => $this->options->get_option('back_up_original', true),
733 748 'back_up_delete_after' => $this->options->get_option('back_up_delete_after', true),
734 749 'back_up_delete_after_days' => $this->options->get_option('back_up_delete_after_days', 50),
735 750 'preserve_exif' => $this->options->get_option('preserve_exif', false),
736 - 'autosmush' => $this->options->get_option('autosmush', false),
737 - 'show_smush_metabox' => $this->options->get_option('show_smush_metabox', 'show') == 'show' ? true : false,
738 - 'webp_conversion' => $this->options->get_option('webp_conversion', false)
751 + 'autosmush' => $this->options->get_option('autosmush'),
752 + 'show_smush_metabox' => $this->options->get_option('show_smush_metabox', 'show') === 'show',
753 + 'webp_conversion' => $this->options->get_option('webp_conversion')
739 754 );
740 755 }
741 756 return $smush_options;
742 757 }
@@ -741,20 +756,29 @@
741 756 return $smush_options;
742 757 }
743 758
744 759 /**
745 - * Updates global smush options
760 + * Update smush options
761 + * Only options whose values differ from the stored values are updated.
746 762 *
747 - * @param array $options - sent in via AJAX
748 - * @return bool - status of the update
763 + * @param array $options Associative array of option names and values sent in via AJAX.
764 + * @return bool True if all updates succeeded or no changes were required,
765 + * false if at least one option update failed.
749 766 */
750 767 public function update_smush_options($options) {
751 -
768 + $success = true;
752 769 foreach ($options as $option => $value) {
753 - $this->options->update_option($option, $value);
770 + // Here we only store string, array as string after serialization, boolean, and integer values which will be stored as strings (LONGTEXT field type)
771 + // So loose comparison is fine, strict comparison results to buggy behavior
772 + if ($this->options->get_option($option) == $value) {
773 + continue;
774 + }
775 +
776 + if (!$this->options->update_option($option, $value)) {
777 + $success = false;
778 + }
754 779 }
755 -
756 - return true;
780 + return $success;
757 781 }
758 782
759 783 /**
760 784 * Clears smush related stats
@@ -786,10 +810,12 @@
786 810 'server_check' => __('Connecting to the Smush API server, please wait', 'wp-optimize'),
787 811 'please_wait' => __('Please wait while the request is being processed', 'wp-optimize'),
788 812 'server_error' => __('There was an error connecting to the image compression server.', 'wp-optimize') .
789 813 '<br>' . __('This could mean either the server is temporarily unavailable or there are connectivity issues with your internet connection.', 'wp-optimize') . ' ' .
814 + // translators: %s is a link
790 815 '<i>' . sprintf(__('(Also ensure IPs listed at the bottom of this %s page are whitelisted by your webserver).', 'wp-optimize'), $resmushit_article_link) . '</i>' .
791 816 '<br>' . __('Please try later.', 'wp-optimize'),
817 + 'exceeded_max_filesize' => __('This image is too large to be optimized — it exceeds the provider\'s size limit', 'wp-optimize'),
792 818 'please_select_images' => __('Please select the images you want compressed from the "Uncompressed images" panel first', 'wp-optimize'),
793 819 'please_updating_images_info' => __('Please wait: updating information about the selected image.', 'wp-optimize'),
794 820 'please_select_compressed_images' => __('Please select the images you want to mark as already compressed from the "Uncompressed images" panel first', 'wp-optimize'),
795 821 'view_image' => __('View Image', 'wp-optimize'),
@@ -831,14 +857,14 @@
831 857 * @param WP_Post $post - a post object
832 858 */
833 859 public function render_smush_metabox($post) {
834 860
835 - $compressed = get_post_meta($post->ID, 'smush-complete', true) ? true : false;
836 - $has_backup = get_post_meta($post->ID, 'original-file', true) ? true : false;
861 + $compressed = (bool) get_post_meta($post->ID, '_wpo-smush-complete', true);
862 + $has_backup = (bool) get_post_meta($post->ID, '_wpo-original-file', true);
837 863
838 - $smush_info = get_post_meta($post->ID, 'smush-info', true);
839 - $smush_stats = get_post_meta($post->ID, 'smush-stats', true);
840 - $marked = get_post_meta($post->ID, 'smush-marked', false);
864 + $smush_info = get_post_meta($post->ID, '_wpo-smush-info', true);
865 + $smush_stats = get_post_meta($post->ID, '_wpo-smush-stats', true);
866 + $marked = get_post_meta($post->ID, '_wpo-smush-marked');
841 867
842 868 $options = Updraft_Smush_Manager()->get_smush_options();
843 869
844 870 $file = get_attached_file($post->ID);
@@ -852,9 +878,9 @@
852 878 'restore_display' => $compressed ? "display:block;" : "display:none;",
853 879 'restore_action' => $has_backup ? "display:block;" : "display:none;",
854 880 'smush_mark' => !$compressed && !$marked ? "display:block;" : "display:none;",
855 881 'smush_unmark' => $marked ? "display:block;" : "display:none;",
856 - 'smush_info' => $smush_info ? $smush_info : ' ',
882 + 'smush_info' => $smush_info ?: ' ',
857 883 'file_size' => $file_size,
858 884 'smush_options' => $options,
859 885 'custom' => 90 >= $options['image_quality'] && 65 <= $options['image_quality'],
860 886 'smush_details' => '',
@@ -870,14 +896,14 @@
870 896 $extract['compressed_by_another_plugin'] = $this->is_image_compressed_by_another_plugin($post->ID);
871 897 if (WPO_Image_Utils::is_supported_extension($ext, $allowed_extensions)) {
872 898 WP_Optimize()->include_template('admin-metabox-smush.php', false, $extract);
873 899 } else {
874 - printf("<p>%s</p>", __('Compressing this file type extension is not supported', 'wp-optimize'));
900 + printf("<p>%s</p>", esc_html__('Compressing this file type extension is not supported', 'wp-optimize'));
875 901 }
876 902 }
877 903
878 904 /**
879 - * Get text for restrore image tooltip.
905 + * Get text for restore image tooltip.
880 906 *
881 907 * @return string
882 908 */
883 909 private function get_restore_image_tooltip_text() {
@@ -895,10 +921,11 @@
895 921 * @return bool
896 922 */
897 923 private function is_image_compressed_by_another_plugin($image_id) {
898 924 global $wpdb;
925 + static $is_ewwwio_images_table_exists = null;
899 926
900 - $meta = $wpdb->get_results("SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE `post_id`={$image_id}", ARRAY_A);
927 + $meta = $wpdb->get_results($wpdb->prepare("SELECT meta_key, meta_value FROM `{$wpdb->postmeta}` WHERE `post_id`=%d", $image_id), ARRAY_A);
901 928
902 929 if (is_array($meta)) {
903 930 foreach ($meta as $row) {
904 931 // Smush, Imagify, Compress JPEG & PNG images by TinyPNG.
@@ -903,16 +930,18 @@
903 930 foreach ($meta as $row) {
904 931 // Smush, Imagify, Compress JPEG & PNG images by TinyPNG.
905 932 if (in_array($row['meta_key'], array('wp-smpro-smush-data', '_imagify_optimization_level', 'tiny_compress_images'))) return true;
906 933 // ShortPixel Image Optimizer
907 - if ('_shortpixel_status' == $row['meta_key'] && 2 <= $row['meta_key'] && 3 > $row['meta_key']) return true;
934 + if ('_shortpixel_status' === $row['meta_key'] && 2 <= (int) $row['meta_value'] && 3 > (int) $row['meta_value']) return true;
908 935 }
909 936 }
910 937
911 - if (WP_Optimize()->get_db_info()->table_exists('ewwwio_images')) {
938 + $is_ewwwio_images_table_exists = is_null($is_ewwwio_images_table_exists) ? WP_Optimize()->get_db_info()->table_exists('ewwwio_images') : $is_ewwwio_images_table_exists;
939 +
940 + if ($is_ewwwio_images_table_exists) {
912 941 $old_show_errors = $wpdb->show_errors(false);
913 942 // EWWW Image Optimizer.
914 - $ewww_image = $wpdb->get_col("SELECT attachment_id FROM {$wpdb->prefix}ewwwio_images WHERE attachment_id={$image_id} AND gallery='media' LIMIT 1");
943 + $ewww_image = $wpdb->get_col($wpdb->prepare("SELECT attachment_id FROM `{$wpdb->prefix}ewwwio_images` WHERE attachment_id=%d AND gallery='media' LIMIT 1", $image_id));
915 944 if (!empty($ewww_image)) return true;
916 945 $wpdb->show_errors($old_show_errors);
917 946 }
918 947
@@ -931,15 +960,15 @@
931 960
932 961 if (!WP_Optimize()->get_db_info()->table_exists('ewwwio_images')) return $args;
933 962
934 963 $old_show_errors = $wpdb->show_errors(false);
935 - $compressed_images = $wpdb->get_col("SELECT DISTINCT(attachment_id) FROM {$wpdb->prefix}ewwwio_images WHERE gallery='media'");
964 + $compressed_images = $wpdb->get_col("SELECT DISTINCT(attachment_id) FROM `{$wpdb->prefix}ewwwio_images` WHERE gallery='media'");
936 965 $wpdb->show_errors($old_show_errors);
937 966
938 967 if (isset($args['post__not_in'])) {
939 - $args['post__not_in'] = array_merge($args['post__not_in'], $compressed_images);
968 + $args['post__not_in'] = array_merge($args['post__not_in'], $compressed_images); // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_post__not_in -- is necessary and used with caution
940 969 } else {
941 - $args['post__not_in'] = $compressed_images;
970 + $args['post__not_in'] = $compressed_images; // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_post__not_in -- is necessary and used with caution
942 971 }
943 972
944 973 return $args;
945 974 }
@@ -950,11 +979,11 @@
950 979 * @param string $use_cache
951 980 * @return array - uncompressed images
952 981 */
953 982 public function get_uncompressed_images($use_cache = "true") {
954 - if ("true" == $use_cache) {
983 + if ("true" === $use_cache) {
955 984 $uncompressed_images = $this->get_from_cache('uncompressed_images');
956 - if ($uncompressed_images) return $uncompressed_images;
985 + if ($uncompressed_images && is_array($uncompressed_images)) return $uncompressed_images;
957 986 }
958 987
959 988 $uncompressed_images = array();
960 989 $accepted_mimes = array('image/jpeg', 'image/gif', 'image/png');
@@ -995,12 +1024,12 @@
995 1024 'thumb_url' => wp_get_attachment_thumb_url($image_id),
996 1025 'filesize' => filesize(get_attached_file($image_id))
997 1026 );
998 1027 } else {
999 - $this->log("Blog_id={$site->blog_id}, ID={$image_id}, File={$file} This image type is not supported.");
1028 + $this->log("Blog_id=$site->blog_id, ID=$image_id, File=$file This image type is not supported.");
1000 1029 }
1001 1030 } else {
1002 - $this->log("Could not find file for image: blog_id={$site->blog_id}, ID={$image_id}, file={$file}");
1031 + $this->log("Could not find file for image: blog_id=$site->blog_id, ID=$image_id, file=$file");
1003 1032 }
1004 1033 }
1005 1034
1006 1035 restore_current_blog();
@@ -1023,12 +1052,12 @@
1023 1052 'thumb_url' => wp_get_attachment_thumb_url($image_id),
1024 1053 'filesize' => filesize(get_attached_file($image_id))
1025 1054 );
1026 1055 } else {
1027 - $this->log("Image ID={$image_id}, File={$file} This image type is not supported.");
1056 + $this->log("Image ID=$image_id, File=$file This image type is not supported.");
1028 1057 }
1029 1058 } else {
1030 - $this->log("Could not find file for image: ID={$image_id}, file={$file}");
1059 + $this->log("Could not find file for image: ID=$image_id, file=$file");
1031 1060 }
1032 1061 }
1033 1062 }
1034 1063
@@ -1103,13 +1132,13 @@
1103 1132 $stats = array();
1104 1133
1105 1134 foreach ($images as $image) {
1106 1135 if (is_multisite()) {
1107 - switch_to_blog($image['blog_id'], 1);
1108 - $stats[] = get_post_meta($image['attachment_id'], 'smush-complete', true) ? 'success' : 'fail';
1136 + switch_to_blog($image['blog_id']);
1137 + $stats[] = get_post_meta($image['attachment_id'], '_wpo-smush-complete', true) ? 'success' : 'fail';
1109 1138 restore_current_blog();
1110 1139 } else {
1111 - $stats[] = get_post_meta($image['attachment_id'], 'smush-complete', true) ? 'success' : 'fail';
1140 + $stats[] = get_post_meta($image['attachment_id'], '_wpo-smush-complete', true) ? 'success' : 'fail';
1112 1141 }
1113 1142 }
1114 1143
1115 1144 return array_count_values($stats);
@@ -1117,9 +1146,9 @@
1117 1146
1118 1147 /**
1119 1148 * Returns a list of images for smush (from cache if available)
1120 1149 *
1121 - * @return array - List of task objects with uncompressed images
1150 + * @return array|mixed - List of task objects with uncompressed images
1122 1151 */
1123 1152 public function get_pending_tasks() {
1124 1153 return $this->get_active_tasks('smush');
1125 1154 }
@@ -1125,8 +1154,10 @@
1125 1154 }
1126 1155
1127 1156 /**
1128 1157 * Deletes and removes any pending tasks from queue
1158 + *
1159 + * @return bool
1129 1160 */
1130 1161 public function clear_pending_images() {
1131 1162
1132 1163 $pending_tasks = $this->get_active_tasks('smush');
@@ -1175,9 +1206,9 @@
1175 1206 $js_variables['cancel'] = esc_html__('Cancel', 'wp-optimize');
1176 1207 $js_variables['cancelling'] = esc_html__('Cancelling...', 'wp-optimize');
1177 1208 $js_variables['images_restored_successfully'] = esc_html__('The images were restored successfully', 'wp-optimize');
1178 1209 $js_variables['logo_src'] = esc_url(WPO_PLUGIN_URL.'images/notices/wp_optimize_logo.png');
1179 -
1210 +
1180 1211 wp_enqueue_script('block-ui-js', WPO_PLUGIN_URL.'includes/blockui/jquery.blockUI'.$min_or_not.'.js', array('jquery'), $enqueue_version);
1181 1212 wp_enqueue_script('wp-optimize-heartbeat-js', WPO_PLUGIN_URL.'js/heartbeat'.$min_or_not_internal.'.js', array('jquery'), $enqueue_version);
1182 1213 wp_localize_script('wp-optimize-heartbeat-js', 'wpo_heartbeat_ajax', array(
1183 1214 'ajaxurl' => admin_url('admin-ajax.php'),
@@ -1236,9 +1267,9 @@
1236 1267
1237 1268 /**
1238 1269 * Gets allowed service providers for smush
1239 1270 *
1240 - * @return array - key value pair of service name => task name
1271 + * @return array - A pair of key/value. e.g. service name => task name
1241 1272 */
1242 1273 public function get_allowed_services() {
1243 1274 return array(
1244 1275 'resmushit' => 'Re_Smush_It_Task',
@@ -1245,11 +1276,32 @@
1245 1276 );
1246 1277 }
1247 1278
1248 1279 /**
1280 + * Gets current compression server hint.
1281 + *
1282 + * @return string
1283 + */
1284 + public function get_compression_server_hint() {
1285 +
1286 + switch ($this->webservice) {
1287 + case 'resmushit':
1288 + $title = 'reSmush.it';
1289 + break;
1290 + default:
1291 + $title = $this->webservice;
1292 + }
1293 +
1294 + // translators: %s is a service used to compress images
1295 + $hint = sprintf(__('Service is provided by %s', 'wp-optimize'), $title);
1296 +
1297 + return $hint;
1298 + }
1299 +
1300 + /**
1249 1301 * Gets allowed service provider features smush
1250 1302 *
1251 - * @return array - key value pair of service name => features exposed
1303 + * @return array - A pair of key/value. e.g. service name => features exposed
1252 1304 */
1253 1305 public function get_features() {
1254 1306 $features = array();
1255 1307 foreach ($this->get_allowed_services() as $service => $class_name) {
@@ -1278,9 +1330,9 @@
1278 1330
1279 1331 /**
1280 1332 * Adds a logger to the task
1281 1333 *
1282 - * @param Mixed $task - a task object
1334 + * @param mixed $task - a task object
1283 1335 */
1284 1336 public function set_task_logger($task) {
1285 1337 if (!$this->logger) {
1286 1338 $this->logger = new Updraft_File_Logger($this->get_logfile_path());
@@ -1313,9 +1365,9 @@
1313 1365 $log_header = array();
1314 1366
1315 1367 // phpcs:enable
1316 1368 $log_header[] = "\n";
1317 - $log_header[] = "Header for logs at time: ".date('r')." on ".network_site_url();
1369 + $log_header[] = "Header for logs at time: ".gmdate('r')." on ".network_site_url();
1318 1370 $log_header[] = "WP: ".$wp_version;
1319 1371 $php_uname = '';
1320 1372 if (function_exists('php_uname')) {
1321 1373 $php_uname = ", " . php_uname();
@@ -1322,9 +1374,9 @@
1322 1374 }
1323 1375 $log_header[] = "PHP: ".phpversion()." (".PHP_SAPI.$php_uname.")";
1324 1376 $log_header[] = "MySQL: $mysql_version";
1325 1377 $log_header[] = "WPLANG: ".get_locale();
1326 - $log_header[] = "Server: ".$_SERVER["SERVER_SOFTWARE"];
1378 + $log_header[] = "Server: ". TeamUpdraft\WP_Optimize\Includes\Fragments\fetch_superglobal('server', 'SERVER_SOFTWARE', 'string', 'sanitize_text_field', '-');
1327 1379 $log_header[] = "Outbound connections: ".(defined('WP_HTTP_BLOCK_EXTERNAL') ? 'Y' : 'N');
1328 1380 $log_header[] = "Disabled Functions: $disabled_functions";
1329 1381 $log_header[] = "max_execution_time: $max_execution_time";
1330 1382 $log_header[] = "memory_limit: $memory_limit (used: {$memory_usage}M | {$total_memory_usage}M)";
@@ -1336,12 +1388,12 @@
1336 1388 $this->log($log_entry);
1337 1389 }
1338 1390 }
1339 1391
1340 - $memlim = $this->memory_check_current();
1392 + $memory_limit = $this->memory_check_current();
1341 1393
1342 - if ($memlim<65 && $memlim>0) {
1343 - $this->log(sprintf('The amount of memory (RAM) allowed for PHP is very low (%s Mb) - you should increase it to avoid failures due to insufficient memory (consult your web hosting company for more help)', round($memlim, 1)), 'warning');
1394 + if ($memory_limit<65 && $memory_limit>0) {
1395 + $this->log(sprintf('The amount of memory (RAM) allowed for PHP is very low (%s Mb) - you should increase it to avoid failures due to insufficient memory (consult your web hosting company for more help)', round($memory_limit, 1)), 'warning');
1344 1396 }
1345 1397
1346 1398 if ($max_execution_time>0 && $max_execution_time<20) {
1347 1399 $this->log(sprintf('The amount of time allowed for WordPress plugins to run is very low (%s seconds) - you should increase it to avoid failures due to time-outs (consult your web hosting company for more help - it is the max_execution_time PHP setting; the recommended value is %s seconds or more)', $max_execution_time, 90), 'warning');
@@ -1358,9 +1410,9 @@
1358 1410
1359 1411 /**
1360 1412 * Get the WordPress version
1361 1413 *
1362 - * @return String - the version
1414 + * @return string - the version
1363 1415 */
1364 1416 public function get_wordpress_version() {
1365 1417 static $got_wp_version = false;
1366 1418
@@ -1365,9 +1417,9 @@
1365 1417 static $got_wp_version = false;
1366 1418
1367 1419 if (!$got_wp_version) {
1368 1420 global $wp_version;
1369 - @include(ABSPATH.WPINC.'/version.php');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- suppress warning if `version.php` does not exists
1421 + @include(ABSPATH.WPINC.'/version.php');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- suppress warning if `version.php` does not exist
1370 1422 $got_wp_version = $wp_version;
1371 1423 }
1372 1424
1373 1425 return $got_wp_version;
@@ -1375,16 +1427,18 @@
1375 1427
1376 1428 /**
1377 1429 * Get the current memory limit
1378 1430 *
1379 - * @return String - memory limit in megabytes
1431 + * @param ?string $memory_limit Memory limit in megabytes
1432 + *
1433 + * @return string - memory limit in megabytes
1380 1434 */
1381 - public function memory_check_current($memory_limit = false) {
1435 + public function memory_check_current($memory_limit = null) {
1382 1436 // Returns in megabytes
1383 - if (false == $memory_limit) $memory_limit = ini_get('memory_limit');
1437 + if (empty($memory_limit)) $memory_limit = ini_get('memory_limit');
1384 1438 $memory_limit = rtrim($memory_limit);
1385 1439 $memory_unit = $memory_limit[strlen($memory_limit)-1];
1386 - if (0 == (int) $memory_unit && '0' !== $memory_unit) {
1440 + if (0 === (int) $memory_unit && '0' !== $memory_unit) {
1387 1441 $memory_limit = substr($memory_limit, 0, strlen($memory_limit)-1);
1388 1442 } else {
1389 1443 $memory_unit = '';
1390 1444 }
@@ -1467,11 +1521,11 @@
1467 1521 global $wpdb;
1468 1522
1469 1523 // get list of cached data by optimization.
1470 1524 if ($this->is_multisite_mode()) {
1471 - $keys = $wpdb->get_col("SELECT meta_key FROM {$wpdb->sitemeta} WHERE meta_key LIKE '%wpo_smush_cache_%'");
1525 + $keys = $wpdb->get_col("SELECT meta_key FROM `{$wpdb->sitemeta}` WHERE meta_key LIKE '%wpo_smush_cache_%'");
1472 1526 } else {
1473 - $keys = $wpdb->get_col("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '%wpo_smush_cache_%'");
1527 + $keys = $wpdb->get_col("SELECT option_name FROM `{$wpdb->options}` WHERE option_name LIKE '%wpo_smush_cache_%'");
1474 1528 }
1475 1529
1476 1530 if (!empty($keys)) {
1477 1531 $transient_keys = array();
@@ -1511,19 +1565,19 @@
1511 1565 $year = (int) $match[1];
1512 1566 $month = (int) $match[2];
1513 1567
1514 1568 $limit = strtotime('-'.$days_ago.' '.(($days_ago > 1) ? 'days' : 'day'));
1515 - $year_limit = (int) date('Y', $limit);
1516 - $month_limit = (int) date('m', $limit);
1517 - $day_limit = (int) date('j', $limit);
1569 + $year_limit = (int) gmdate('Y', $limit);
1570 + $month_limit = (int) gmdate('m', $limit);
1571 + $day_limit = (int) gmdate('j', $limit);
1518 1572
1519 1573 // if current directory is newer than needed then we skip it.
1520 - if ($year_limit < $year || ($year_limit == $year && $month_limit < $month)) {
1574 + if ($year_limit < $year || ($year_limit === $year && $month_limit < $month)) {
1521 1575 return;
1522 1576 }
1523 1577
1524 1578 // we will check dates only in directory that contain limit date.
1525 - $check_date = ($year_limit == $year && $month_limit == $month);
1579 + $check_date = ($year_limit === $year && $month_limit === $month);
1526 1580 }
1527 1581
1528 1582 // GLOB_BRACE isn't defined on some systems (Solaris, SunOS and more) > https://www.php.net/manual/en/function.glob.php
1529 1583 $files = glob($directory . '*-updraft-pre-smush-original.*', (defined('GLOB_BRACE') ? GLOB_BRACE : 0));
@@ -1529,13 +1583,13 @@
1529 1583 $files = glob($directory . '*-updraft-pre-smush-original.*', (defined('GLOB_BRACE') ? GLOB_BRACE : 0));
1530 1584
1531 1585 foreach ($files as $file) {
1532 1586 if ($check_date) {
1533 - $filedate_day = (int) date('j', filectime($file));
1587 + $filedate_day = (int) gmdate('j', filectime($file));
1534 1588 if ($filedate_day >= $day_limit) continue;
1535 1589 }
1536 1590
1537 - unlink($file);
1591 + wp_delete_file($file);
1538 1592 }
1539 1593
1540 1594 } else {
1541 1595 // scan directories recursively.
@@ -1546,9 +1600,9 @@
1546 1600 $file = readdir($handle);
1547 1601
1548 1602 while (false !== $file) {
1549 1603
1550 - if ('.' == $file || '..' == $file) {
1604 + if ('.' === $file || '..' === $file) {
1551 1605 $file = readdir($handle);
1552 1606 continue;
1553 1607 }
1554 1608
@@ -1556,9 +1610,9 @@
1556 1610 $this->clear_backup_images_directory($directory . $file, $days_ago);
1557 1611 } elseif (is_file($directory . $file) && preg_match('/^.+-updraft-pre-smush-original\.\S{3,4}/i', $file)) {
1558 1612 // check the file time and compare with $days_ago.
1559 1613 $filedate_day = (int) filectime($directory . $file);
1560 - if ($filedate_day > 0 && ($current_time - $filedate_day) / 86400 >= $days_ago) unlink($directory . $file);
1614 + if ($filedate_day > 0 && ($current_time - $filedate_day) / 86400 >= $days_ago) wp_delete_file($directory . $file);
1561 1615 }
1562 1616
1563 1617 $file = readdir($handle);
1564 1618 }
@@ -1569,9 +1623,9 @@
1569 1623 /**
1570 1624 * Clean backup smush images according to saved options.
1571 1625 */
1572 1626 public function clear_backup_images() {
1573 - $back_up_delete_after = $this->options->get_option('back_up_delete_after', false);
1627 + $back_up_delete_after = $this->options->get_option('back_up_delete_after');
1574 1628
1575 1629 if (!$back_up_delete_after) return;
1576 1630
1577 1631 $back_up_delete_after_days = $this->options->get_option('back_up_delete_after_days', 50);
@@ -1589,48 +1643,12 @@
1589 1643 *
1590 1644 * @return bool
1591 1645 */
1592 1646 public function is_compressed($attachment_id) {
1593 - return (true == get_post_meta($attachment_id, 'smush-complete', true));
1647 + return (true === (bool) get_post_meta($attachment_id, '_wpo-smush-complete', true));
1594 1648 }
1595 1649
1596 1650 /**
1597 - * @param array $form_fields
1598 - * @param WP_Post $post
1599 - *
1600 - * @return array
1601 - */
1602 - public function add_compress_button_to_media_modal($form_fields, $post) {
1603 -
1604 - if (!is_admin() || !function_exists('get_current_screen')) return $form_fields;
1605 -
1606 - /**
1607 - * In media modal get_current_screen() return null or id = 'async-upload' We don't need add smush fields elsewhere.
1608 - */
1609 - $current_screen = get_current_screen();
1610 - if (null !== $current_screen && 'async-upload' != $current_screen->id) return $form_fields;
1611 -
1612 - /**
1613 - * Don't show additional fields for non-image attachments.
1614 - */
1615 - if (!wp_attachment_is_image($post->ID)) return $form_fields;
1616 -
1617 - ob_start();
1618 - $this->render_smush_metabox($post);
1619 - $smush_metabox = ob_get_contents();
1620 - ob_end_clean();
1621 -
1622 - $form_fields['wpo_compress_image'] = array(
1623 - 'value' => '',
1624 - 'label' => __('Compress image', 'wp-optimize'),
1625 - 'input' => 'html',
1626 - 'html' => $smush_metabox,
1627 - );
1628 -
1629 - return $form_fields;
1630 - }
1631 -
1632 - /**
1633 1651 * Returns true if multisite
1634 1652 *
1635 1653 * @return bool
1636 1654 */
@@ -1643,13 +1661,20 @@
1643 1661 *
1644 1662 * @param int $post_id - WordPress Post ID
1645 1663 */
1646 1664 public function unscheduled_original_file_deletion($post_id) {
1647 - $the_original_file = get_post_meta($post_id, 'original-file', true);
1665 + $the_original_file = get_post_meta($post_id, '_wpo-original-file', true);
1666 + // If no original file meta exists, there is nothing to delete.
1667 + if (empty($the_original_file)) {
1668 + return;
1669 + }
1648 1670 $uploads_dir = wp_get_upload_dir();
1649 - $the_original_file = trailingslashit($uploads_dir['basedir']) . $the_original_file;
1650 - if ('' != $the_original_file && file_exists($the_original_file)) {
1651 - @unlink($the_original_file);// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- suppress warning because of file permission issues
1671 + $uploads_basedir = realpath($uploads_dir['basedir']);
1672 + if (!$uploads_basedir) return;
1673 + $uploads_basedir = trailingslashit($uploads_basedir);
1674 + $the_original_file = realpath($uploads_basedir . $the_original_file);
1675 + if ($the_original_file && 0 === strpos($the_original_file, $uploads_basedir) && file_exists($the_original_file)) {
1676 + wp_delete_file($the_original_file);
1652 1677 }
1653 1678 }
1654 1679
1655 1680 /**
@@ -1688,14 +1713,14 @@
1688 1713 'relation' => 'AND',
1689 1714 array(
1690 1715 'relation' => 'OR',
1691 1716 array(
1692 - 'key' => 'smush-complete',
1717 + 'key' => '_wpo-smush-complete',
1693 1718 'compare' => '!=',
1694 1719 'value' => '1',
1695 1720 ),
1696 1721 array(
1697 - 'key' => 'smush-complete',
1722 + 'key' => '_wpo-smush-complete',
1698 1723 'compare' => 'NOT EXISTS',
1699 1724 'value' => '',
1700 1725 ),
1701 1726 ),
@@ -1740,9 +1765,9 @@
1740 1765 }
1741 1766 }
1742 1767
1743 1768 /**
1744 - * Returns a Updraft_Smush_Manager instance
1769 + * Returns Updraft_Smush_Manager instance
1745 1770 */
1746 1771 function Updraft_Smush_Manager() {
1747 1772 return Updraft_Smush_Manager::instance();
1748 1773 }