izes'][ $size_name ]->bytes = $stats['sizes'][ $size_name ]->bytes + $existing_stats_size->bytes; $stats['sizes'][ $size_name ]->percent = $this->calculate_percentage( $stats['sizes'][ $size_name ], $existing_stats_size ); } } } } // Sum Up all the stats. $stats = WP_Smush::get_instance()->core()->total_compression( $stats ); // If there was any compression and there was no error in smushing. if ( isset( $stats['stats']['bytes'] ) && $stats['stats']['bytes'] >= 0 && ! $has_errors ) { /** * Runs if the image smushing was successful * * @param int $id Image Id * * @param array $stats Smush Stats for the image * * @param array $meta Attachment meta. */ do_action( 'wp_smush_image_optimised', $id, $stats, $meta ); } /** * If webp is active and all images have been converted to webp set a flag to meta. * * @since 3.8.0 */ if ( $should_convert_to_webp && false === $webp_has_error ) { $udir = WP_Smush::get_instance()->core()->mod->webp->get_upload_dir(); // Use the relative path of the first webp image as a flag. $stats['webp_flag'] = substr( $webp_files[0], strlen( $udir['webp_path'] . '/' ) ); } update_post_meta( $id, self::$smushed_meta_key, $stats ); } else { /** * If webp is active and some images have been converted to webp already delete those new webp files. * * @since 3.8.0 */ if ( $should_convert_to_webp && 0 < count( $webp_files ) ) { foreach ( $webp_files as $webp_file ) { unlink( $webp_file ); } } } unset( $stats ); // Unset response. if ( ! empty( $response ) ) { unset( $response ); } return $meta; } /** * Calculate saving percentage from existing and current stats * * @param object|string $stats Stats object. * @param object|string $existing_stats Existing stats object. * * @return float */ public function calculate_percentage( $stats = '', $existing_stats = '' ) { if ( empty( $stats ) || empty( $existing_stats ) ) { return 0; } $size_before = ! empty( $stats->size_before ) ? $stats->size_before : $existing_stats->size_before; $size_after = ! empty( $stats->size_after ) ? $stats->size_after : $existing_stats->size_after; $savings = $size_before - $size_after; if ( $savings > 0 ) { $percentage = ( $savings / $size_before ) * 100; $percentage = $percentage > 0 ? round( $percentage, 2 ) : $percentage; return $percentage; } return 0; } /** * Read the image paths from an attachment's metadata and process each image with wp_smushit(). * * @uses resize_from_meta_data * * @param array $meta Attachment metadata. * @param int $id Attachment ID. * * @return mixed */ public function smush_image( $meta, $id ) { // We need to check if this call originated from Gutenberg and allow only media. if ( ! empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) { $route = untrailingslashit( $GLOBALS['wp']->query_vars['rest_route'] ); // Only allow media routes. if ( empty( $route ) || '/wp/v2/media' !== $route ) { // If not - return image metadata. return $meta; } } $upload_attachment = filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING ); $is_upload_attachment = 'upload-attachment' === $upload_attachment || isset( $_POST['post_id'] ); // Our async task runs when action is upload-attachment and post_id found. So do not run on these conditions. if ( $is_upload_attachment && defined( 'WP_SMUSH_ASYNC' ) && WP_SMUSH_ASYNC ) { return $meta; } // Return directly if not a image. if ( ! wp_attachment_is_image( $id ) ) { return $meta; } // Check if we're restoring the image Or already smushing the image. if ( get_option( "wp-smush-restore-$id", false ) || get_option( "smush-in-progress-$id", false ) ) { return $meta; } /** * Filter: wp_smush_image * * Whether to smush the given attachment id or not * * @param bool $skip Bool, whether to Smush image or not. * @param int $ID Attachment Id, Attachment id of the image being processed. */ if ( ! apply_filters( 'wp_smush_image', true, $id ) ) { return $meta; } // Set a transient to avoid multiple request. update_option( 'smush-in-progress-' . $id, true ); // While uploading from Mobile App or other sources, admin_init action may not fire. // So we need to manually initialize those. WP_Smush::get_instance()->core()->mod->resize->initialize( true ); // Check if auto is enabled. $auto_smush = $this->is_auto_smush_enabled(); // Allow downloading the file from S3 all throughout the process. do_action( 'smush_s3_integration_fetch_file' ); // Get the file path for backup. $attachment_file_path = get_attached_file( $id ); Helper::check_animated_status( $attachment_file_path, $id ); // Take backup. WP_Smush::get_instance()->core()->mod->backup->create_backup( $attachment_file_path, $id ); // Optionally resize images. $meta = WP_Smush::get_instance()->core()->mod->resize->auto_resize( $id, $meta ); // Auto Smush the new image. if ( $auto_smush ) { // Optionally convert PNGs to JPG. $meta = WP_Smush::get_instance()->core()->mod->png2jpg->png_to_jpg( $id, $meta ); /** * Fix for Hostgator. * Check for use of http url (Hostgator mostly). */ $use_http = wp_cache_get( WP_SMUSH_PREFIX . 'use_http', 'smush' ); if ( ! $use_http ) { $use_http = $this->settings->get_setting( WP_SMUSH_PREFIX . 'use_http', false ); wp_cache_add( WP_SMUSH_PREFIX . 'use_http', $use_http, 'smush' ); } if ( $use_http ) { define( 'WP_SMUSH_API_HTTP', 'http://smushpro.wpmudev.org/1.0/' ); } $this->resize_from_meta_data( $meta, $id ); } else { // Remove the smush metadata. delete_post_meta( $id, self::$smushed_meta_key ); } // Delete transient. delete_option( 'smush-in-progress-' . $id ); return $meta; } /** * Smush single images * * @param int $attachment_id Attachment ID. * @param bool $return Return/echo the stats. * * @return array|string */ public function smush_single( $attachment_id, $return = false ) { // If the smushing option is already set, return the status. if ( get_option( "smush-in-progress-{$attachment_id}", false ) || get_option( "wp-smush-restore-{$attachment_id}", false ) ) { // Get the button status. $status = WP_Smush::get_instance()->library()->generate_markup( $attachment_id ); if ( $return ) { return $status; } wp_send_json_success( $status ); } // Set a transient to avoid multiple request. update_option( "smush-in-progress-{$attachment_id}", true ); $attachment_id = absint( (int) $attachment_id ); // Allow downloading the file from S3 all throughout the process. do_action( 'smush_s3_integration_fetch_file' ); // Get the file path for backup. $attachment_file_path = get_attached_file( $attachment_id ); Helper::check_animated_status( $attachment_file_path, $attachment_id ); // Take backup. WP_Smush::get_instance()->core()->mod->backup->create_backup( $attachment_file_path, $attachment_id ); // Get the image metadata from $_POST. $original_meta = ! empty( $_POST['metadata'] ) ? Helper::format_meta_from_post( $_POST['metadata'] ) : ''; $original_meta = empty( $original_meta ) ? wp_get_attachment_metadata( $attachment_id ) : $original_meta; // Send image for resizing, if enabled resize first before any other operation. $updated_meta = $this->resize_image( $attachment_id, $original_meta ); // Convert PNGs to JPG. $updated_meta = WP_Smush::get_instance()->core()->mod->png2jpg->png_to_jpg( $attachment_id, $updated_meta ); $original_meta = ! empty( $updated_meta ) ? $updated_meta : $original_meta; // Smush the image. $smush = $this->resize_from_meta_data( $original_meta, $attachment_id ); /** * When S3 integration is enabled, the wp_update_attachment_metadata below will trigger the * wp_update_attachment_metadata filter WP Offload Media, which in turn will try to re-upload all the files * to an S3 bucket. But, if some sizes are skipped during Smushing, WP Offload Media will print error * messages to debug.log. This will help avoid that. * * @since 3.0 */ add_filter( 'as3cf_attachment_file_paths', array( $this, 'remove_sizes_from_s3_upload' ), 10, 3 ); // Update the details, after smushing, so that latest image is used in hook. wp_update_attachment_metadata( $attachment_id, $original_meta ); // Delete the transient after attachment meta is updated. delete_option( 'smush-in-progress-' . $attachment_id ); // Get the button status. $status = WP_Smush::get_instance()->library()->generate_markup( $attachment_id ); // Send Json response if we are not suppose to return the results. if ( is_wp_error( $smush ) ) { if ( $return ) { return array( 'error' => $smush->get_error_message() ); } wp_send_json_error( array( 'error_msg' => '
', 'show_warning' => (int) $this->show_warning(), ) ); } $this->update_resmush_list( $attachment_id ); \Smush\Core\Core::add_to_smushed_list( $attachment_id ); if ( $return ) { return $status; } wp_send_json_success( $status ); } /** * Returns api key. * * @return mixed */ private function get_api_key() { $api_key = false; // If API key defined manually, get that. if ( defined( 'WPMUDEV_APIKEY' ) && WPMUDEV_APIKEY ) { $api_key = WPMUDEV_APIKEY; } elseif ( class_exists( 'WPMUDEV_Dashboard' ) ) { // If dashboard plugin is active, get API key from db. $api_key = get_site_option( 'wpmudev_apikey' ); } return $api_key; } /** * If auto smush is set to true or not, default is true * * @return int|mixed */ public function is_auto_smush_enabled() { $auto_smush = $this->settings->get( 'auto' ); // Keep the auto smush on by default. if ( ! isset( $auto_smush ) ) { $auto_smush = 1; } return $auto_smush; } /** * Deletes all the backup files when an attachment is deleted * Update resmush List * Update Super Smush image count * * @param int $image_id Attachment ID. * * @return bool */ public function delete_images( $image_id ) { // Update the savings cache. WP_Smush::get_instance()->core()->get_savings( 'resize' ); // Update the savings cache. WP_Smush::get_instance()->core()->get_savings( 'pngjpg' ); // If no image id provided. if ( empty( $image_id ) ) { return false; } // Check and Update resmush list. $resmush_list = get_option( 'wp-smush-resmush-list' ); if ( $resmush_list ) { $this->update_resmush_list( $image_id, 'wp-smush-resmush-list' ); } /** Delete Backups */ // Check if we have any smush data for image. WP_Smush::get_instance()->core()->mod->backup->delete_backup_files( $image_id ); /** * Detete webp. * Run WebP::delete_images always even when the module is deactivated. * @since 3.8.0 */ WP_Smush::get_instance()->core()->mod->webp->delete_images( $image_id , false ); } /** * Calculate saving percentage for a given size stats * * @param object $stats Stats object. * * @return float|int */ private function calculate_percentage_from_stats( $stats ) { if ( empty( $stats ) || ! isset( $stats->size_before, $stats->size_after ) ) { return 0; } $savings = $stats->size_before - $stats->size_after; if ( $savings > 0 ) { $percentage = ( $savings / $stats->size_before ) * 100; $percentage = $percentage > 0 ? round( $percentage, 2 ) : $percentage; return $percentage; } return 0; } /** * Perform the resize operation for the image * * @param int $attachment_id Attachment ID. * @param array $meta Attachment meta. * * @return mixed */ public function resize_image( $attachment_id, $meta ) { if ( empty( $attachment_id ) || empty( $meta ) ) { return $meta; } return WP_Smush::get_instance()->core()->mod->resize->auto_resize( $attachment_id, $meta ); } /** * Send a smush request for the attachment * * @param int $id Attachment ID. */ public function wp_smush_handle_async( $id ) { // If we don't have image id, or the smush is already in progress for the image, return. if ( empty( $id ) || get_option( 'smush-in-progress-' . $id, false ) || get_option( "wp-smush-restore-$id", false ) ) { return; } // If auto Smush is disabled. if ( ! $this->is_auto_smush_enabled() ) { return; } /** * Filter: wp_smush_image * * Whether to smush the given attachment id or not * * @param bool $skip Whether to Smush image or not. * @param int $id Attachment id of the image being processed. */ if ( ! apply_filters( 'wp_smush_image', true, $id ) ) { return; } $this->smush_single( $id, true ); } /** * Send a smush request for the attachment * * @param int $id Attachment ID. * @param array $post_data Post data. */ public function wp_smush_handle_editor_async( $id, $post_data ) { // If we don't have image id, or the smush is already in progress for the image, return. if ( empty( $id ) || get_option( "smush-in-progress-$id", false ) || get_option( "wp-smush-restore-$id", false ) ) { return; } // If auto Smush is disabled. if ( ! $this->is_auto_smush_enabled() ) { return; } /** * Filter: wp_smush_image * * Whether to smush the given attachment id or not * * @param bool $skip Whether to Smush image or not. * @param int $id Attachment ID of the image being processed. */ if ( ! apply_filters( 'wp_smush_image', true, $id ) ) { return; } // If filepath is not set or file doesn't exists. if ( ! isset( $post_data['filepath'] ) || ! file_exists( $post_data['filepath'] ) ) { return; } // Send image for smushing. $res = $this->do_smushit( $post_data['filepath'] ); // Exit if smushing wasn't successful. if ( is_wp_error( $res ) || empty( $res['success'] ) || ! $res['success'] ) { return; } // Update stats if it's the full size image. // Return if it's not the full image size. if ( $post_data['filepath'] != get_attached_file( $post_data['postid'] ) ) { return; } // Get the existing Stats. $smush_stats = get_post_meta( $post_data['postid'], self::$smushed_meta_key, true ); $stats_full = ! empty( $smush_stats['sizes'] ) && ! empty( $smush_stats['sizes']['full'] ) ? $smush_stats['sizes']['full'] : ''; if ( empty( $stats_full ) ) { return; } // store the original image size. $stats_full->size_before = ( ! empty( $stats_full->size_before ) && $stats_full->size_before > $res['data']->before_size ) ? $stats_full->size_before : $res['data']->before_size; $stats_full->size_after = $res['data']->after_size; // Update compression percent and bytes saved for each size. $stats_full->bytes = $stats_full->size_before - $stats_full->size_after; $stats_full->percent = $this->calculate_percentage_from_stats( $stats_full ); $smush_stats['sizes']['full'] = $stats_full; // Update stats. update_post_meta( $post_data['postid'], self::$smushed_meta_key, $smush_stats ); } /** * Remove paths that should not be re-uploaded to an S3 bucket. * * See as3cf_attachment_file_paths filter description for more information. * * @since 3.0 * * @param array $paths Paths to be uploaded to S3 bucket. * @param int $attachment_id Attachment ID. * @param array $meta Image metadata. * * @return mixed */ public function remove_sizes_from_s3_upload( $paths, $attachment_id, $meta ) { // Only run when S3 integration is active. It won't run otherwise, but check just in case. if ( ! $this->settings->get( 's3' ) ) { return $paths; } foreach ( $meta['sizes'] as $size_key => $size_data ) { // Check if registered size is supposed to be Smushed or not. if ( 'full' !== $size_key && $this->skip_image_size( $size_key ) ) { unset( $paths[ $size_key ] ); } } return $paths; } }