engines = $engines; // Auto-convert on upload / metadata regeneration. add_filter( 'wp_generate_attachment_metadata', array( $this, 'auto_convert' ), 20, 2 ); // Clean up variant files when an attachment is deleted. add_action( 'delete_attachment', array( $this, 'on_attachment_delete' ) ); } /** * Auto convert new/regenerated attachments. * * @param array $metadata Attachment metadata. * @param int $attachment_id Attachment ID. * @return array */ public function auto_convert( $metadata, $attachment_id ) { if ( ! ADEE_Plugin::get_setting( 'auto_convert' ) ) { return $metadata; } if ( ! wp_attachment_is_image( $attachment_id ) ) { return $metadata; } $this->convert_attachment( $attachment_id ); return $metadata; } /** * Remove variant files on attachment delete. * * @param int $attachment_id Attachment ID. * @return void */ public function on_attachment_delete( $attachment_id ) { $old = $this->get_variants( $attachment_id ); if ( empty( $old ) ) { return; } $this->delete_variant_files( $old ); $this->update_stats( $old, array() ); } /** * Get stored variants for an attachment. * * @param int $attachment_id Attachment ID. * @return array */ public function get_variants( $attachment_id ) { $variants = get_post_meta( $attachment_id, self::META_KEY, true ); return is_array( $variants ) ? $variants : array(); } /** * Absolute paths for every image size of an attachment. * * @param int $attachment_id Attachment ID. * @return array size => absolute path. */ public function sizes_to_convert( $attachment_id ) { $list = array(); $full = get_attached_file( $attachment_id ); if ( $full && file_exists( $full ) ) { $list['full'] = $full; $meta = wp_get_attachment_metadata( $attachment_id ); if ( ! empty( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) { $dir = dirname( $full ); foreach ( $meta['sizes'] as $size => $data ) { if ( empty( $data['file'] ) || isset( $list[ $size ] ) ) { continue; } $path = $dir . '/' . $data['file']; if ( file_exists( $path ) ) { $list[ $size ] = $path; } } } } return $list; } /** * Convert every size of an attachment to configured formats. * * @param int $attachment_id Attachment ID. * @param array $args { * @type array|null $formats Explicit formats, e.g. array('webp'). * @type bool $skip_existing Skip when variants already exist. * } * @return array Report: status (ok|skipped|error), variants, errors, reason. */ public function convert_attachment( $attachment_id, $args = array() ) { $args = wp_parse_args( $args, array( 'formats' => null, 'skip_existing' => false, ) ); if ( ! wp_attachment_is_image( $attachment_id ) ) { return array( 'status' => 'skipped', 'reason' => 'not_image' ); } $old_variants = $this->get_variants( $attachment_id ); if ( $args['skip_existing'] && ! empty( $old_variants ) ) { return array( 'status' => 'skipped', 'reason' => 'already_converted' ); } $settings = ADEE_Plugin::settings(); $want = is_array( $args['formats'] ) && ! empty( $args['formats'] ) ? $args['formats'] : array(); if ( empty( $want ) ) { if ( ! empty( $settings['convert_webp'] ) ) { $want[] = 'webp'; } if ( ! empty( $settings['convert_avif'] ) ) { $want[] = 'avif'; } } // Animated GIFs: only WebP (static frame) to avoid heavy processing. $mime = get_post_mime_type( $attachment_id ); if ( 'image/gif' === $mime ) { $want = array_values( array_intersect( $want, array( 'webp' ) ) ); if ( empty( $want ) ) { return array( 'status' => 'skipped', 'reason' => 'gif_webp_only' ); } } $sizes = $this->sizes_to_convert( $attachment_id ); if ( empty( $sizes ) ) { return array( 'status' => 'skipped', 'reason' => 'no_files' ); } $new_variants = array(); $errors = array(); foreach ( $sizes as $size => $path ) { foreach ( $want as $format ) { $engine = $this->engines->pick( $format ); if ( ! $engine ) { continue; } $res = $this->convert_file( $path, $format, $engine ); if ( 'ok' === $res['status'] ) { $new_variants[ $size ][ $format ] = array( 'file' => $this->rel_path( $res['file'] ), 'bytes' => (int) $res['bytes'], 'src' => (int) $res['src_bytes'], ); } elseif ( 'error' === $res['status'] ) { $errors[] = basename( $path ) . ': ' . $res['reason']; } } } // Remove stale files from earlier conversions. $this->cleanup_stale( $old_variants, $new_variants ); if ( ! empty( $new_variants ) ) { update_post_meta( $attachment_id, self::META_KEY, $new_variants ); } else { delete_post_meta( $attachment_id, self::META_KEY ); } $this->update_stats( $old_variants, $new_variants ); if ( empty( $new_variants ) ) { return array( 'status' => 'error', 'reason' => $errors ? implode( '; ', $errors ) : 'no_engine_or_no_benefit', 'errors' => $errors, ); } return array( 'status' => 'ok', 'variants' => $new_variants, 'errors' => $errors, ); } /** * Convert a single image file to a format. * * @param string $src Source absolute path. * @param string $format webp|avif. * @param string $engine gd|imagick|cli. * @return array status, file, bytes, src_bytes, reason. */ public function convert_file( $src, $format, $engine ) { $src_bytes = @filesize( $src ); if ( ! $src_bytes ) { return array( 'status' => 'error', 'reason' => 'unreadable_source' ); } $dir = dirname( $src ); $name = pathinfo( $src, PATHINFO_FILENAME ); $dst = $dir . '/' . $name . '.' . $format; if ( file_exists( $dst ) ) { wp_delete_file( $dst ); } $quality = ( 'webp' === $format ) ? (int) ADEE_Plugin::get_setting( 'webp_quality' ) : (int) ADEE_Plugin::get_setting( 'avif_quality' ); $quality = min( 100, max( 10, $quality ) ); $ok = false; switch ( $engine ) { case 'gd': $ok = $this->convert_gd( $src, $dst, $format, $quality ); break; case 'imagick': $ok = $this->convert_imagick( $src, $dst, $format, $quality ); break; case 'cli': $ok = $this->convert_cli( $src, $dst, $format, $quality ); break; } if ( ! $ok || ! file_exists( $dst ) ) { return array( 'status' => 'error', 'reason' => 'engine_failed' ); } $out_bytes = @filesize( $dst ); if ( ! $out_bytes || $out_bytes < 100 ) { wp_delete_file( $dst ); return array( 'status' => 'error', 'reason' => 'empty_output' ); } // Only keep variants that are actually smaller than the original. if ( $out_bytes >= $src_bytes ) { wp_delete_file( $dst ); return array( 'status' => 'skipped', 'reason' => 'larger_than_original' ); } return array( 'status' => 'ok', 'file' => $dst, 'bytes' => (int) $out_bytes, 'src_bytes' => (int) $src_bytes, ); } /** * GD conversion. * * @param string $src Source. * @param string $dst Destination. * @param string $format webp|avif. * @param int $quality Quality. * @return bool */ private function convert_gd( $src, $dst, $format, $quality ) { if ( 'webp' === $format && ! function_exists( 'imagewebp' ) ) { return false; } if ( 'avif' === $format && ! function_exists( 'imageavif' ) ) { return false; } $data = @file_get_contents( $src ); // phpcs:ignore WordPress.WP.AlternativeFunctions if ( ! $data ) { return false; } $img = @imagecreatefromstring( $data ); if ( ! $img ) { return false; } if ( function_exists( 'imagepalettetotruecolor' ) ) { @imagepalettetotruecolor( $img ); } if ( function_exists( 'imagealphablending' ) ) { @imagealphablending( $img, true ); } if ( function_exists( 'imagesavealpha' ) ) { @imagesavealpha( $img, true ); } $ok = ( 'webp' === $format ) ? @imagewebp( $img, $dst, $quality ) : @imageavif( $img, $dst, $quality ); if ( is_resource( $img ) || ( is_object( $img ) && $img instanceof GdImage ) ) { imagedestroy( $img ); } return (bool) $ok; } /** * Imagick conversion. * * @param string $src Source. * @param string $dst Destination. * @param string $format webp|avif. * @param int $quality Quality. * @return bool */ private function convert_imagick( $src, $dst, $format, $quality ) { if ( ! class_exists( 'Imagick' ) ) { return false; } try { $imagick = new Imagick( $src ); $imagick->setImageFormat( strtoupper( $format ) ); $imagick->setImageCompressionQuality( $quality ); $ok = $imagick->writeImage( $dst ); $imagick->clear(); $imagick->destroy(); return (bool) $ok; } catch ( Exception $e ) { return false; } } /** * CLI conversion via cwebp / avifenc. * * @param string $src Source. * @param string $dst Destination. * @param string $format webp|avif. * @param int $quality Quality. * @return bool */ private function convert_cli( $src, $dst, $format, $quality ) { $binaries = $this->engines->detect(); if ( 'webp' === $format ) { $bin = $binaries['cli_cwebp']; if ( ! $bin ) { return false; } $cmd = escapeshellarg( $bin ) . ' -quiet -q ' . (int) $quality . ' ' . escapeshellarg( $src ) . ' -o ' . escapeshellarg( $dst ) . ' 2>&1'; } else { $bin = $binaries['cli_avifenc']; if ( ! $bin ) { return false; } $cmd = escapeshellarg( $bin ) . ' -q ' . (int) $quality . ' -s 6 -j 2 ' . escapeshellarg( $src ) . ' ' . escapeshellarg( $dst ) . ' 2>&1'; } $output = array(); $code = 1; @exec( $cmd, $output, $code ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions return ( 0 === $code && file_exists( $dst ) ); } /** * Restore (delete variants) for one attachment. * * @param int $attachment_id Attachment ID. * @return bool */ public function restore_attachment( $attachment_id ) { $old = $this->get_variants( $attachment_id ); if ( empty( $old ) ) { return false; } $this->delete_variant_files( $old ); delete_post_meta( $attachment_id, self::META_KEY ); $this->update_stats( $old, array() ); return true; } /** * Restore up to $limit attachments; returns number restored. * * @param int $limit Max attachments per run. * @return int */ public function restore_all( $limit = 200 ) { $query = new WP_Query( array( 'post_type' => 'attachment', 'post_status' => 'any', 'posts_per_page' => $limit, 'fields' => 'ids', 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, 'meta_key' => self::META_KEY, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Indexed meta_key lookup via the WP query API. ) ); $count = 0; foreach ( $query->posts as $id ) { if ( $this->restore_attachment( (int) $id ) ) { $count++; } } return $count; } /** * Delete the files referenced by a variants array. * * @param array $variants Variants meta. * @return void */ private function delete_variant_files( $variants ) { foreach ( $variants as $sizes ) { if ( ! is_array( $sizes ) ) { continue; } foreach ( $sizes as $data ) { if ( ! is_array( $data ) || empty( $data['file'] ) ) { continue; } $abs = $this->abs_path( $data['file'] ); if ( $abs && file_exists( $abs ) ) { wp_delete_file( $abs ); } } } } /** * Remove stale variants no longer regenerated. * * @param array $old Old variants. * @param array $new New variants. * @return void */ private function cleanup_stale( $old, $new ) { foreach ( $old as $size => $formats ) { if ( ! is_array( $formats ) ) { continue; } foreach ( $formats as $format => $data ) { $still_exists = isset( $new[ $size ][ $format ] ) && isset( $new[ $size ][ $format ]['file'] ) && $new[ $size ][ $format ]['file'] === ( isset( $data['file'] ) ? $data['file'] : '' ); if ( $still_exists ) { continue; } if ( ! empty( $data['file'] ) ) { $abs = $this->abs_path( $data['file'] ); if ( $abs && file_exists( $abs ) ) { wp_delete_file( $abs ); } } } } } /** * Absolute path for an uploads-relative path. * * @param string $rel Relative path. * @return string */ private function abs_path( $rel ) { $up = wp_get_upload_dir(); $basedir = isset( $up['basedir'] ) ? rtrim( $up['basedir'], '/' ) : ''; if ( ! $basedir ) { return ''; } if ( 0 === strpos( $rel, $basedir ) ) { return $rel; } return $basedir . '/' . ltrim( $rel, '/' ); } /** * Uploads-relative path for an absolute path. * * @param string $file Absolute path. * @return string */ private function rel_path( $file ) { $up = wp_get_upload_dir(); $basedir = isset( $up['basedir'] ) ? rtrim( $up['basedir'], '/' ) : ''; if ( $basedir && 0 === strpos( $file, $basedir . '/' ) ) { return substr( $file, strlen( $basedir ) + 1 ); } return $file; } /** * Totals helper for a variants array. * * @param array $variants Variants meta. * @return array variants, src, out. */ private function totals( $variants ) { $variants_count = 0; $src = 0; $out = 0; foreach ( $variants as $sizes ) { if ( ! is_array( $sizes ) ) { continue; } $size_src = 0; foreach ( $sizes as $data ) { if ( ! is_array( $data ) ) { continue; } $variants_count++; $out += isset( $data['bytes'] ) ? (int) $data['bytes'] : 0; if ( isset( $data['src'] ) ) { $size_src = (int) $data['src']; } } $src += $size_src; } return array( 'variants' => $variants_count, 'src' => $src, 'out' => $out, ); } /** * Apply delta between old and new variants to global stats. * * @param array $old Old variants. * @param array $new New variants. * @return void */ private function update_stats( $old, $new ) { $stats = $this->stats(); $o = $this->totals( is_array( $old ) ? $old : array() ); $n = $this->totals( is_array( $new ) ? $new : array() ); $stats['variants'] = max( 0, (int) $stats['variants'] - $o['variants'] + $n['variants'] ); $stats['src_bytes'] = max( 0, (int) $stats['src_bytes'] - $o['src'] + $n['src'] ); $stats['out_bytes'] = max( 0, (int) $stats['out_bytes'] - $o['out'] + $n['out'] ); update_option( 'adee_stats', $stats, false ); } /** * Global stats. * * @return array */ public function stats() { $stats = get_option( 'adee_stats', array() ); if ( ! is_array( $stats ) ) { $stats = array(); } return wp_parse_args( $stats, array( 'variants' => 0, 'src_bytes' => 0, 'out_bytes' => 0, ) ); } /** * Recompute stats from all variant meta (slow but exact). * * @return array */ public function recalculate_stats() { $query = new WP_Query( array( 'post_type' => 'attachment', 'post_status' => 'any', 'posts_per_page' => 50000, 'fields' => 'ids', 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, 'meta_key' => self::META_KEY, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Indexed meta_key lookup via the WP query API. ) ); $variants = 0; $src = 0; $out = 0; foreach ( $query->posts as $id ) { $t = $this->totals( $this->get_variants( (int) $id ) ); $variants += $t['variants']; $src += $t['src']; $out += $t['out']; } $stats = array( 'variants' => $variants, 'src_bytes' => $src, 'out_bytes' => $out, ); update_option( 'adee_stats', $stats, false ); return $stats; } /** * Human readable bytes. * * @param int $bytes Bytes. * @return string */ public static function human_bytes( $bytes ) { $bytes = max( 0, (int) $bytes ); $units = array( 'B', 'KB', 'MB', 'GB' ); $i = 0; $value = (float) $bytes; while ( $value >= 1024 && $i < count( $units ) - 1 ) { $value /= 1024; $i++; } return round( $value, $i ? 1 : 0 ) . ' ' . $units[ $i ]; } }