diff --git a/README.md b/README.md index 273f4fef..e77d3ddb 100755 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ -# TinyPNG - JPEG, PNG & WebP image compression for WordPress +# TinyPNG - JPEG, PNG, WebP, AVIF & JPEG XL image compression for WordPress [![Integration Tests](https://github.com/tinify/wordpress-plugin/actions/workflows/integration-tests.yml/badge.svg)](https://github.com/tinify/wordpress-plugin/actions/workflows/integration-tests.yml) [![Check and Test](https://github.com/tinify/wordpress-plugin/actions/workflows/check-test.yml/badge.svg)](https://github.com/tinify/wordpress-plugin/actions/workflows/check-test.yml) -Make your website faster by optimizing your JPEG, PNG, and WebP images. +Make your website faster by optimizing your JPEG, PNG, WebP, AVIF and JPEG XL images. This plugin automatically optimizes your images by integrating with the popular image compression services TinyJPG and TinyPNG. You can download the diff --git a/readme.txt b/readme.txt index be60c8c7..5caee57e 100644 --- a/readme.txt +++ b/readme.txt @@ -8,18 +8,18 @@ Stable tag: 3.8.1 License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html -Speed up your website. Optimize your JPEG, PNG, and WebP images automatically with TinyPNG. +Speed up your website. Optimize your JPEG, PNG, WebP, AVIF and JPEG XL images automatically with TinyPNG. == Description == -The best & easiest image compression plugin for WordPress. Speed up your website by compressing and converting your images with TinyPNG for WordPress. Improve your websites’ performance by significantly reducing file sizes without noticeable quality loss. Support for WebP, AVIF, JPG and PNG formats. +The best & easiest image compression plugin for WordPress. Speed up your website by compressing and converting your images with TinyPNG for WordPress. Improve your websites’ performance by significantly reducing file sizes without noticeable quality loss. Support for WebP, AVIF, JPEG XL, JPG and PNG formats. Start optimizing your images today to boost SEO, improve your PageSpeed scores, save bandwidth and enhance your website’s user experience. = Why TinyPNG? = * Next-gen format conversion, convert images to WebP and AVIF for even smaller files (NEW) * Smart compression algorithm, reduce image file sizes without visible quality loss -* Broad format support, supports AVIF, WebP, PNG, animated PNG (APNG) and JPG. +* Broad format support, supports AVIF, JPEG XL, WebP, PNG, animated PNG (APNG) and JPG. * Automatic image compression, compresses new images on upload. * Bulk optimization, optimize your full media library in just one click. * Individual image control, optimize a single image straight from your media library. @@ -43,9 +43,11 @@ Google’s PageSpeed Insights and other tools strongly recommend serving images With the TinyPNG WordPress plugin, your images can be automatically converted to AVIF or WebP when you upload them. No extra steps are required. +AVIF images are already in a next-gen format, so they are compressed but not converted. + = Optimizing all your images = -You can bulk optimize your existing JPEG, PNG, and WebP images all at once by going to Media > Bulk TinyPNG. Clicking on the big button will start compressing and converting, when needed, all unoptimized images in your media library. +You can bulk optimize your existing JPEG, PNG, WebP, AVIF and JPEG XL images all at once by going to Media > Bulk TinyPNG. Clicking on the big button will start compressing and converting, when needed, all unoptimized images in your media library. If you have more images than your free credits allow, the tool will show you an estimated cost to optimize your entire library. If you are interested, you can upgrade your account to the paid plan and optimize the full library all in one go. Prefer to stay on the free plan? No problem! The bulk optimization tool will simply process images until your free limit is reached. @@ -171,7 +173,10 @@ A: Yes! After installing the plugin, go to *Media > Bulk TinyPNG*, and click on A: You can upgrade to a paid account by adding your *Payment details* on your [account dashboard](https://tinypng.com/dashboard/api). Additional compressions above 500 will then be charged at the end of each month as a one-time fee. = Q: Does converting to AVIF or WebP use more credits? = -A: When the conversion feature is enabled (to convert images to AVIF or WebP), each image will use double the number of credits: one for compression and one for format conversion. +A: When the conversion feature is enabled (to convert images to AVIF or WebP), each image will use double the number of credits: one for compression and one for format conversion. AVIF images are not converted, so they use one credit per size. + += Q: Can I optimize JPEG XL images? = +A: Yes, if your site accepts JPEG XL uploads. WordPress does not accept them by default, and the plugin does not change that. WordPress cannot create thumbnails of a JPEG XL image, so only the uploaded image is compressed. Not every browser can display JPEG XL; with the conversion feature enabled, an AVIF or WebP version is created and served instead. == Changelog == = 3.8.1 = diff --git a/src/class-tiny-apache-rewrite.php b/src/class-tiny-apache-rewrite.php index 31b5aa12..a602b63c 100644 --- a/src/class-tiny-apache-rewrite.php +++ b/src/class-tiny-apache-rewrite.php @@ -82,6 +82,21 @@ public static function toggle_rules( $old_value, $value, $option ) { } } + /** + * Reinstalls the rules when images are delivered with htaccess, so a + * plugin update can change the installed rules. + * + * @return void + */ + public static function refresh_rules() { + $convert_format = get_option( 'tinypng_convert_format' ); + if ( isset( $convert_format['delivery_method'] ) && + 'htaccess' === $convert_format['delivery_method'] ) { + $installed = self::install_rules(); + Tiny_Logger::debug( 'htaccess rules refreshed: ' . $installed ); + } + } + /** * Generate .htaccess rewrite rules for serving WebP and AVIF images. * @@ -99,7 +114,7 @@ private static function get_rewrite_rules() { $rules[] = ''; $rules[] = ''; - $rules[] = ''; + $rules[] = ''; $rules[] = 'Header append Vary Accept'; $rules[] = ''; $rules[] = ''; @@ -120,10 +135,10 @@ private static function get_rewrite_rules() { private static function get_avif_rules() { $rules = array(); $rules[] = 'RewriteCond %{HTTP_ACCEPT} image/avif'; - $rules[] = 'RewriteCond %{REQUEST_URI} ^(.+)\.(?:jpe?g|png)$'; + $rules[] = 'RewriteCond %{REQUEST_URI} ^(.+)\.(?:jpe?g|png|jxl)$'; $rules[] = 'RewriteCond %{DOCUMENT_ROOT}/%1.avif -f'; $rules[] = 'RewriteCond %{QUERY_STRING} !type=original'; - $rules[] = 'RewriteRule (.+)\.(?:jpe?g|png)$ $1.avif [T=image/avif,L]'; + $rules[] = 'RewriteRule (.+)\.(?:jpe?g|png|jxl)$ $1.avif [T=image/avif,L]'; return $rules; } @@ -135,10 +150,10 @@ private static function get_avif_rules() { private static function get_webp_rules() { $rules = array(); $rules[] = 'RewriteCond %{HTTP_ACCEPT} image/webp'; - $rules[] = 'RewriteCond %{REQUEST_URI} ^(.+)\.(?:jpe?g|png)$'; + $rules[] = 'RewriteCond %{REQUEST_URI} ^(.+)\.(?:jpe?g|png|jxl)$'; $rules[] = 'RewriteCond %{DOCUMENT_ROOT}/%1.webp -f'; $rules[] = 'RewriteCond %{QUERY_STRING} !type=original'; - $rules[] = 'RewriteRule (.+)\.(?:jpe?g|png)$ $1.webp [T=image/webp,L]'; + $rules[] = 'RewriteRule (.+)\.(?:jpe?g|png|jxl)$ $1.webp [T=image/webp,L]'; return $rules; } diff --git a/src/class-tiny-bulk-optimization.php b/src/class-tiny-bulk-optimization.php index 611fbf44..51c3ade2 100644 --- a/src/class-tiny-bulk-optimization.php +++ b/src/class-tiny-bulk-optimization.php @@ -65,9 +65,11 @@ private static function wpdb_retrieve_images_and_metadata( $start_id ) { global $wpdb; // Retrieve posts that have "_wp_attachment_metadata" image metadata - // and optionally contain "tiny_compress_images" metadata. - $sql_start_id = ( $start_id ? " $wpdb->posts.ID < $start_id AND " : '' ); - $query = + // and optionally contain "tiny_compress_images" metadata. Before + // WordPress 6.0, a JPEG XL has no attachment metadata. + $sql_start_id = ( $start_id ? " $wpdb->posts.ID < $start_id AND " : '' ); + $sql_mime_types = "'" . implode( "', '", Tiny_Image::compressible_mime_types() ) . "'"; + $query = "SELECT $wpdb->posts.ID, $wpdb->posts.post_title, @@ -77,6 +79,7 @@ private static function wpdb_retrieve_images_and_metadata( $start_id ) { FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id + AND $wpdb->postmeta.meta_key = '_wp_attachment_metadata' LEFT JOIN $wpdb->postmeta AS wp_postmeta_file ON $wpdb->posts.ID = wp_postmeta_file.post_id AND wp_postmeta_file.meta_key = '_wp_attached_file' @@ -86,12 +89,11 @@ private static function wpdb_retrieve_images_and_metadata( $start_id ) { WHERE $sql_start_id $wpdb->posts.post_type = 'attachment' + AND $wpdb->posts.post_mime_type IN ( $sql_mime_types ) AND ( - $wpdb->posts.post_mime_type = 'image/jpeg' OR - $wpdb->posts.post_mime_type = 'image/png' OR - $wpdb->posts.post_mime_type = 'image/webp' + $wpdb->postmeta.meta_id IS NOT NULL + OR $wpdb->posts.post_mime_type = 'image/jxl' ) - AND $wpdb->postmeta.meta_key = '_wp_attachment_metadata' GROUP BY unique_attachment_name ORDER BY ID DESC LIMIT " . self::PAGING_SIZE; diff --git a/src/class-tiny-cli.php b/src/class-tiny-cli.php index d4f8a182..fbbeffce 100644 --- a/src/class-tiny-cli.php +++ b/src/class-tiny-cli.php @@ -138,8 +138,7 @@ private function is_valid_attachment( $attachment_id ) { return false; } - $supported_types = array( 'image/jpeg', 'image/png', 'image/webp' ); - if ( ! in_array( $mime_type, $supported_types, true ) ) { + if ( ! in_array( $mime_type, Tiny_Image::compressible_mime_types(), true ) ) { return false; } diff --git a/src/class-tiny-helpers.php b/src/class-tiny-helpers.php index 7bfa70eb..5d4b7f9b 100644 --- a/src/class-tiny-helpers.php +++ b/src/class-tiny-helpers.php @@ -34,8 +34,8 @@ class Tiny_Helpers { * @return string the truncated string */ public static function truncate_text( $text, $length ) { - if ( mb_strlen( $text ) > $length ) { - return mb_substr( $text, 0, $length - 3 ) . '...'; + if ( mb_strlen( $text, 'UTF-8' ) > $length ) { + return mb_substr( $text, 0, $length - 3, 'UTF-8' ) . '...'; } return $text; } diff --git a/src/class-tiny-image.php b/src/class-tiny-image.php index 1306fa66..55fef77c 100644 --- a/src/class-tiny-image.php +++ b/src/class-tiny-image.php @@ -50,8 +50,13 @@ private function parse_wp_metadata() { if ( ! is_array( $this->wp_metadata ) ) { $this->wp_metadata = wp_get_attachment_metadata( $this->id ); } + if ( ! is_array( $this->wp_metadata ) && 'image/jxl' === $this->get_mime_type() ) { + // Before WordPress 6.0, a JPEG XL has no attachment metadata. + $this->wp_metadata = array(); + } - if ( ! is_array( $this->wp_metadata ) || ! isset( $this->wp_metadata['file'] ) ) { + $file = $this->get_metadata_file(); + if ( null === $file ) { /* No file metadata found, this might be another plugin messing with metadata. Simply ignore this! */ @@ -60,7 +65,7 @@ private function parse_wp_metadata() { $upload_dir = wp_upload_dir(); $path_prefix = $upload_dir['basedir'] . '/'; - $path_info = pathinfo( $this->wp_metadata['file'] ); + $path_info = pathinfo( $file ); if ( isset( $path_info['dirname'] ) ) { $path_prefix .= $path_info['dirname'] . '/'; } @@ -68,7 +73,7 @@ private function parse_wp_metadata() { /* Do not use pathinfo for getting the filename. It doesn't work when the filename starts with a special character. */ - $path_parts = explode( '/', $this->wp_metadata['file'] ); + $path_parts = explode( '/', $file ); $this->name = end( $path_parts ); $filename = $path_prefix . $this->name; $this->sizes[ self::ORIGINAL ] = new Tiny_Image_Size( $filename ); @@ -100,6 +105,26 @@ private function parse_wp_metadata() { $this->wp_metadata['sizes'] = $sanitized_sizes; } + /** + * WordPress cannot read JPEG XL, so the metadata of a JXL attachment + * holds no file. Its attached file is used instead. + * + * @return string|null the file relative to the upload directory + */ + private function get_metadata_file() { + if ( ! is_array( $this->wp_metadata ) ) { + return null; + } + if ( isset( $this->wp_metadata['file'] ) ) { + return $this->wp_metadata['file']; + } + if ( 'image/jxl' === $this->get_mime_type() ) { + $file = get_post_meta( $this->id, '_wp_attached_file', true ); + return $file ? $file : null; + } + return null; + } + private function detect_duplicates( $active_sizes, $active_tinify_sizes ) { $filenames = array(); @@ -206,12 +231,18 @@ public function get_wp_metadata() { return $this->wp_metadata; } + /** + * The attachment mime types the plugin compresses. A function instead of + * a constant, because PHP 5.4 and 5.5 do not allow arrays in constants. + * + * @return string[] mime types + */ + public static function compressible_mime_types() { + return array( 'image/jpeg', 'image/png', 'image/webp', 'image/avif', 'image/jxl' ); + } + public function file_type_allowed() { - return in_array( - $this->get_mime_type(), - array( 'image/jpeg', 'image/png', 'image/webp' ), - true - ); + return in_array( $this->get_mime_type(), self::compressible_mime_types(), true ); } public function get_mime_type() { @@ -254,7 +285,7 @@ public function compress() { $active_tinify_sizes = $this->settings->get_active_tinify_sizes(); - if ( $this->settings->get_conversion_enabled() ) { + if ( $this->conversion_applies() ) { $uncompressed_sizes = $this->filter_image_sizes( 'uncompressed', $active_tinify_sizes ); $unconverted_sizes = $this->filter_image_sizes( 'unconverted', $active_tinify_sizes ); @@ -534,7 +565,7 @@ public function get_statistics( $active_sizes, $active_tinify_sizes ) { $this->statistics['image_sizes_optimized'] = 0; $this->statistics['available_unoptimized_sizes'] = 0; - $conversion_enabled = $this->settings->get_conversion_enabled(); + $conversion_enabled = $this->conversion_applies(); foreach ( $this->sizes as $size_name => $size ) { // skip duplicates or inactive sizes @@ -575,7 +606,7 @@ public function get_statistics( $active_sizes, $active_tinify_sizes ) { if ( $is_active_size ) { if ( $size->has_been_converted() ) { ++$this->statistics['image_sizes_converted']; - } else { + } elseif ( ! $this->is_avif() ) { ++$this->statistics['available_unconverted_sizes']; } @@ -616,7 +647,22 @@ public static function is_retina( $size ) { } public function can_be_converted() { - return $this->settings->get_conversion_enabled() && $this->file_type_allowed(); + return $this->conversion_applies() && $this->file_type_allowed(); + } + + /** + * A WebP or AVIF copy of an AVIF is not worth a credit, so an AVIF is + * only compressed. The extension is checked instead of the mime type, + * so that bulk statistics need no query per image. + * + * @return bool true if the image is an AVIF + */ + private function is_avif() { + return 'avif' === strtolower( pathinfo( (string) $this->name, PATHINFO_EXTENSION ) ); + } + + private function conversion_applies() { + return $this->settings->get_conversion_enabled() && ! $this->is_avif(); } /** @@ -627,14 +673,13 @@ public function can_be_converted() { * * @since 3.6.4 * - * @return array{string} mimetypes to which the image should be converted to + * @return string[] mimetypes to which the image should be converted to, empty when conversion does not apply */ private function convert_to() { - $convert_settings = $this->settings->get_conversion_options(); - if ( ! $convert_settings['convert'] ) { - // conversion is off so return no mimetypes to convert to + if ( ! $this->conversion_applies() ) { return array(); } + $convert_settings = $this->settings->get_conversion_options(); foreach ( $this->sizes as $size ) { if ( ! $size->converted() ) { @@ -662,11 +707,11 @@ private function convert_to() { public function mark_as_compressed() { $this->parse_tiny_metadata(); - $conversion_enabled = $this->settings->get_conversion_enabled(); + $conversion_enabled = $this->conversion_applies(); $active_tinify_sizes = $this->settings->get_active_tinify_sizes(); - if ( $this->settings->get_conversion_enabled() ) { + if ( $conversion_enabled ) { $uncompressed_sizes = $this->filter_image_sizes( 'uncompressed', $active_tinify_sizes ); $unconverted_sizes = $this->filter_image_sizes( 'unconverted', $active_tinify_sizes ); diff --git a/src/class-tiny-logger.php b/src/class-tiny-logger.php index da0efa2b..117cb0cf 100644 --- a/src/class-tiny-logger.php +++ b/src/class-tiny-logger.php @@ -30,7 +30,7 @@ class Tiny_Logger { const LOG_LEVEL_ERROR = 'error'; const LOG_LEVEL_DEBUG = 'debug'; - const MAX_LOG_SIZE = 2 * 1024 * 1024; // 2MB + const MAX_LOG_SIZE = 2097152; // 2MB private static $instance = null; diff --git a/src/class-tiny-migrate.php b/src/class-tiny-migrate.php index de38aae1..33225a74 100644 --- a/src/class-tiny-migrate.php +++ b/src/class-tiny-migrate.php @@ -36,7 +36,7 @@ class Tiny_Migrate { * @since 3.7.0 * @var int */ - const DB_VERSION = 1; + const DB_VERSION = 2; /** * WordPress option key used to track the applied database version. @@ -68,7 +68,8 @@ class Tiny_Migrate { */ private static function migrations() { return array( - 1 => array( self::class, 'migrate_meta_key_to_private' ), + 1 => array( __CLASS__, 'migrate_meta_key_to_private' ), + 2 => array( __CLASS__, 'refresh_htaccess_rules' ), ); } @@ -144,4 +145,16 @@ private static function migrate_meta_key_to_private() { return true; } + + /** + * Rewrites the installed .htaccess rules, so they also serve the + * converted copies of JPEG XL images. + * + * @return bool Always true, retrying does not help when the upload + * directory is not writable. + */ + private static function refresh_htaccess_rules() { + Tiny_Apache_Rewrite::refresh_rules(); + return true; + } } diff --git a/src/class-tiny-plugin.php b/src/class-tiny-plugin.php index 59539323..30f62962 100644 --- a/src/class-tiny-plugin.php +++ b/src/class-tiny-plugin.php @@ -405,7 +405,7 @@ public function process_attachment( $metadata, $attachment_id ) { } public function blocking_compress_on_upload( $metadata, $attachment_id ) { - if ( ! empty( $metadata ) ) { + if ( is_array( $metadata ) ) { $tiny_image = new Tiny_Image( $this->settings, $attachment_id, $metadata ); Tiny_Logger::debug( @@ -572,6 +572,10 @@ private function validate_ajax_attachment_request() { } $id = intval( $_POST['id'] ); $metadata = wp_get_attachment_metadata( $id ); + if ( ! is_array( $metadata ) && 'image/jxl' === get_post_mime_type( $id ) ) { + // Before WordPress 6.0, a JPEG XL has no attachment metadata. + $metadata = array(); + } if ( ! is_array( $metadata ) ) { return array( 'error' => esc_html__( @@ -882,7 +886,7 @@ public function show_media_info() { if ( $tiny_image->file_type_allowed() ) { echo '
'; echo '

'; - esc_html_e( 'JPEG, PNG, & WebP optimization', 'tiny-compress-images' ); + esc_html_e( 'Image optimization', 'tiny-compress-images' ); echo '

'; echo '
'; diff --git a/src/views/compress-details.php b/src/views/compress-details.php index ef11e8ed..14fbb933 100644 --- a/src/views/compress-details.php +++ b/src/views/compress-details.php @@ -8,7 +8,7 @@ */ $available_sizes = array_keys( $this->settings->get_sizes() ); -$conversion_enabled = $this->settings->get_conversion_enabled(); +$conversion_enabled = $tiny_image->can_be_converted(); $active_sizes = $this->settings->get_sizes(); $backup_enabled = $this->settings->get_backup_enabled(); $active_tinify_sizes = $this->settings->get_active_tinify_sizes(); @@ -132,7 +132,7 @@ - 0 && $tiny_image->can_be_converted() ) { ?> + 0 && $conversion_enabled ) { ?> diff --git a/test/fixtures/class-tiny-config.php b/test/fixtures/class-tiny-config.php index 54587d14..c304048f 100644 --- a/test/fixtures/class-tiny-config.php +++ b/test/fixtures/class-tiny-config.php @@ -85,6 +85,26 @@ function clear_media_library() { ) ); } +// WordPress does not accept JPEG XL uploads, act like a site that does. The file +// check is overridden too, as the fileinfo of older PHP versions cannot detect JXL. +add_filter( 'upload_mimes', 'tiny_test_allow_jxl_uploads' ); +function tiny_test_allow_jxl_uploads( $mimes ) { + $mimes['jxl'] = 'image/jxl'; + return $mimes; +} + +add_filter( 'wp_check_filetype_and_ext', 'tiny_test_accept_jxl_files', 10, 3 ); +function tiny_test_accept_jxl_files( $data, $file, $filename ) { + if ( 'jxl' === strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ) ) { + return array( + 'ext' => 'jxl', + 'type' => 'image/jxl', + 'proper_filename' => false, + ); + } + return $data; +} + // ajax hook to upload copies of an image from test/fixtures in one request, as // uploading through the UI takes four page loads per image add_action( 'wp_ajax_upload_images', 'upload_images' ); diff --git a/test/fixtures/input-example.avif b/test/fixtures/input-example.avif new file mode 100644 index 00000000..977568a4 Binary files /dev/null and b/test/fixtures/input-example.avif differ diff --git a/test/fixtures/input-example.jxl b/test/fixtures/input-example.jxl new file mode 100644 index 00000000..0af3ff7d Binary files /dev/null and b/test/fixtures/input-example.jxl differ diff --git a/test/integration/bulkoptimization.spec.ts b/test/integration/bulkoptimization.spec.ts index 369279e5..1f2e5b94 100644 --- a/test/integration/bulkoptimization.spec.ts +++ b/test/integration/bulkoptimization.spec.ts @@ -152,6 +152,20 @@ test.describe('bulkoptimization', () => { await expect(page.locator('#optimized-image-sizes')).toHaveText('4'); }); + test('summary should count jpeg xl images that were not compressed on upload', async () => { + // Before WordPress 6.0, such an image has no attachment metadata + await setAPIKey(page, 'JPG123'); + await setCompressionTiming(page, 'manual'); + await enableCompressionSizes(page, ['0']); + + await uploadMedia(page, 'input-example.jxl'); + + await page.goto('/wp-admin/upload.php?page=tiny-bulk-optimization'); + + await expect(page.locator('#uploaded-images')).toHaveText('1'); + await expect(page.locator('#optimizable-image-sizes')).toHaveText('1'); + }); + test('summary should display correct values', async () => { await setAPIKey(page, 'JPG123'); await setCompressionTiming(page, 'auto'); diff --git a/test/integration/compression.spec.ts b/test/integration/compression.spec.ts index 5927cca7..0cc48e71 100644 --- a/test/integration/compression.spec.ts +++ b/test/integration/compression.spec.ts @@ -172,6 +172,48 @@ test.describe('compression', () => { await expect(page.getByText('3 sizes compressed')).toBeVisible({ timeout: 6000 }); }); + test('upload of an avif image should compress all sizes', async () => { + // https://make.wordpress.org/core/2024/02/23/wordpress-6-5-adds-avif-support/ + if (WPVersion < 6.5) return; + + await setAPIKey(page, 'JPG123'); + await setCompressionTiming(page, 'auto'); + await enableCompressionSizes(page, ['0', 'medium', 'thumbnail']); + + await uploadMedia(page, 'input-example.avif'); + + await page.goto('/wp-admin/upload.php'); + + await expect(page.getByText('3 sizes compressed')).toBeVisible(); + }); + + test('upload of a jpeg xl image should compress the uploaded image', async () => { + // WordPress cannot read JPEG XL, so it creates no other sizes + await setAPIKey(page, 'JPG123'); + await setCompressionTiming(page, 'auto'); + await enableCompressionSizes(page, ['0', 'medium', 'thumbnail']); + + await uploadMedia(page, 'input-example.jxl'); + + await page.goto('/wp-admin/upload.php'); + + await expect(page.getByText('1 size compressed')).toBeVisible(); + }); + + test('compress button should compress a jpeg xl image that was not compressed on upload', async () => { + // Before WordPress 6.0, such an image has no attachment metadata + await setAPIKey(page, 'JPG123'); + await setCompressionTiming(page, 'manual'); + await enableCompressionSizes(page, ['0', 'medium', 'thumbnail']); + + await uploadMedia(page, 'input-example.jxl'); + + await page.goto('/wp-admin/upload.php'); + + await page.getByRole('button', { name: 'Compress', exact: true }).click(); + await expect(page.getByText('1 size compressed')).toBeVisible({ timeout: 6000 }); + }); + test('compress button should compress uncompressed sizes', async () => { await setAPIKey(page, 'JPG123'); await setCompressionTiming(page, 'auto'); diff --git a/test/integration/conversion.spec.ts b/test/integration/conversion.spec.ts index 60ff0cc7..7166dcda 100644 --- a/test/integration/conversion.spec.ts +++ b/test/integration/conversion.spec.ts @@ -70,6 +70,37 @@ test.describe('conversion', () => { await expect(picture).toBeVisible(); }); + test('will compress an avif image without converting it', async () => { + // https://make.wordpress.org/core/2024/02/23/wordpress-6-5-adds-avif-support/ + if (WPVersion < 6.5) return; + + await setConversionSettings(page, { + convert: true, + output: 'smallest', + delivery: 'picture', + }); + await uploadMedia(page, 'input-example.avif'); + + await page.goto('/wp-admin/upload.php'); + + await expect(page.getByText('1 size compressed')).toBeVisible(); + await expect(page.locator('.tiny-ajax-container').getByText(/convert/i)).toHaveCount(0); + }); + + test('will add the optimized format to a jpeg xl image', async () => { + await setConversionSettings(page, { + convert: true, + output: 'smallest', + delivery: 'picture', + }); + await uploadMedia(page, 'input-example.jxl'); + + await page.goto('/wp-admin/upload.php'); + + await expect(page.getByText('1 size compressed')).toBeVisible(); + await expect(page.getByText('1 size converted')).toBeVisible(); + }); + test('will serve optimized image when server side rules are configured', async () => { await setConversionSettings(page, { convert: true, @@ -102,4 +133,22 @@ test.describe('conversion', () => { expect(signature).toContain('ftypavif'); }); + + test('will serve the optimized format of a jpeg xl image when server side rules are configured', async () => { + await setConversionSettings(page, { + convert: true, + output: 'smallest', + delivery: 'htaccess', + }); + const { imageURL } = await uploadMedia(page, 'input-example.jxl'); + + const response = await page.request.get(imageURL, { + headers: { + Accept: 'image/avif,image/webp,*/*', + }, + }); + const signature = (await response.body()).toString('ascii', 0, 16); + + expect(signature).toContain('ftypavif'); + }); }); diff --git a/test/unit/TinyBulkOptimizationTest.php b/test/unit/TinyBulkOptimizationTest.php index 505b40dd..59218422 100644 --- a/test/unit/TinyBulkOptimizationTest.php +++ b/test/unit/TinyBulkOptimizationTest.php @@ -229,4 +229,92 @@ public function test_get_optimization_statistics() Tiny_Bulk_Optimization::get_optimization_statistics(new Tiny_Settings(), $wpdb_results) ); } + + public function test_retrieves_avif_and_jxl_attachments() + { + if (!defined('ARRAY_A')) { + define('ARRAY_A', 'ARRAY_A'); + } + global $wpdb; + $wpdb = $this->getMockBuilder(stdClass::class) + ->addMethods(['get_results']) + ->getMock(); + $wpdb->posts = 'wp_posts'; + $wpdb->postmeta = 'wp_postmeta'; + + $queries = array(); + $wpdb->method('get_results') + ->willReturnCallback(function ($query) use (&$queries) { + $queries[] = $query; + return array(); + }); + + Tiny_Bulk_Optimization::get_optimization_statistics(new Tiny_Settings()); + + $this->assertStringContainsString("'image/avif'", $queries[0]); + $this->assertStringContainsString("'image/jxl'", $queries[0]); + } + + public function test_counts_jxl_without_attachment_metadata() + { + $this->wp->addOption('tinypng_sizes', array(Tiny_Image::ORIGINAL => 'on')); + $this->wp->createImage(5000, '2023/05', 'photo.jxl'); + $this->wp->updateMetadata(4400, '_wp_attached_file', '2023/05/photo.jxl'); + $this->wp->stub('get_post_mime_type', function () { + return 'image/jxl'; + }); + $this->wp->stub('wp_get_attachment_metadata', function () { + return false; + }); + + $stats = Tiny_Bulk_Optimization::get_optimization_statistics(new Tiny_Settings(), array( + array( + 'ID' => 4400, + 'post_title' => 'photo', + 'meta_value' => null, + 'tiny_meta_value' => null, + ), + )); + + $this->assertEquals(1, $stats['estimated_credit_use']); + $this->assertEquals(1, $stats['available-unoptimized-sizes']); + } + + public function test_avif_needs_no_conversion_credits() + { + $this->wp->addOption('tinypng_convert_format', array( + 'convert' => 'on', + 'convert_to' => 'smallest', + )); + $this->wp->addOption('tinypng_sizes', array( + Tiny_Image::ORIGINAL => 'on', + 'thumbnail' => 'on', + )); + $this->wp->createImagesFromJSON(array( + 'path' => '2023/05', + 'images' => array( + array('file' => 'photo.avif', 'size' => 50000), + array('file' => 'photo-150x150.avif', 'size' => 5000), + ), + )); + + $stats = Tiny_Bulk_Optimization::get_optimization_statistics(new Tiny_Settings(), array( + array( + 'ID' => 4400, + 'post_title' => 'photo', + 'meta_value' => serialize(array( + 'width' => 1080, + 'height' => 720, + 'file' => '2023/05/photo.avif', + 'sizes' => array( + 'thumbnail' => array('file' => 'photo-150x150.avif'), + ), + )), + 'tiny_meta_value' => '', + ), + )); + + $this->assertEquals(2, $stats['estimated_credit_use']); + $this->assertEquals(2, $stats['available-unoptimized-sizes']); + } } diff --git a/test/unit/TinyCliTest.php b/test/unit/TinyCliTest.php index e817eeed..c9cf8806 100644 --- a/test/unit/TinyCliTest.php +++ b/test/unit/TinyCliTest.php @@ -75,6 +75,84 @@ public function test_will_compress_attachments_given_in_params() )); } + public function test_will_compress_avif_attachments() + { + $this->wp->stub('get_post_mime_type', function ($i) { + return 'image/avif'; + }); + $this->wp->stub('wp_get_attachment_metadata', function ($i) { + return array( + 'width' => 1080, + 'height' => 720, + 'file' => '2025/07/photo.avif', + 'sizes' => array(), + ); + }); + $this->wp->createImage(137856, '2025/07', 'photo.avif'); + + $settings = new Tiny_Settings(); + $mockCompressor = $this->createMock(Tiny_Compress::class); + $mockCompressor->expects($this->once()) + ->method('compress_file') + ->with('vfs://root/wp-content/uploads/2025/07/photo.avif'); + $settings->set_compressor($mockCompressor); + + $command = new Tiny_Cli($settings); + $command->optimize(array(), array( + "attachments" => '4030', + )); + } + + public function test_will_compress_jxl_attachments() + { + $this->wp->stub('get_post_mime_type', function ($i) { + return 'image/jxl'; + }); + $this->wp->stub('wp_get_attachment_metadata', function ($i) { + return array('filesize' => 137856); + }); + $this->wp->updateMetadata(4030, '_wp_attached_file', '2025/07/photo.jxl'); + $this->wp->createImage(137856, '2025/07', 'photo.jxl'); + + $settings = new Tiny_Settings(); + $mockCompressor = $this->createMock(Tiny_Compress::class); + $mockCompressor->expects($this->once()) + ->method('compress_file') + ->with('vfs://root/wp-content/uploads/2025/07/photo.jxl'); + $settings->set_compressor($mockCompressor); + + $command = new Tiny_Cli($settings); + $command->optimize(array(), array( + "attachments" => '4030', + )); + } + + public function test_will_skip_unsupported_attachments() + { + $this->wp->stub('get_post_mime_type', function ($i) { + return 'image/gif'; + }); + $this->wp->stub('wp_get_attachment_metadata', function ($i) { + return array( + 'width' => 100, + 'height' => 100, + 'file' => '2025/07/anim.gif', + 'sizes' => array(), + ); + }); + $this->wp->createImage(1000, '2025/07', 'anim.gif'); + + $settings = new Tiny_Settings(); + $mockCompressor = $this->createMock(Tiny_Compress::class); + $mockCompressor->expects($this->never())->method('compress_file'); + $settings->set_compressor($mockCompressor); + + $command = new Tiny_Cli($settings); + $command->optimize(array(), array( + "attachments" => '4030', + )); + } + public function test_will_compress_all_uncompressed_attachments_if_none_given() { // mock db diff --git a/test/unit/TinyHelpersTest.php b/test/unit/TinyHelpersTest.php index eca30971..fd756478 100644 --- a/test/unit/TinyHelpersTest.php +++ b/test/unit/TinyHelpersTest.php @@ -24,6 +24,19 @@ public function test_will_not_truncate_if_text_is_shorter_than_length() $this->assertEquals($input_text, Tiny_Helpers::truncate_text($input_text, 26)); } + public function test_truncates_utf8_text_by_characters_when_internal_encoding_is_latin1() + { + $internal_encoding = mb_internal_encoding(); + mb_internal_encoding('ISO-8859-1'); + try { + $truncated = Tiny_Helpers::truncate_text(str_repeat('é', 25), 20); + } finally { + mb_internal_encoding($internal_encoding); + } + + $this->assertEquals(str_repeat('é', 17) . '...', $truncated); + } + public function test_will_change_file_extension() { $input_file = "/home/user/image.png"; diff --git a/test/unit/TinyImageTest.php b/test/unit/TinyImageTest.php index f35b12ff..eac9d02e 100644 --- a/test/unit/TinyImageTest.php +++ b/test/unit/TinyImageTest.php @@ -512,4 +512,215 @@ public function test_compression_after_mark_as_compressed_uses_conversion_settin $tinyimg = new Tiny_Image($settings, 999, $this->wp->getTestMetadata()); $tinyimg->compress(); } + + public static function mime_types() + { + return array( + 'jpeg' => array('image/jpeg', true), + 'png' => array('image/png', true), + 'webp' => array('image/webp', true), + 'avif' => array('image/avif', true), + 'jxl' => array('image/jxl', true), + 'gif' => array('image/gif', false), + 'heic' => array('image/heic', false), + 'svg' => array('image/svg+xml', false), + ); + } + + /** + * @dataProvider mime_types + */ + public function test_file_type_allowed($mime_type, $allowed) + { + $this->wp->stub('get_post_mime_type', function () use ($mime_type) { + return $mime_type; + }); + + $tinyimg = new Tiny_Image(new Tiny_Settings(), 1, $this->json('_wp_attachment_metadata')); + + $this->assertSame($allowed, $tinyimg->file_type_allowed()); + } + + public function test_avif_is_compressed_without_a_converted_copy() + { + $this->enable_conversion(); + $metadata = $this->create_avif_attachment(); + + $settings = new Tiny_Settings(); + $mock_compressor = $this->createMock(Tiny_Compress::class); + $mock_compressor->expects($this->exactly(2)) + ->method('compress_file') + ->with($this->anything(), $this->anything(), $this->anything(), array()) + ->willReturn(array( + 'input' => array('size' => 5000), + 'output' => array('size' => 4000, 'type' => 'image/avif'), + )); + $settings->set_compressor($mock_compressor); + + $tinyimg = new Tiny_Image($settings, 999, $metadata); + $tinyimg->compress(); + } + + public function test_compressed_avif_has_nothing_left_to_optimize_with_conversion_enabled() + { + $this->enable_conversion(); + $metadata = $this->create_avif_attachment(); + + $settings = new Tiny_Settings(); + $mock_compressor = $this->createMock(Tiny_Compress::class); + $mock_compressor->method('compress_file') + ->willReturnCallback(function ($file) { + return array( + 'input' => array('size' => filesize($file)), + 'output' => array('size' => filesize($file), 'type' => 'image/avif'), + ); + }); + $settings->set_compressor($mock_compressor); + + $tinyimg = new Tiny_Image($settings, 999, $metadata); + $tinyimg->compress(); + $stats = $tinyimg->get_statistics($settings->get_sizes(), $settings->get_active_tinify_sizes()); + + $this->assertEquals(2, $stats['image_sizes_optimized']); + $this->assertEquals(0, $stats['available_unoptimized_sizes']); + $this->assertEquals(0, $stats['available_unconverted_sizes']); + $this->assertFalse($tinyimg->can_be_converted()); + } + + public function test_jxl_without_a_file_in_its_metadata_compresses_the_attached_file() + { + $this->wp->addOption('tinypng_sizes', array(Tiny_Image::ORIGINAL => 'on')); + $metadata = $this->create_jxl_attachment(); + + $settings = new Tiny_Settings(); + $mock_compressor = $this->createMock(Tiny_Compress::class); + $mock_compressor->expects($this->once()) + ->method('compress_file') + ->with( + 'vfs://root/wp-content/uploads/14/01/photo.jxl', + $this->anything(), + $this->anything(), + array() + ) + ->willReturn(array( + 'input' => array('size' => 5000), + 'output' => array('size' => 4000, 'type' => 'image/jxl'), + )); + $settings->set_compressor($mock_compressor); + + $tinyimg = new Tiny_Image($settings, 999, $metadata); + $tinyimg->compress(); + } + + public function test_jxl_without_attachment_metadata_compresses_the_attached_file() + { + $this->wp->addOption('tinypng_sizes', array(Tiny_Image::ORIGINAL => 'on')); + $this->create_jxl_attachment(); + $this->wp->stub('wp_get_attachment_metadata', function () { + return false; + }); + + $settings = new Tiny_Settings(); + $mock_compressor = $this->createMock(Tiny_Compress::class); + $mock_compressor->expects($this->once()) + ->method('compress_file') + ->with( + 'vfs://root/wp-content/uploads/14/01/photo.jxl', + $this->anything(), + $this->anything(), + array() + ) + ->willReturn(array( + 'input' => array('size' => 5000), + 'output' => array('size' => 4000, 'type' => 'image/jxl'), + )); + $settings->set_compressor($mock_compressor); + + $tinyimg = new Tiny_Image($settings, 999); + $tinyimg->compress(); + } + + public function test_jxl_gets_a_converted_copy_when_conversion_is_enabled() + { + $this->enable_conversion(); + $metadata = $this->create_jxl_attachment(); + + $settings = new Tiny_Settings(); + $mock_compressor = $this->createMock(Tiny_Compress::class); + $mock_compressor->expects($this->once()) + ->method('compress_file') + ->with($this->anything(), $this->anything(), $this->anything(), array('image/avif', 'image/webp')) + ->willReturn(array( + 'input' => array('size' => 5000), + 'output' => array('size' => 4000, 'type' => 'image/jxl'), + 'convert' => array('type' => 'image/avif', 'size' => 3000, 'path' => 'vfs://root/wp-content/uploads/14/01/photo.avif'), + )); + $settings->set_compressor($mock_compressor); + + $tinyimg = new Tiny_Image($settings, 999, $metadata); + $tinyimg->compress(); + } + + public function test_other_formats_without_a_file_in_their_metadata_are_skipped() + { + $this->wp->addOption('tinypng_sizes', array(Tiny_Image::ORIGINAL => 'on')); + $this->wp->stub('get_post_mime_type', function () { + return 'image/png'; + }); + $this->wp->createImage(5000, '14/01', 'photo.png'); + $this->wp->updateMetadata(999, '_wp_attached_file', '14/01/photo.png'); + + $settings = new Tiny_Settings(); + $mock_compressor = $this->createMock(Tiny_Compress::class); + $mock_compressor->expects($this->never())->method('compress_file'); + $settings->set_compressor($mock_compressor); + + $tinyimg = new Tiny_Image($settings, 999, array('filesize' => 5000)); + $tinyimg->compress(); + } + + private function enable_conversion() + { + $this->wp->addOption('tinypng_convert_format', array( + 'convert' => 'on', + 'convert_to' => 'smallest', + )); + $this->wp->addOption('tinypng_sizes', array( + Tiny_Image::ORIGINAL => 'on', + 'thumbnail' => 'on', + )); + } + + private function create_avif_attachment() + { + $this->wp->stub('get_post_mime_type', function () { + return 'image/avif'; + }); + $this->wp->createImage(5000, '14/01', 'photo.avif'); + $this->wp->createImage(1000, '14/01', 'photo-150x150.avif'); + + return array( + 'file' => '14/01/photo.avif', + 'width' => 1080, + 'height' => 720, + 'sizes' => array( + 'thumbnail' => array('file' => 'photo-150x150.avif'), + ), + ); + } + + /** + * WordPress cannot read JPEG XL, so the metadata of a JXL attachment + * holds only its file size. + */ + private function create_jxl_attachment() + { + $this->wp->stub('get_post_mime_type', function () { + return 'image/jxl'; + }); + $this->wp->createImage(5000, '14/01', 'photo.jxl'); + $this->wp->updateMetadata(999, '_wp_attached_file', '14/01/photo.jxl'); + + return array('filesize' => 5000); + } } diff --git a/test/unit/TinyMigrateTest.php b/test/unit/TinyMigrateTest.php index 7ceea0b5..79c7f325 100644 --- a/test/unit/TinyMigrateTest.php +++ b/test/unit/TinyMigrateTest.php @@ -81,6 +81,49 @@ public function test_run_renames_meta_key_in_batches() $this->assertOptionWasUpdated(Tiny_Migrate::DB_VERSION_OPTION, Tiny_Migrate::DB_VERSION); } + public function test_run_refreshes_htaccess_rules_for_htaccess_delivery() + { + $this->wp->addOption(Tiny_Migrate::DB_VERSION_OPTION, 1); + $this->wp->addOption('tinypng_convert_format', array( + 'convert' => 'on', + 'delivery_method' => 'htaccess', + )); + $htaccess_file = $this->create_upload_dir() . '/.htaccess'; + file_put_contents( + $htaccess_file, + "# BEGIN tiny-compress-images\nRewriteRule (.+)\\.(?:jpe?g|png)$ $1.avif [T=image/avif,L]\n# END tiny-compress-images\n" + ); + + Tiny_Migrate::run(); + + $this->assertStringContainsString('jxl', file_get_contents($htaccess_file)); + $this->assertOptionWasUpdated(Tiny_Migrate::DB_VERSION_OPTION, Tiny_Migrate::DB_VERSION); + } + + public function test_run_leaves_htaccess_alone_for_picture_delivery() + { + $this->wp->addOption(Tiny_Migrate::DB_VERSION_OPTION, 1); + $this->wp->addOption('tinypng_convert_format', array( + 'convert' => 'on', + 'delivery_method' => 'picture', + )); + $upload_dir = $this->create_upload_dir(); + + Tiny_Migrate::run(); + + $this->assertFileDoesNotExist($upload_dir . '/.htaccess'); + $this->assertOptionWasUpdated(Tiny_Migrate::DB_VERSION_OPTION, Tiny_Migrate::DB_VERSION); + } + + private function create_upload_dir() + { + $upload_dir = $this->vfs->url() . '/wp-content/uploads'; + if (!is_dir($upload_dir)) { + mkdir($upload_dir, 0755, true); + } + return $upload_dir; + } + public function test_get_tiny_metadata_reads_the_current_private_key() { $this->wp->updateMetadata(1, Tiny_Config::META_KEY, array('size' => 'current')); diff --git a/test/unit/TinyPluginTest.php b/test/unit/TinyPluginTest.php index 5971aaf8..ca7b2955 100644 --- a/test/unit/TinyPluginTest.php +++ b/test/unit/TinyPluginTest.php @@ -230,6 +230,32 @@ public function test_should_return_if_no_image() $this->subject->blocking_compress_on_upload($this->wp->getTestMetadata(), 1); } + public static function jxl_upload_metadata() + { + return array( + 'WordPress 6.0 and later store the file size' => array(array('filesize' => 5000)), + 'earlier versions store nothing' => array(array()), + ); + } + + /** + * @dataProvider jxl_upload_metadata + */ + public function test_compress_on_upload_compresses_jxl($metadata) + { + $this->wp->stub('get_post_mime_type', function ($i) { + return 'image/jxl'; + }); + $this->wp->createImage(5000, '14/01', 'photo.jxl'); + $this->wp->updateMetadata(1, '_wp_attached_file', '14/01/photo.jxl'); + $this->compressor->expects($this->once()) + ->method('compress_file') + ->with($this->equalTo('vfs://root/wp-content/uploads/14/01/photo.jxl')) + ->will($this->returnCallback(array($this, 'success_compress'))); + + $this->subject->blocking_compress_on_upload($metadata, 1); + } + public function test_wrong_metadata_should_not_show_warnings() { $this->wp->stub('get_post_mime_type', function ($i) { diff --git a/test/unit/Tiny_Apache_Rewrite_Test.php b/test/unit/Tiny_Apache_Rewrite_Test.php index 78009335..bd15c823 100644 --- a/test/unit/Tiny_Apache_Rewrite_Test.php +++ b/test/unit/Tiny_Apache_Rewrite_Test.php @@ -79,6 +79,33 @@ function test_toggle_rules_for_new_option_installs_upload_dir_htaccess() $this->assertStringContainsString('tiny-compress-images', file_get_contents($htaccess_file)); } + /** + * A JXL request is served its converted AVIF or WebP copy, like JPEG and PNG. + */ + function test_rules_serve_converted_copies_of_jxl() + { + $upload_dir = $this->vfs->url() . '/wp-content/uploads'; + if (!is_dir($upload_dir)) { + mkdir($upload_dir, 0755, true); + } + + Tiny_Apache_Rewrite::toggle_rules_for_new_option( + 'tinypng_convert_format', + array('convert' => 'on', 'delivery_method' => 'htaccess') + ); + $rules = file_get_contents($upload_dir . '/.htaccess'); + + preg_match_all('/^RewriteCond %\{REQUEST_URI\} (\S+)$/m', $rules, $conditions); + preg_match_all('/^RewriteRule (\S+) /m', $rules, $rewrites); + preg_match_all('//', $rules, $vary); + $this->assertCount(2, $conditions[1]); + $this->assertCount(2, $rewrites[1]); + $this->assertCount(1, $vary[1]); + foreach (array_merge($conditions[1], $rewrites[1], $vary[1]) as $pattern) { + $this->assertMatchesRegularExpression('#' . $pattern . '#', '/wp-content/uploads/2026/11/photo.jxl'); + } + } + /** * uninstall_rules removes htaccess rules from upload directory. * - creates a htaccess file in uploads directory