commands = new Updraft_Smush_Manager_Commands($this); $this->options = WP_Optimize()->get_options(); // we set default options when compression server is false - it means that options was not saved before if (!$this->options->get_option('compression_server')) { $this->set_default_options(); } $this->webservice = $this->options->get_option('compression_server', 'resmushit'); // Ensure the saved service is valid if (!in_array($this->webservice, $this->get_allowed_services())) { $this->webservice = $this->get_default_webservice(); } $this->logger = new Updraft_File_Logger($this->get_logfile_path()); $this->add_logger($this->logger); add_action('wp_ajax_updraft_smush_ajax', array($this, 'updraft_smush_ajax')); add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'), 9); add_action('elementor/editor/before_enqueue_scripts', array($this, 'admin_enqueue_scripts')); add_action('add_attachment', array($this, 'autosmush_create_task')); add_action('ud_task_initialised', array($this, 'set_task_logger')); add_action('ud_task_started', array($this, 'set_task_logger')); add_action('ud_task_completed', array($this, 'record_stats')); add_action('ud_task_failed', array($this, 'record_stats')); add_action('prune_smush_logs', array($this, 'prune_smush_logs')); add_action('process_smush_tasks', array($this, 'process_smush_tasks')); if ('show' == $this->options->get_option('show_smush_metabox', 'show')) { add_action('add_meta_boxes_attachment', array($this, 'add_smush_metabox'), 10, 2); add_filter('attachment_fields_to_edit', array($this, 'add_compress_button_to_media_modal' ), 10, 2); } add_action('delete_attachment', array($this, 'unscheduled_original_file_deletion')); add_filter('manage_media_columns', array($this, 'manage_media_columns')); add_action('manage_media_custom_column', array($this, 'manage_media_custom_column'), 10, 2); // clean backup images cron action. add_action('wpo_smush_clear_backup_images', array($this, 'clear_backup_images')); // add filter for already compressed images by EWWW Image Optimizer. add_filter('wpo_get_uncompressed_images_args', array($this, 'ewww_image_optimizer_compressed_images_args')); // schedule or unschedule clear backup images cron if need $scheduled = wp_next_scheduled('wpo_smush_clear_backup_images'); if ($this->options->get_option('back_up_delete_after', true)) { if (!$scheduled) { wp_schedule_event(time(), 'daily', 'wpo_smush_clear_backup_images'); } } else { if ($scheduled) { wp_unschedule_event($scheduled, 'wpo_smush_clear_backup_images'); } } // Schedule CRON job for deleting failed smush tasks add_action('wpo_smush_clear_failed_tasks', array($this, 'clear_failed_tasks')); if (!wp_next_scheduled('wpo_smush_clear_failed_tasks')) { wp_schedule_event(time(), 'wpo_monthly', 'wpo_smush_clear_failed_tasks'); } } /** * Add custom column to Media Library. * * @param array $columns * @return mixed */ public function manage_media_columns($columns) { $columns['wpo_smush'] = 'WP-Optimize'; return $columns; } /** * Display content in the custom column. * * @param string $column * @param int $attachment_id */ public function manage_media_custom_column($column, $attachment_id) { if ('wpo_smush' !== $column) return; echo $this->get_smush_details($attachment_id); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output already escaped when generating smush details } /** * Get smush details of given image ID * * @param int $attachment_id * * @return string smush details */ public function get_smush_details($attachment_id) { $info = '
%s
", esc_html($message)); } if (WPO_Image_Utils::is_supported_extension($ext, array_diff($allowed_extensions, array('gif'))) && file_exists($file) && !file_exists($file . '.webp')) { if (WPO_WebP_Utils::can_do_webp_conversion()) { $link_text = __('Convert to WebP', 'wp-optimize'); $output .= sprintf('%s%s
", esc_html__('Compressing this file type extension is not supported', 'wp-optimize')); } } /** * Get text for restrore image tooltip. * * @return string */ private function get_restore_image_tooltip_text() { $text = __('Only the original image will be restored.', 'wp-optimize'); $text .= ' '; $text .= __('In order to restore the other sizes, you should use a plugin such as "Regenerate Thumbnails".', 'wp-optimize'); return $text; } /** * Check if a single image compressed by another plugin. * * @param int $image_id * @return bool */ private function is_image_compressed_by_another_plugin($image_id) { global $wpdb; $meta = $wpdb->get_results("SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE `post_id`={$image_id}", ARRAY_A); if (is_array($meta)) { foreach ($meta as $row) { // Smush, Imagify, Compress JPEG & PNG images by TinyPNG. if (in_array($row['meta_key'], array('wp-smpro-smush-data', '_imagify_optimization_level', 'tiny_compress_images'))) return true; // ShortPixel Image Optimizer if ('_shortpixel_status' == $row['meta_key'] && 2 <= $row['meta_key'] && 3 > $row['meta_key']) return true; } } if (WP_Optimize()->get_db_info()->table_exists('ewwwio_images')) { $old_show_errors = $wpdb->show_errors(false); // EWWW Image Optimizer. $ewww_image = $wpdb->get_col("SELECT attachment_id FROM {$wpdb->prefix}ewwwio_images WHERE attachment_id={$image_id} AND gallery='media' LIMIT 1"); if (!empty($ewww_image)) return true; $wpdb->show_errors($old_show_errors); } return apply_filters('wpo_image_compressed_by_another_plugin', false); } /** * Get attachment ids for images those already compressed with EWWW Image Optimizer. * Used with filter `wpo_get_uncompressed_images_args`. * * @param array $args WP_Query arguments. * @return array */ public function ewww_image_optimizer_compressed_images_args($args) { global $wpdb; if (!WP_Optimize()->get_db_info()->table_exists('ewwwio_images')) return $args; $old_show_errors = $wpdb->show_errors(false); $compressed_images = $wpdb->get_col("SELECT DISTINCT(attachment_id) FROM {$wpdb->prefix}ewwwio_images WHERE gallery='media'"); $wpdb->show_errors($old_show_errors); if (isset($args['post__not_in'])) { $args['post__not_in'] = array_merge($args['post__not_in'], $compressed_images); } else { $args['post__not_in'] = $compressed_images; } return $args; } /** * Returns a list of images for smush (from cache if available) * * @param string $use_cache * @return array - uncompressed images */ public function get_uncompressed_images($use_cache = "true") { if ("true" == $use_cache) { $uncompressed_images = $this->get_from_cache('uncompressed_images'); if ($uncompressed_images) return $uncompressed_images; } $uncompressed_images = array(); $accepted_mimes = array('image/jpeg', 'image/gif', 'image/png'); $args = array( 'post_type' => 'attachment', 'post_mime_type' => $accepted_mimes, 'post_status' => 'inherit', 'posts_per_page' => apply_filters('updraft_smush_posts_per_page', 1000), 'meta_query' => $this->get_uncompressed_images_meta_query(), 'no_found_rows' => true, 'fields' => 'ids' ); $allowed_extensions = WPO_Image_Utils::get_allowed_extensions(); if (is_multisite()) { $sites = WP_Optimize()->get_sites(); foreach ($sites as $site) { switch_to_blog($site->blog_id); $args = apply_filters('wpo_get_uncompressed_images_args', $args); $images = new WP_Query($args); foreach ($images->posts as $image) { // If `field` is removed from $args it returns a WP_Post obj $image_id = is_int($image) ? $image : $image->ID; $file = get_attached_file($image_id); $ext = WPO_Image_Utils::get_extension($file); if (file_exists($file)) { if (WPO_Image_Utils::is_supported_extension($ext, $allowed_extensions)) { $uncompressed_images[$site->blog_id][] = array( 'id' => $image_id, 'thumb_url' => wp_get_attachment_thumb_url($image_id), 'filesize' => filesize(get_attached_file($image_id)) ); } else { $this->log("Blog_id={$site->blog_id}, ID={$image_id}, File={$file} This image type is not supported."); } } else { $this->log("Could not find file for image: blog_id={$site->blog_id}, ID={$image_id}, file={$file}"); } } restore_current_blog(); } } else { $args = apply_filters('wpo_get_uncompressed_images_args', $args); $images = new WP_Query($args); foreach ($images->posts as $image) { // If `field` is removed from $args it returns a WP_Post obj $image_id = is_int($image) ? $image : $image->ID; $file = get_attached_file($image_id); $ext = WPO_Image_Utils::get_extension($file); if (file_exists($file)) { if (WPO_Image_Utils::is_supported_extension($ext, $allowed_extensions)) { $uncompressed_images[1][] = array( 'id' => $image_id, 'thumb_url' => wp_get_attachment_thumb_url($image_id), 'filesize' => filesize(get_attached_file($image_id)) ); } else { $this->log("Image ID={$image_id}, File={$file} This image type is not supported."); } } else { $this->log("Could not find file for image: ID={$image_id}, file={$file}"); } } } $this->save_to_cache('uncompressed_images', $uncompressed_images); return $uncompressed_images; } /** * Returns a list of admin URLs. This is to prevent unnecessary bloat in the output of get_uncompressed_images() (and thus better performance over the network on sites with huge numbers of images) * * @return array - list of admin URLs */ public function get_admin_urls() { $admin_urls = $this->get_from_cache('admin_urls'); if ($admin_urls) return $admin_urls; $admin_urls = array(); if (is_multisite()) { $sites = WP_Optimize()->get_sites(); foreach ($sites as $site) { switch_to_blog($site->blog_id); $admin_urls[$site->blog_id] = admin_url(); restore_current_blog(); } } else { // The pseudo-blog_id here (1) matches (and must match) what is used in get_uncompressed_images $admin_urls[1] = admin_url(); } $this->save_to_cache('admin_urls', $admin_urls); return $admin_urls; } /** * Check if a task exists for a given image * * @param string $image - The attachment ID of the image * @return bool - true if yes, false otherwise */ public function task_exists($image) { $blog_id = get_current_blog_id(); $pending_tasks = $this->get_active_tasks('smush'); if (!empty($pending_tasks)) { foreach ($pending_tasks as $task) { $task_attachment_id = $task->get_option('attachment_id'); $task_blog_id = $task->get_option('blog_id'); if ($image === $task_attachment_id && $blog_id === $task_blog_id) { return true; } } } return false; } /** * Returns the status of images compressed in this iteration of the bulk compress * * @param array $images - List of images in the current session * * @return array - status of the operation */ public function get_session_stats($images) { $stats = array(); foreach ($images as $image) { if (is_multisite()) { switch_to_blog($image['blog_id']); $stats[] = get_post_meta($image['attachment_id'], 'smush-complete', true) ? 'success' : 'fail'; restore_current_blog(); } else { $stats[] = get_post_meta($image['attachment_id'], 'smush-complete', true) ? 'success' : 'fail'; } } return array_count_values($stats); } /** * Returns a list of images for smush (from cache if available) * * @return array - List of task objects with uncompressed images */ public function get_pending_tasks() { return $this->get_active_tasks('smush'); } /** * Deletes and removes any pending tasks from queue */ public function clear_pending_images() { $pending_tasks = $this->get_active_tasks('smush'); if (!empty($pending_tasks)) { foreach ($pending_tasks as $task) { $task->delete_meta(); $task->delete(); } } return true; } /** * Returns a count of failed tasks * * @return int - failed tasks */ public function get_failed_task_count() { return $this->options->get_option('failed_task_count', 0); } /** * Adds the required scripts and styles */ public function admin_enqueue_scripts() { $current_screen = get_current_screen(); if (null === $current_screen) return; // load scripts and styles only on WP-Optimize pages if (!preg_match('/wp\-optimize|attachment|upload/i', $current_screen->id)) return; $enqueue_version = WP_Optimize()->get_enqueue_version(); $min_or_not = WP_Optimize()->get_min_or_not_string(); $min_or_not_internal = WP_Optimize()->get_min_or_not_internal_string(); $js_variables = $this->smush_js_translations(); $js_variables['ajaxurl'] = admin_url('admin-ajax.php'); $js_variables['features'] = $this->get_features(); $js_variables['smush_ajax_nonce'] = wp_create_nonce('updraft-task-manager-ajax-nonce'); $js_variables['smush_settings'] = $this->get_smush_options(); $js_variables['blog_id'] = get_current_blog_id(); $js_variables['compress'] = esc_html__('Compress', 'wp-optimize'); $js_variables['cancel'] = esc_html__('Cancel', 'wp-optimize'); $js_variables['cancelling'] = esc_html__('Cancelling...', 'wp-optimize'); $js_variables['images_restored_successfully'] = esc_html__('The images were restored successfully', 'wp-optimize'); $js_variables['logo_src'] = esc_url(WPO_PLUGIN_URL.'images/notices/wp_optimize_logo.png'); wp_enqueue_script('block-ui-js', WPO_PLUGIN_URL.'includes/blockui/jquery.blockUI'.$min_or_not.'.js', array('jquery'), $enqueue_version); wp_enqueue_script('wp-optimize-heartbeat-js', WPO_PLUGIN_URL.'js/heartbeat'.$min_or_not_internal.'.js', array('jquery'), $enqueue_version); wp_localize_script('wp-optimize-heartbeat-js', 'wpo_heartbeat_ajax', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('heartbeat-nonce'), 'interval' => WPO_Ajax::HEARTBEAT_INTERVAL )); wp_enqueue_script('smush-js', WPO_PLUGIN_URL.'js/wposmush'.$min_or_not_internal.'.js', array('jquery', 'block-ui-js', 'wp-optimize-block-ui', 'wp-optimize-send-command', 'wp-optimize-heartbeat-js'), $enqueue_version); wp_enqueue_style('smush-css', WPO_PLUGIN_URL.'css/smush'.$min_or_not_internal.'.css', array(), $enqueue_version); wp_localize_script('smush-js', 'wposmush', $js_variables); } /** * Gets default service provider for smush * * @return string - service name */ public function get_default_webservice() { return 'resmushit'; } /** * Sets default options for smush */ public function set_default_options() { $options = array( 'compression_server' => $this->get_default_webservice(), 'image_quality' => 92, 'lossy_compression' => false, 'back_up_original' => true, 'preserve_exif' => false, 'autosmush' => false, 'back_up_delete_after' => $this->options->get_option('back_up_delete_after', true), 'back_up_delete_after_days' => $this->options->get_option('back_up_delete_after_days', 50), 'webp_conversion' => false, ); $this->update_smush_options($options); } /** * Gets default service provider for smush * * @param string $server - The name of the server * @return string - associated task type, default if none found */ public function get_associated_task($server) { $allowed = $this->get_allowed_services(); if (key_exists($server, $allowed)) return $allowed[$server]; $default = $this->get_default_webservice(); return $allowed[$default]; } /** * Gets allowed service providers for smush * * @return array - key value pair of service name => task name */ public function get_allowed_services() { return array( 'resmushit' => 'Re_Smush_It_Task', ); } /** * Gets allowed service provider features smush * * @return array - key value pair of service name => features exposed */ public function get_features() { $features = array(); foreach ($this->get_allowed_services() as $service => $class_name) { $features[$service] = call_user_func(array($class_name, 'get_features')); } return $features; } /** * Returns the path to the logfile * * @return string - file path */ public function get_logfile_path() { return WP_Optimize_Utils::get_log_file_path('smush'); } /** * Delete all smush log files * * @deprecated 3.5.0 */ public function delete_log_files() { _deprecated_function(__METHOD__, '3.5.0'); } /** * Adds a logger to the task * * @param Mixed $task - a task object */ public function set_task_logger($task) { if (!$this->logger) { $this->logger = new Updraft_File_Logger($this->get_logfile_path()); } if (!$task->get_loggers()) { $task->add_logger($this->logger); } } /** * Writes a standardised header to the log file */ public function write_log_header() { global $wpdb; // phpcs:disable $wp_version = $this->get_wordpress_version(); $mysql_version = $wpdb->db_version(); $disabled_functions = ini_get('disable_functions'); $max_execution_time = (int) @ini_get("max_execution_time"); $memory_limit = ini_get('memory_limit'); $memory_usage = round(@memory_get_usage(false)/1048576, 1); $total_memory_usage = round(@memory_get_usage(true)/1048576, 1); // Attempt to raise limit @set_time_limit(330); $log_header = array(); // phpcs:enable $log_header[] = "\n"; $log_header[] = "Header for logs at time: ".gmdate('r')." on ".network_site_url(); $log_header[] = "WP: ".$wp_version; $php_uname = ''; if (function_exists('php_uname')) { $php_uname = ", " . php_uname(); } $log_header[] = "PHP: ".phpversion()." (".PHP_SAPI.$php_uname.")"; $log_header[] = "MySQL: $mysql_version"; $log_header[] = "WPLANG: ".get_locale(); $log_header[] = "Server: ".$_SERVER["SERVER_SOFTWARE"]; $log_header[] = "Outbound connections: ".(defined('WP_HTTP_BLOCK_EXTERNAL') ? 'Y' : 'N'); $log_header[] = "Disabled Functions: $disabled_functions"; $log_header[] = "max_execution_time: $max_execution_time"; $log_header[] = "memory_limit: $memory_limit (used: {$memory_usage}M | {$total_memory_usage}M)"; $log_header[] = "multisite: ".(is_multisite() ? 'Y' : 'N'); $log_header[] = "openssl: ".(defined('OPENSSL_VERSION_TEXT') ? OPENSSL_VERSION_TEXT : 'N'); if (apply_filters("wpo_write_server_info_in_smush_log", false)) { foreach ($log_header as $log_entry) { $this->log($log_entry); } } $memlim = $this->memory_check_current(); if ($memlim<65 && $memlim>0) { $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'); } if ($max_execution_time>0 && $max_execution_time<20) { $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'); } } /** * Prunes the log file */ public function prune_smush_logs() { $this->log("Pruning the smush log file"); $this->logger->prune_logs(); } /** * Get the WordPress version * * @return String - the version */ public function get_wordpress_version() { static $got_wp_version = false; if (!$got_wp_version) { global $wp_version; @include(ABSPATH.WPINC.'/version.php');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- suppress warning if `version.php` does not exists $got_wp_version = $wp_version; } return $got_wp_version; } /** * Get the current memory limit * * @return String - memory limit in megabytes */ public function memory_check_current($memory_limit = false) { // Returns in megabytes if (false == $memory_limit) $memory_limit = ini_get('memory_limit'); $memory_limit = rtrim($memory_limit); $memory_unit = $memory_limit[strlen($memory_limit)-1]; if (0 == (int) $memory_unit && '0' !== $memory_unit) { $memory_limit = substr($memory_limit, 0, strlen($memory_limit)-1); } else { $memory_unit = ''; } switch ($memory_unit) { case '': $memory_limit = floor($memory_limit/1048576); break; case 'K': case 'k': $memory_limit = floor($memory_limit/1024); break; case 'G': $memory_limit = $memory_limit*1024; break; case 'M': // assumed size, no change needed break; } return $memory_limit; } /** * Saves a value to the cache. * * @param string $key * @param mixed $value * @param int $blog_id */ public function save_to_cache($key, $value, $blog_id = 1) { $transient_limit = 3600 * 48; $key = 'wpo_smush_cache_' . $blog_id . '_'. $key; WP_Optimize_Transients_Cache::get_instance()->set_transient($key, $value, $transient_limit); } /** * Gets value from the cache. * * @param string $key * @param int $blog_id * @return mixed */ public function get_from_cache($key, $blog_id = 1) { $key = 'wpo_smush_cache_' . $blog_id . '_'. $key; return WP_Optimize_Transients_Cache::get_instance()->get($key); } /** * Deletes a value from the cache. * * @param string $key * @param int $blog_id */ public function delete_from_cache($key, $blog_id = 1) { $key = 'wpo_smush_cache_' . $blog_id . '_'. $key; WP_Optimize_Transients_Cache::get_instance()->delete($key); $this->delete_transient($key); } /** * Wrapper for deleting a transient * * @param string $key */ public function delete_transient($key) { if ($this->is_multisite_mode()) { delete_site_transient($key); } else { delete_transient($key); } } /** * Removes all cached data */ public function clear_cached_data() { global $wpdb; // get list of cached data by optimization. if ($this->is_multisite_mode()) { $keys = $wpdb->get_col("SELECT meta_key FROM {$wpdb->sitemeta} WHERE meta_key LIKE '%wpo_smush_cache_%'"); } else { $keys = $wpdb->get_col("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '%wpo_smush_cache_%'"); } if (!empty($keys)) { $transient_keys = array(); foreach ($keys as $key) { preg_match('/wpo_smush_cache_.+/', $key, $option_name); $option_name = $option_name[0]; $transient_keys[] = $option_name; } // get unique keys. $transient_keys = array_unique($transient_keys); // delete transients. foreach ($transient_keys as $key) { $this->delete_transient($key); } } } /** * Delete recursively all smush backup files created more that $days_ago days. * * @param string $directory upload directory * @param int $days_ago */ public function clear_backup_images_directory($directory, $days_ago = 30) { $directory = trailingslashit($directory); $current_time = time(); if (preg_match('/(\d{4})\/(\d{2})\/$/', $directory, $match)) { $check_date = false; if ($days_ago > 0) { // check if it is end directory then scan for backup images. $year = (int) $match[1]; $month = (int) $match[2]; $limit = strtotime('-'.$days_ago.' '.(($days_ago > 1) ? 'days' : 'day')); $year_limit = (int) gmdate('Y', $limit); $month_limit = (int) gmdate('m', $limit); $day_limit = (int) gmdate('j', $limit); // if current directory is newer than needed then we skip it. if ($year_limit < $year || ($year_limit == $year && $month_limit < $month)) { return; } // we will check dates only in directory that contain limit date. $check_date = ($year_limit == $year && $month_limit == $month); } // GLOB_BRACE isn't defined on some systems (Solaris, SunOS and more) > https://www.php.net/manual/en/function.glob.php $files = glob($directory . '*-updraft-pre-smush-original.*', (defined('GLOB_BRACE') ? GLOB_BRACE : 0)); foreach ($files as $file) { if ($check_date) { $filedate_day = (int) gmdate('j', filectime($file)); if ($filedate_day >= $day_limit) continue; } wp_delete_file($file); } } else { // scan directories recursively. $handle = opendir($directory); if (false === $handle) return; $file = readdir($handle); while (false !== $file) { if ('.' == $file || '..' == $file) { $file = readdir($handle); continue; } if (is_dir($directory . $file)) { $this->clear_backup_images_directory($directory . $file, $days_ago); } elseif (is_file($directory . $file) && preg_match('/^.+-updraft-pre-smush-original\.\S{3,4}/i', $file)) { // check the file time and compare with $days_ago. $filedate_day = (int) filectime($directory . $file); if ($filedate_day > 0 && ($current_time - $filedate_day) / 86400 >= $days_ago) wp_delete_file($directory . $file); } $file = readdir($handle); } } } /** * Clean backup smush images according to saved options. */ public function clear_backup_images() { $back_up_delete_after = $this->options->get_option('back_up_delete_after', false); if (!$back_up_delete_after) return; $back_up_delete_after_days = $this->options->get_option('back_up_delete_after_days', 50); $upload_dir = wp_upload_dir(null, false); $base_dir = $upload_dir['basedir']; $this->clear_backup_images_directory($base_dir, $back_up_delete_after_days); } /** * Check if attachment already compressed. * * @param int $attachment_id * * @return bool */ public function is_compressed($attachment_id) { return (true == get_post_meta($attachment_id, 'smush-complete', true)); } /** * @param array $form_fields * @param WP_Post $post * * @return array */ public function add_compress_button_to_media_modal($form_fields, $post) { if (!is_admin() || !function_exists('get_current_screen')) return $form_fields; /** * In media modal get_current_screen() return null or id = 'async-upload' We don't need add smush fields elsewhere. */ $current_screen = get_current_screen(); if (null !== $current_screen && 'async-upload' != $current_screen->id) return $form_fields; /** * Don't show additional fields for non-image attachments. */ if (!wp_attachment_is_image($post->ID)) return $form_fields; ob_start(); $this->render_smush_metabox($post); $smush_metabox = ob_get_contents(); ob_end_clean(); $form_fields['wpo_compress_image'] = array( 'value' => '', 'label' => __('Compress image', 'wp-optimize'), 'input' => 'html', 'html' => $smush_metabox, ); return $form_fields; } /** * Returns true if multisite * * @return bool */ public function is_multisite_mode() { return WP_Optimize()->is_multisite_mode(); } /** * This callback function is triggered due to delete_attachment action (wp-includes/post.php) and is executed prior to deletion of post-type attachment * * @param int $post_id - WordPress Post ID */ public function unscheduled_original_file_deletion($post_id) { $the_original_file = get_post_meta($post_id, 'original-file', true); $uploads_dir = wp_get_upload_dir(); $the_original_file = trailingslashit($uploads_dir['basedir']) . $the_original_file; if ('' != $the_original_file && file_exists($the_original_file)) { wp_delete_file($the_original_file); } } /** * Remove failed smush tasks from the wp_tm_tasks table */ public function clear_failed_tasks() { $failed_tasks = $this->get_tasks('failed', 'smush'); if (empty($failed_tasks)) return; foreach ($failed_tasks as $task) { $task->delete_meta(); $task->delete(); } } /** * Instance of WP_Optimize_Page_Cache_Preloader. * * @return self */ public static function instance() { if (empty(self::$_instance)) { self::$_instance = new self(); } return self::$_instance; } /** * Meta query array for getting uncompressed images * * @return array */ public function get_uncompressed_images_meta_query() { return array( 'relation' => 'AND', array( 'relation' => 'OR', array( 'key' => 'smush-complete', 'compare' => '!=', 'value' => '1', ), array( 'key' => 'smush-complete', 'compare' => 'NOT EXISTS', 'value' => '', ), ), // ShortPixel Image Optimizer plugin array( 'relation' => 'OR', array( 'key' => '_shortpixel_status', 'compare' => '<', 'value' => '2', ), array( 'key' => '_shortpixel_status', 'compare' => '>=', 'value' => '3', ), array( 'key' => '_shortpixel_status', 'compare' => 'NOT EXISTS', 'value' => '', ), ), // Smush plugin array( 'key' => 'wp-smpro-smush-data', 'compare' => 'NOT EXISTS', 'value' => '', ), // Imagify array( 'key' => '_imagify_optimization_level', 'compare' => 'NOT EXISTS', 'value' => '', ), // Compress JPEG & PNG images by TinyPNG array( 'key' => 'tiny_compress_images', 'compare' => 'NOT EXISTS', 'value' => '', ), ); } } /** * Returns a Updraft_Smush_Manager instance */ function Updraft_Smush_Manager() { return Updraft_Smush_Manager::instance(); } endif;