Edit File by line
/home/zeestwma/ajeebong.../wp-conte.../plugins/image-op.../modules/optimiza.../classes
File: optimize-image.php
<?php
[0] Fix | Delete
[1] Fix | Delete
namespace ImageOptimization\Modules\Optimization\Classes;
[2] Fix | Delete
[3] Fix | Delete
use ImageOptimization\Classes\File_System\{
[4] Fix | Delete
Exceptions\File_System_Operation_Error,
[5] Fix | Delete
File_System,
[6] Fix | Delete
};
[7] Fix | Delete
use ImageOptimization\Classes\File_Utils;
[8] Fix | Delete
use ImageOptimization\Classes\Image\{
[9] Fix | Delete
Exceptions\Image_Backup_Creation_Error,
[10] Fix | Delete
Exceptions\Invalid_Image_Exception,
[11] Fix | Delete
Image,
[12] Fix | Delete
Image_Backup,
[13] Fix | Delete
Image_Conversion,
[14] Fix | Delete
Image_DB_Update,
[15] Fix | Delete
Image_Dimensions,
[16] Fix | Delete
Image_Meta,
[17] Fix | Delete
Image_Status,
[18] Fix | Delete
WP_Image_Meta
[19] Fix | Delete
};
[20] Fix | Delete
use ImageOptimization\Classes\Logger;
[21] Fix | Delete
use ImageOptimization\Classes\Utils;
[22] Fix | Delete
use ImageOptimization\Classes\Exceptions\Quota_Exceeded_Error;
[23] Fix | Delete
use ImageOptimization\Modules\Optimization\Classes\{
[24] Fix | Delete
Exceptions\Image_File_Already_Exists_Error,
[25] Fix | Delete
Exceptions\Image_Optimization_Error,
[26] Fix | Delete
Exceptions\Bulk_Token_Expired_Error,
[27] Fix | Delete
Exceptions\Image_Already_Optimized_Error,
[28] Fix | Delete
};
[29] Fix | Delete
use ImageOptimization\Modules\Connect\Classes\Exceptions\Connection_Error;
[30] Fix | Delete
use ImageOptimization\Modules\Settings\Classes\Settings;
[31] Fix | Delete
use Throwable;
[32] Fix | Delete
[33] Fix | Delete
use ImageOptimization\Plugin;
[34] Fix | Delete
[35] Fix | Delete
if ( ! defined( 'ABSPATH' ) ) {
[36] Fix | Delete
exit; // Exit if accessed directly.
[37] Fix | Delete
}
[38] Fix | Delete
[39] Fix | Delete
/**
[40] Fix | Delete
* The class is responsible for the optimization logic itself. It gets an image file, runs
[41] Fix | Delete
* backup process if needed, sends a file to the service, stores the result and updates image meta.
[42] Fix | Delete
*
[43] Fix | Delete
* This class is used by manual, bulk and on-upload optimization flows.
[44] Fix | Delete
*/
[45] Fix | Delete
class Optimize_Image {
[46] Fix | Delete
public const IMAGE_OPTIMIZE_ENDPOINT = 'image/optimize';
[47] Fix | Delete
[48] Fix | Delete
protected ?Image $image;
[49] Fix | Delete
protected WP_Image_Meta $wp_meta;
[50] Fix | Delete
protected string $initiator;
[51] Fix | Delete
protected ?string $bulk_token;
[52] Fix | Delete
private string $current_image_path;
[53] Fix | Delete
private string $current_image_size;
[54] Fix | Delete
private bool $keep_backups;
[55] Fix | Delete
private array $current_size_duplicates;
[56] Fix | Delete
protected Image_Conversion $image_conversion;
[57] Fix | Delete
private bool $is_reoptimize;
[58] Fix | Delete
[59] Fix | Delete
/**
[60] Fix | Delete
* @throws Quota_Exceeded_Error|Connection_Error|Bulk_Token_Expired_Error|Image_File_Already_Exists_Error|Image_Optimization_Error
[61] Fix | Delete
*/
[62] Fix | Delete
public function optimize(): void {
[63] Fix | Delete
$sizes_enabled = Settings::get( Settings::CUSTOM_SIZES_OPTION_NAME );
[64] Fix | Delete
$sizes_exist = $this->wp_meta->get_size_keys();
[65] Fix | Delete
[66] Fix | Delete
Logger::debug( "Start optimization of {$this->image->get_id()}" );
[67] Fix | Delete
[68] Fix | Delete
foreach ( $sizes_exist as $size_exist ) {
[69] Fix | Delete
// If some image sizes optimization is disabled in settings, we check if the current one is still enabled
[70] Fix | Delete
if (
[71] Fix | Delete
'all' !== $sizes_enabled &&
[72] Fix | Delete
Image::SIZE_FULL !== $size_exist &&
[73] Fix | Delete
! in_array( $size_exist, $sizes_enabled, true )
[74] Fix | Delete
) {
[75] Fix | Delete
continue;
[76] Fix | Delete
}
[77] Fix | Delete
[78] Fix | Delete
// Elementor editor generates thumbnails we don't need to optimize.
[79] Fix | Delete
if ( str_starts_with( $size_exist, 'elementor_' ) ) {
[80] Fix | Delete
continue;
[81] Fix | Delete
}
[82] Fix | Delete
[83] Fix | Delete
$image_meta = new Image_Meta( $this->image->get_id() );
[84] Fix | Delete
[85] Fix | Delete
// If the current size was already optimized -- ignore it.
[86] Fix | Delete
if ( ! $this->is_reoptimize && in_array( $size_exist, $image_meta->get_optimized_sizes(), true ) ) {
[87] Fix | Delete
Logger::debug( "Size `$size_exist` is already optimized" );
[88] Fix | Delete
[89] Fix | Delete
continue;
[90] Fix | Delete
}
[91] Fix | Delete
[92] Fix | Delete
if ( ! file_exists( $this->image->get_file_path( $size_exist ) ) ) {
[93] Fix | Delete
Logger::debug( "Can't access file for size `$size_exist`" );
[94] Fix | Delete
[95] Fix | Delete
continue;
[96] Fix | Delete
}
[97] Fix | Delete
[98] Fix | Delete
$this->current_image_size = $size_exist;
[99] Fix | Delete
$this->current_size_duplicates = $this->wp_meta->get_size_duplicates( $size_exist );
[100] Fix | Delete
$this->current_image_path = $this->image->get_file_path( $size_exist );
[101] Fix | Delete
[102] Fix | Delete
$this->optimize_current_size();
[103] Fix | Delete
[104] Fix | Delete
$this->current_image_size = '';
[105] Fix | Delete
$this->current_size_duplicates = [];
[106] Fix | Delete
$this->current_image_path = '';
[107] Fix | Delete
}
[108] Fix | Delete
[109] Fix | Delete
$this->mark_as_optimized();
[110] Fix | Delete
[111] Fix | Delete
if ( ! $this->keep_backups ) {
[112] Fix | Delete
Image_Backup::remove( $this->image->get_id() );
[113] Fix | Delete
}
[114] Fix | Delete
[115] Fix | Delete
Logger::debug( "End optimization of {$this->image->get_id()}" );
[116] Fix | Delete
}
[117] Fix | Delete
[118] Fix | Delete
private function optimize_current_size(): void {
[119] Fix | Delete
try {
[120] Fix | Delete
$original_path = $this->current_image_path;
[121] Fix | Delete
$response = $this->send_file();
[122] Fix | Delete
[123] Fix | Delete
$optimized_size = (int) $response->optimizedSize; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
[124] Fix | Delete
$optimized_image_binary = base64_decode( $response->image, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
[125] Fix | Delete
[126] Fix | Delete
$this->replace_image_file( $optimized_image_binary );
[127] Fix | Delete
$this->update_attachment_meta( $optimized_size );
[128] Fix | Delete
[129] Fix | Delete
if ( $original_path !== $this->current_image_path ) {
[130] Fix | Delete
$this->update_posts( $original_path, $this->current_image_path );
[131] Fix | Delete
}
[132] Fix | Delete
[133] Fix | Delete
// This should only be updated after meta
[134] Fix | Delete
$this->update_attachment_post();
[135] Fix | Delete
} catch ( Image_Already_Optimized_Error $iao ) {
[136] Fix | Delete
// If we can't optimize it further, just update the meta
[137] Fix | Delete
$original_size = $this->wp_meta->get_file_size( $this->current_image_size )
[138] Fix | Delete
?? File_System::size( $this->image->get_file_path( $this->current_image_size ) );
[139] Fix | Delete
[140] Fix | Delete
$this->update_attachment_meta( $original_size, true );
[141] Fix | Delete
$this->update_attachment_post( true );
[142] Fix | Delete
} catch ( Bulk_Token_Expired_Error | Quota_Exceeded_Error | Connection_Error | Image_File_Already_Exists_Error $e ) {
[143] Fix | Delete
throw $e;
[144] Fix | Delete
} catch ( Throwable $t ) {
[145] Fix | Delete
// In case of anything else
[146] Fix | Delete
throw new Image_Optimization_Error( esc_html( $t->getMessage() ) );
[147] Fix | Delete
}
[148] Fix | Delete
}
[149] Fix | Delete
[150] Fix | Delete
private function send_file() {
[151] Fix | Delete
$connect_status = Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->get_connect_status();
[152] Fix | Delete
$headers = [
[153] Fix | Delete
'access_token' => $connect_status->access_token ?? '',
[154] Fix | Delete
];
[155] Fix | Delete
[156] Fix | Delete
if ( $this->bulk_token ) {
[157] Fix | Delete
$headers['x-elementor-bulk-token'] = $this->bulk_token;
[158] Fix | Delete
}
[159] Fix | Delete
[160] Fix | Delete
$optimization_options = [
[161] Fix | Delete
'compression_level' => Settings::get( Settings::COMPRESSION_LEVEL_OPTION_NAME ),
[162] Fix | Delete
'convert_to_format' => $this->image_conversion->get_current_conversion_option(),
[163] Fix | Delete
'strip_exif' => Settings::get( Settings::STRIP_EXIF_METADATA_OPTION_NAME ),
[164] Fix | Delete
];
[165] Fix | Delete
[166] Fix | Delete
if ( Settings::get( Settings::RESIZE_LARGER_IMAGES_OPTION_NAME ) ) {
[167] Fix | Delete
$optimization_options['resize'] = Settings::get( Settings::RESIZE_LARGER_IMAGES_SIZE_OPTION_NAME );
[168] Fix | Delete
}
[169] Fix | Delete
[170] Fix | Delete
$image_key = wp_generate_password( 15, false );
[171] Fix | Delete
[172] Fix | Delete
$response = Utils::get_api_client()->make_request(
[173] Fix | Delete
'POST',
[174] Fix | Delete
self::IMAGE_OPTIMIZE_ENDPOINT,
[175] Fix | Delete
[
[176] Fix | Delete
'initiator' => $this->initiator,
[177] Fix | Delete
'image_url' => $this->image->get_url( $this->current_image_size ),
[178] Fix | Delete
'image_key' => $image_key,
[179] Fix | Delete
'checksum' => md5_file( $this->current_image_path ),
[180] Fix | Delete
'attachment_id' => $this->image->get_id(),
[181] Fix | Delete
'attachment_parent_id' => Image::SIZE_FULL === $this->current_image_size ? 0 : $this->image->get_id(),
[182] Fix | Delete
'image_optimization_settings' => base64_encode( wp_json_encode( $optimization_options ) ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
[183] Fix | Delete
],
[184] Fix | Delete
$headers,
[185] Fix | Delete
$this->current_image_path,
[186] Fix | Delete
'image'
[187] Fix | Delete
);
[188] Fix | Delete
[189] Fix | Delete
if ( isset( $response->stats ) ) {
[190] Fix | Delete
Plugin::instance()->modules_manager->get_modules( 'connect-manager' )->connect_instance->update_usage_data( $response->stats );
[191] Fix | Delete
}
[192] Fix | Delete
[193] Fix | Delete
if ( ! isset( $response->imageKey ) || $image_key !== $response->imageKey ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
[194] Fix | Delete
Logger::error( "Image key must be $image_key, instead got $response->imageKey" );
[195] Fix | Delete
[196] Fix | Delete
throw new Image_Optimization_Error( esc_html__( 'Service response is incorrect', 'image-optimization' ) );
[197] Fix | Delete
}
[198] Fix | Delete
[199] Fix | Delete
$received_file_hash = md5( base64_decode( $response->image, true ) );
[200] Fix | Delete
[201] Fix | Delete
if ( ! isset( $response->checksum ) || $received_file_hash !== $response->checksum ) {
[202] Fix | Delete
Logger::error( "Image key must be $response->checksum, instead calculated $received_file_hash" );
[203] Fix | Delete
[204] Fix | Delete
throw new Image_Optimization_Error( esc_html__( 'Service response is incorrect', 'image-optimization' ) );
[205] Fix | Delete
}
[206] Fix | Delete
[207] Fix | Delete
return $response;
[208] Fix | Delete
}
[209] Fix | Delete
[210] Fix | Delete
/**
[211] Fix | Delete
* @throws File_System_Operation_Error|Image_Backup_Creation_Error|Image_File_Already_Exists_Error
[212] Fix | Delete
*/
[213] Fix | Delete
private function replace_image_file( string $file_data ): void {
[214] Fix | Delete
$path = $this->current_image_path;
[215] Fix | Delete
[216] Fix | Delete
// If we have backups disabled, we want to make sure we can download and save new file before we
[217] Fix | Delete
// remove an existing one.
[218] Fix | Delete
$tmp_path = File_Utils::replace_extension( $path, 'tmp' );
[219] Fix | Delete
[220] Fix | Delete
File_System::put_contents( $tmp_path, $file_data );
[221] Fix | Delete
[222] Fix | Delete
if ( $this->image_conversion->is_enabled() ) {
[223] Fix | Delete
$converted_path = File_Utils::replace_extension( $tmp_path, $this->image_conversion->get_current_file_extension() );
[224] Fix | Delete
$original_is_already_converted = strtolower( $path ) === strtolower( $converted_path );
[225] Fix | Delete
[226] Fix | Delete
if ( ! $original_is_already_converted && File_System::exists( $converted_path ) ) {
[227] Fix | Delete
throw new Image_File_Already_Exists_Error();
[228] Fix | Delete
}
[229] Fix | Delete
[230] Fix | Delete
// We want to keep both original as a fallback and optimized webp to prevent 404s
[231] Fix | Delete
if ( ! $original_is_already_converted ) {
[232] Fix | Delete
$this->keep_backups = true;
[233] Fix | Delete
[234] Fix | Delete
( new Image_Meta( $this->image->get_id() ) )
[235] Fix | Delete
->set_image_backup_path( $this->current_image_size, $this->current_image_path )
[236] Fix | Delete
->save();
[237] Fix | Delete
}
[238] Fix | Delete
[239] Fix | Delete
if ( $original_is_already_converted ) {
[240] Fix | Delete
Image_Backup::create( $this->image->get_id(), $this->current_image_size, $this->current_image_path );
[241] Fix | Delete
}
[242] Fix | Delete
[243] Fix | Delete
File_System::move( $tmp_path, $converted_path, true );
[244] Fix | Delete
[245] Fix | Delete
$path = $converted_path;
[246] Fix | Delete
} else {
[247] Fix | Delete
Image_Backup::create( $this->image->get_id(), $this->current_image_size, $this->current_image_path );
[248] Fix | Delete
[249] Fix | Delete
File_System::move( $tmp_path, $path, true );
[250] Fix | Delete
}
[251] Fix | Delete
[252] Fix | Delete
if ( Image::SIZE_FULL === $this->current_image_size ) {
[253] Fix | Delete
// Drop WP caches
[254] Fix | Delete
update_attached_file( $this->image->get_id(), $path );
[255] Fix | Delete
}
[256] Fix | Delete
[257] Fix | Delete
// Updating to the correct value
[258] Fix | Delete
$this->current_image_path = $path;
[259] Fix | Delete
}
[260] Fix | Delete
[261] Fix | Delete
/**
[262] Fix | Delete
* Updates attachment records in the `wp_posts` table.
[263] Fix | Delete
*
[264] Fix | Delete
* @return void
[265] Fix | Delete
*/
[266] Fix | Delete
private function update_attachment_post( ?bool $is_fully_optimized = false ) {
[267] Fix | Delete
$update_query = [];
[268] Fix | Delete
[269] Fix | Delete
if ( $this->image_conversion->is_enabled() && ! $is_fully_optimized ) {
[270] Fix | Delete
$attachment_object = $this->image->get_attachment_object();
[271] Fix | Delete
[272] Fix | Delete
$update_query['guid'] = File_Utils::replace_extension(
[273] Fix | Delete
$attachment_object->guid,
[274] Fix | Delete
$this->image_conversion->get_current_file_extension()
[275] Fix | Delete
);
[276] Fix | Delete
[277] Fix | Delete
$update_query['post_mime_type'] = $this->image_conversion->get_current_mime_type();
[278] Fix | Delete
}
[279] Fix | Delete
[280] Fix | Delete
$update_query['post_modified'] = current_time( 'mysql' );
[281] Fix | Delete
$update_query['post_modified_gmt'] = current_time( 'mysql', true );
[282] Fix | Delete
[283] Fix | Delete
$this->image->update_attachment( $update_query );
[284] Fix | Delete
}
[285] Fix | Delete
[286] Fix | Delete
/**
[287] Fix | Delete
* Updates attachment records in the `wp_postmeta` table.
[288] Fix | Delete
*
[289] Fix | Delete
* @param int $optimized_size
[290] Fix | Delete
* @param bool|null $is_fully_optimized
[291] Fix | Delete
*
[292] Fix | Delete
* @return void
[293] Fix | Delete
*/
[294] Fix | Delete
private function update_attachment_meta( int $optimized_size, ?bool $is_fully_optimized = false ) {
[295] Fix | Delete
$meta = new Image_Meta( $this->image->get_id() );
[296] Fix | Delete
$dimensions = Image_Dimensions::get_by_path( $this->current_image_path );
[297] Fix | Delete
[298] Fix | Delete
$sizes_to_update = [ $this->current_image_size, ...$this->current_size_duplicates ];
[299] Fix | Delete
[300] Fix | Delete
foreach ( $sizes_to_update as $size ) {
[301] Fix | Delete
$meta
[302] Fix | Delete
->set_compression_level( Settings::get( Settings::COMPRESSION_LEVEL_OPTION_NAME ) )
[303] Fix | Delete
->add_optimized_size( $size )
[304] Fix | Delete
->add_original_data( $size, $this->wp_meta->get_size_data( $size ) );
[305] Fix | Delete
[306] Fix | Delete
$this->wp_meta
[307] Fix | Delete
->set_width( $size, $dimensions->width )
[308] Fix | Delete
->set_height( $size, $dimensions->height )
[309] Fix | Delete
->set_file_size( $size, $optimized_size );
[310] Fix | Delete
[311] Fix | Delete
if ( $this->image_conversion->is_enabled() && ! $is_fully_optimized ) {
[312] Fix | Delete
$this->wp_meta
[313] Fix | Delete
->set_file_path( $size, $this->current_image_path )
[314] Fix | Delete
->set_mime_type( $size, $this->image_conversion->get_current_mime_type() );
[315] Fix | Delete
}
[316] Fix | Delete
}
[317] Fix | Delete
[318] Fix | Delete
$meta->save();
[319] Fix | Delete
$this->wp_meta->save();
[320] Fix | Delete
}
[321] Fix | Delete
[322] Fix | Delete
/**
[323] Fix | Delete
* If we change an image extension, we should walk through the wp_posts table and update all the
[324] Fix | Delete
* hardcoded image links to prevent 404s.
[325] Fix | Delete
*
[326] Fix | Delete
* @param string $old_path Previous image path
[327] Fix | Delete
* @param string $new_path Current image path
[328] Fix | Delete
*
[329] Fix | Delete
* @return void
[330] Fix | Delete
*/
[331] Fix | Delete
private function update_posts( string $old_path, string $new_path ) {
[332] Fix | Delete
Image_DB_Update::update_posts_table_urls(
[333] Fix | Delete
File_Utils::get_url_from_path( $old_path ),
[334] Fix | Delete
File_Utils::get_url_from_path( $new_path )
[335] Fix | Delete
);
[336] Fix | Delete
}
[337] Fix | Delete
[338] Fix | Delete
/**
[339] Fix | Delete
* Changes image status after all image sizes were optimized.
[340] Fix | Delete
*
[341] Fix | Delete
* @return void
[342] Fix | Delete
*/
[343] Fix | Delete
private function mark_as_optimized() {
[344] Fix | Delete
( new Image_Meta( $this->image->get_id() ) )
[345] Fix | Delete
->set_status( Image_Status::OPTIMIZED )
[346] Fix | Delete
->set_error_type( null )
[347] Fix | Delete
->save();
[348] Fix | Delete
}
[349] Fix | Delete
[350] Fix | Delete
/**
[351] Fix | Delete
* @throws Invalid_Image_Exception
[352] Fix | Delete
*/
[353] Fix | Delete
public function __construct( int $image_id, string $initiator, ?string $bulk_token = null, ?bool $is_reoptimize = false ) {
[354] Fix | Delete
$this->image = new Image( $image_id );
[355] Fix | Delete
$this->wp_meta = new WP_Image_Meta( $image_id, $this->image );
[356] Fix | Delete
$this->initiator = $initiator;
[357] Fix | Delete
$this->bulk_token = $bulk_token;
[358] Fix | Delete
$this->is_reoptimize = $is_reoptimize;
[359] Fix | Delete
$this->image_conversion = new Image_Conversion();
[360] Fix | Delete
$this->keep_backups = Settings::get( Settings::BACKUP_ORIGINAL_IMAGES_OPTION_NAME );
[361] Fix | Delete
}
[362] Fix | Delete
}
[363] Fix | Delete
[364] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function