Skip to content

Instantly share code, notes, and snippets.

@wpmudev-sls
Created June 30, 2020 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpmudev-sls/14ce8479b026a733125a72fa79577b19 to your computer and use it in GitHub Desktop.
Save wpmudev-sls/14ce8479b026a733125a72fa79577b19 to your computer and use it in GitHub Desktop.
[Smush] - Force Re-Smush. This snippet should be used with caution and only temporarily, while the image scan is running. It has to be removed once done scanning as it will always return that all images need to be Smushed. When rechecking images this snippet will return all images that need Re-Smushing. This way admin can Smush them all again.
<?php
/**
* Plugin Name: [Smush] - Force Re-Smush
* Plugin URI: https://premium.wpmudev.org/
* Description: This snippet should be used with caution and only temporarily, while the image scan is running. It has to be removed once done scanning as it will always return that all images need to be Smushed. When rechecking images this snippet will return all images that need Re-Smushing. This way admin can Smush them all again.
* Task: SLS-262
* Author: Panos Lyrakis @ WPMUDEV
* Author URI: https://premium.wpmudev.org/
* License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return;
}
if ( ! class_exists( 'WPMUDEV_Smush_Force_Resmush' ) ) {
class WPMUDEV_Smush_Force_Resmush {
private static $_instance = null;
private $smush_core = null;
private $smush_instance = null;
private $core_settings = null;
public static function get_instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new WPMUDEV_Smush_Force_Resmush();
}
return self::$_instance;
}
private function __construct() {
$this->setup();
add_action( 'init', array( $this, 'remove_resmush_scan' ), 4 );
add_action( 'wp_ajax_scan_for_resmush', array( $this, 'override_resmush_scan' ) );
}
public function override_resmush_scan() {
check_ajax_referer( 'save_wp_smush_options', 'wp_smush_options_nonce' );
wp_cache_delete( 'media_attachments', 'wp-smush' );
$resmush_list = array();
// Scanning for NextGen or Media Library.
$type = isset( $_REQUEST['type'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['type'] ) ) : '';
$core = WP_Smush::get_instance()->core();
// Save settings only if networkwide settings are disabled.
if ( Smush\Core\Settings::can_access() && ( ! isset( $_REQUEST['process_settings'] ) || 'false' !== $_REQUEST['process_settings'] ) ) {
// Save Settings.
$this->core_settings->save( false );
// Fetch the new settings.
$this->core_settings->init();
}
// If there aren't any images in the library, return the notice.
if ( 0 === count( $core->get_media_attachments() ) && 'nextgen' !== $type ) {
wp_send_json_success(
array(
'notice' => esc_html__( 'We haven’t found any images in your media library yet so there’s no smushing to be done! Once you upload images, reload this page and start playing!', 'wp-smushit' ),
'super_smush' => WP_Smush::is_pro() && $this->core_settings->get( 'lossy' ),
)
);
}
// If a user manually runs smush check.
$return_ui = isset( $_REQUEST['get_ui'] ) && 'true' == $_REQUEST['get_ui'] ? true : false;
/**
* Logic: If none of the required settings is on, don't need to resmush any of the images
* We need at least one of these settings to be on, to check if any of the image needs resmush.
*/
// Initialize Media Library Stats.
if ( 'nextgen' !== $type && empty( $core->remaining_count ) ) {
// Force update to clear caches.
$core->setup_global_stats( true );
}
// Initialize NextGen Stats.
if ( 'nextgen' === $type && is_object( $core->nextgen->ng_admin ) && empty( $core->nextgen->ng_admin->remaining_count ) ) {
$core->nextgen->ng_admin->setup_image_counts();
}
$key = 'nextgen' === $type ? 'wp-smush-nextgen-resmush-list' : 'wp-smush-resmush-list';
$remaining_count = 'nextgen' === $type ? $core->nextgen->ng_admin->remaining_count : $core->remaining_count;
if ( 0 === (int) $remaining_count && ( ! WP_Smush::is_pro() || ! $this->core_settings->get( 'lossy' ) ) && ( ! $this->core_settings->get( 'original' ) || ! WP_Smush::is_pro() ) && ! $this->core_settings->get( 'strip_exif' ) ) {
delete_option( $key );
// Default Notice, to be displayed at the top of page. Show a message, at the top.
wp_send_json_success(
array(
'notice' => esc_html__( 'Yay! All images are optimized as per your current settings.', 'wp-smushit' ),
)
);
}
// Set to empty by default.
$ajax_response = '';
// Get Smushed Attachments.
if ( 'nextgen' !== $type ) {
// Get list of Smushed images.
$attachments = ! empty( $core->smushed_attachments ) ? $core->smushed_attachments : $core->get_smushed_attachments();
} else {
// Get smushed attachments list from nextgen class, We get the meta as well.
$attachments = $core->nextgen->ng_stats->get_ngg_images();
}
$image_count = $super_smushed_count = $smushed_count = $resized_count = 0;
// Check if any of the smushed image needs to be resmushed.
if ( ! empty( $attachments ) && is_array( $attachments ) ) {
$stats = array(
'size_before' => 0,
'size_after' => 0,
'savings_resize' => 0,
'savings_conversion' => 0,
);
// Initialize resize class.
$core->mod->resize->initialize();
foreach ( $attachments as $attachment_k => $attachment ) {
// Skip if already in resmush list.
if ( ! empty( $core->resmush_ids ) && in_array( $attachment, $core->resmush_ids ) ) {
// continue;
}
$should_resmush = false;
// For NextGen we get the metadata in the attachment data itself.
if ( is_array( $attachment ) && ! empty( $attachment['wp_smush'] ) ) {
$smush_data = $attachment['wp_smush'];
} else {
// Check the current settings, and smush data for the image.
$smush_data = get_post_meta( $attachment, Smush\Core\Modules\Smush::$smushed_meta_key, true );
}
// If the image is already smushed.
if ( is_array( $smush_data ) && ! empty( $smush_data['stats'] ) ) {
// If we need to optmise losslessly, add to resmush list.
$smush_lossy = WP_Smush::is_pro() && $this->core_settings->get( 'lossy' ) && ! $smush_data['stats']['lossy'];
// If we need to strip exif, put it in resmush list.
$strip_exif = $this->core_settings->get( 'strip_exif' ) && isset( $smush_data['stats']['keep_exif'] ) && ( 1 == $smush_data['stats']['keep_exif'] );
// If Original image needs to be smushed.
$smush_original = $this->core_settings->get( 'original' ) && WP_Smush::is_pro() && empty( $smush_data['sizes']['full'] );
$should_resmush = true;
// Check if new sizes have been selected.
$image_sizes = $this->core_settings->get_setting( WP_SMUSH_PREFIX . 'image_sizes' );
// Empty means we need to smush all images. So get all sizes of current site.
if ( empty( $image_sizes ) ) {
$image_sizes = array_keys( WP_Smush::get_instance()->core()->image_dimensions() );
}
// If the image needs to be resmushed add it to the list.
if ( $should_resmush ) {
$resmush_list[] = 'nextgen' === $type ? $attachment_k : $attachment;
}
/**
* Calculate stats during re-check images action.
*/
if ( 'nextgen' !== $type ) {
$resize_savings = get_post_meta( $attachment, WP_SMUSH_PREFIX . 'resize_savings', true );
$conversion_savings = Smush\Core\Helper::get_pngjpg_savings( $attachment );
// Increase the smushed count.
$smushed_count ++;
// Get the resized image count.
if ( ! empty( $resize_savings ) ) {
$resized_count ++;
}
// Get the image count.
$image_count += ( ! empty( $smush_data['sizes'] ) && is_array( $smush_data['sizes'] ) ) ? count( $smush_data['sizes'] ) : 0;
// If the image is in resmush list, and it was super smushed earlier.
$super_smushed_count += ( $smush_data['stats']['lossy'] ) ? 1 : 0;
// Add to the stats.
$stats['size_before'] += ! empty( $smush_data['stats'] ) ? $smush_data['stats']['size_before'] : 0;
$stats['size_before'] += ! empty( $resize_savings['size_before'] ) ? $resize_savings['size_before'] : 0;
$stats['size_before'] += ! empty( $conversion_savings['size_before'] ) ? $conversion_savings['size_before'] : 0;
$stats['size_after'] += ! empty( $smush_data['stats'] ) ? $smush_data['stats']['size_after'] : 0;
$stats['size_after'] += ! empty( $resize_savings['size_after'] ) ? $resize_savings['size_after'] : 0;
$stats['size_after'] += ! empty( $conversion_savings['size_after'] ) ? $conversion_savings['size_after'] : 0;
$stats['savings_resize'] += ! empty( $resize_savings ) && isset( $resize_savings['bytes'] ) ? $resize_savings['bytes'] : 0;
$stats['savings_conversion'] += ! empty( $conversion_savings ) && isset( $conversion_savings['bytes'] ) ? $conversion_savings['bytes'] : 0;
}
}
}// End of Foreach Loop
// Store the resmush list in Options table.
update_option( $key, $resmush_list, false );
}
// Get updated stats for NextGen.
if ( 'nextgen' === $type ) {
// Reinitialize NextGen stats.
$core->nextgen->ng_admin->setup_image_counts();
// Image count, Smushed Count, Super-smushed Count, Savings.
$stats = $core->nextgen->ng_stats->get_smush_stats();
$image_count = $core->nextgen->ng_admin->image_count;
$smushed_count = $core->nextgen->ng_admin->smushed_count;
$super_smushed_count = $core->nextgen->ng_admin->super_smushed;
}
// Delete resmush list if empty.
if ( empty( $resmush_list ) ) {
delete_option( $key );
}
$resmush_count = $count = count( $resmush_list );
$count += 'nextgen' === $type ? $core->nextgen->ng_admin->remaining_count : $core->remaining_count;
// Return the Remsmush list and UI to be appended to Bulk Smush UI.
if ( $return_ui ) {
if ( 'nextgen' !== $type ) {
// Set the variables.
$core->resmush_ids = $resmush_list;
} else {
// To avoid the php warning.
$core->nextgen->ng_admin->resmush_ids = $resmush_list;
}
if ( $resmush_count ) {
$ajax_response = WP_Smush::get_instance()->admin()->bulk_resmush_content( $count );
}
}
// Directory Smush Stats
// Include directory smush stats if not requested for NextGen.
if ( 'nextgen' !== $type ) {
// Append the directory smush stats.
$dir_smush_stats = get_option( 'dir_smush_stats' );
if ( ! empty( $dir_smush_stats ) && is_array( $dir_smush_stats ) ) {
if ( ! empty( $dir_smush_stats['dir_smush'] ) && ! empty( $dir_smush_stats['optimised'] ) ) {
$dir_smush_stats = $dir_smush_stats['dir_smush'];
$image_count += $dir_smush_stats['optimised'];
}
// Add directory smush stats if not empty.
if ( ! empty( $dir_smush_stats['image_size'] ) && ! empty( $dir_smush_stats['orig_size'] ) ) {
$stats['size_before'] += $dir_smush_stats['orig_size'];
$stats['size_after'] += $dir_smush_stats['image_size'];
}
}
}
// If there is a Ajax response return it, else return null.
$return = ! empty( $ajax_response ) ? array(
'resmush_ids' => $resmush_list,
'content' => $ajax_response,
'count_image' => $image_count,
'count_supersmushed' => $super_smushed_count,
'count_smushed' => $smushed_count,
'count_resize' => $resized_count,
'size_before' => $stats['size_before'],
'size_after' => $stats['size_after'],
'savings_resize' => ! empty( $stats['savings_resize'] ) ? $stats['savings_resize'] : 0,
'savings_conversion' => ! empty( $stats['savings_conversion'] ) ? $stats['savings_conversion'] : 0,
) : array();
// Include the count.
if ( ! empty( $count ) && $count ) {
$return['count'] = $count;
}
if ( ! empty( $count ) ) {
$return['noticeType'] = 'warning';
$return['notice'] = sprintf(
/* translators: %1$d - number of images, %2$s - opening a tag, %3$s - closing a tag */
esc_html__( 'Image check complete, you have %1$d images that need smushing. %2$sBulk smush now!%3$s', 'wp-smushit' ),
$count,
'<a href="#" class="wp-smush-trigger-bulk" data-type="' . $type . '">',
'</a>'
);
}
$return['super_smush'] = WP_Smush::is_pro() && $this->core_settings->get( 'lossy' );
if ( WP_Smush::is_pro() && $this->core_settings->get( 'lossy' ) && 'nextgen' === $type ) {
$ss_count = $core->nextgen->ng_stats->nextgen_super_smushed_count( $core->nextgen->ng_stats->get_ngg_images( 'smushed' ) );
$return['super_smush_stats'] = sprintf( '<strong><span class="smushed-count">%d</span>/%d</strong>', $ss_count, $core->nextgen->ng_admin->total_count );
}
wp_send_json_success( $return );
}
public function remove_resmush_scan() {
global $wp_filter;
$tag = 'wp_ajax_scan_for_resmush';
$hook_method = 'scan_images';
$hook_class = 'Smush\\App\\Ajax';
if ( ! isset( $wp_filter[ $tag ] ) ) {
return;
}
foreach ( $wp_filter[ $tag ]->callbacks as $key => $callback_array ) {
foreach ( $callback_array as $c_key => $callback ) {
if ( substr_compare( $c_key, $hook_method, strlen( $c_key ) - strlen( $hook_method ), strlen( $hook_method ) ) === 0 ) {
if ( $callback['function'][0] instanceof $hook_class ) {
unset( $wp_filter[ $tag ]->callbacks[ $key ][ $c_key ] );
}
}
}
}
}
private function setup() {
if ( is_null( $this->smush_core ) ) {
if ( version_compare( WP_SMUSH_VERSION, '3.5.0' ) >= 0 ) {
$this->smush_instance = WP_Smush::get_instance();
$this->smush_core = $this->smush_instance::get_instance()->core();
} else {
$this->smush_instance = Smush\WP_Smush::get_instance();
$this->smush_core = $this->smush_instance::get_instance()->core();
}
$this->core_settings = Smush\Core\Settings::get_instance();
}
}
}
if ( ! function_exists( 'wpmudev_smush_force_resmush' ) ) {
function wpmudev_smush_force_resmush() {
return WPMUDEV_Smush_Force_Resmush::get_instance();
};
add_action( 'plugins_loaded', 'wpmudev_smush_force_resmush', 99 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment