From f2c58e240874637e5c07ab2ce8f87dfece2cba63 Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Wed, 2 Dec 2026 13:27:34 +0530 Subject: [PATCH 1/8] chore(core): Declare WP 6.3 and drop old fallbacks readme.txt already declares WordPress 6.3 as the minimum. Add the same "Requires at least" and "Requires PHP" headers to the plugin file, so WordPress blocks activation on older sites. Remove the code paths that only ran on WordPress versions below 6.3: the function_exists() checks for wp_get_original_image_path/url, has_block and wp_print_inline_script_tag, the get_post_parent() fallback, the pre-5.9 class-http.php include and the pre-5.1 render_block fallback for video blocks. The fallback callback stays, marked deprecated, for third-party callers. Use wp_admin_notice() (WP 6.4+) for the PHP version notice when it is available. --- cloudinary.php | 10 +++++++++- php/class-media.php | 7 ++----- php/class-sync.php | 2 +- php/class-utils.php | 18 ++---------------- php/connect/class-api.php | 2 +- php/media/class-gallery.php | 2 +- php/media/class-video.php | 9 +++------ php/sync/class-download-sync.php | 7 +------ phpcs.xml.dist | 3 ++- 9 files changed, 22 insertions(+), 38 deletions(-) diff --git a/cloudinary.php b/cloudinary.php index fa6a53a10..fefa7f6b6 100644 --- a/cloudinary.php +++ b/cloudinary.php @@ -4,6 +4,8 @@ * Plugin URI: https://cloudinary.com/documentation/wordpress_integration * Description: With the Cloudinary plugin, you can upload and manage your media assets in the cloud, then deliver them to your users through a fast content delivery network, improving your website’s loading speed and overall user experience. Apply multiple transformations and take advantage of a full digital asset management solution without leaving WordPress. * Version: STABLETAG + * Requires at least: 6.3 + * Requires PHP: 7.4 * Author: Cloudinary Ltd., XWP * Author URI: https://cloudinary.com/ * License: GPLv2+ @@ -52,7 +54,13 @@ * Admin notice for incompatible versions of PHP. */ function php_version_error() { - printf( '

%s

', esc_html( php_version_text() ) ); + if ( function_exists( 'wp_admin_notice' ) ) { + wp_admin_notice( esc_html( php_version_text() ), array( 'type' => 'error' ) ); + + return; + } + + printf( '

%s

', esc_html( php_version_text() ) ); } /** diff --git a/php/class-media.php b/php/class-media.php index 74924df24..184ae783e 100644 --- a/php/class-media.php +++ b/php/class-media.php @@ -475,10 +475,7 @@ public function is_oversize_media( $attachment_id ) { public function get_attachment_file_size( $attachment_id ) { $callback = 'get_attached_file'; - if ( - function_exists( 'wp_get_original_image_path' ) - && wp_attachment_is_image( $attachment_id ) - ) { + if ( wp_attachment_is_image( $attachment_id ) ) { $callback = 'wp_get_original_image_path'; } @@ -509,7 +506,7 @@ function_exists( 'wp_get_original_image_path' ) public function get_upload_file_path( $attachment_id ) { /** This filter is documented in php/connect/class-api.php */ $use_original = apply_filters( 'cloudinary_use_original_image', true, $attachment_id ); - if ( $use_original && function_exists( 'wp_get_original_image_path' ) && wp_attachment_is_image( $attachment_id ) ) { + if ( $use_original && wp_attachment_is_image( $attachment_id ) ) { return wp_get_original_image_path( $attachment_id ); } diff --git a/php/class-sync.php b/php/class-sync.php index 2db1f2277..2b2fd54ba 100644 --- a/php/class-sync.php +++ b/php/class-sync.php @@ -428,7 +428,7 @@ public function get_signature( $attachment_id, $cached = true ) { public function generate_public_id( $attachment_id ) { $cld_folder = $this->managers['media']->get_cloudinary_folder(); - if ( function_exists( 'wp_get_original_image_path' ) && wp_attachment_is_image( $attachment_id ) ) { + if ( wp_attachment_is_image( $attachment_id ) ) { $file = wp_get_original_image_path( $attachment_id ); } else { $file = get_attached_file( $attachment_id ); diff --git a/php/class-utils.php b/php/class-utils.php index 2f3af7459..1eea37430 100644 --- a/php/class-utils.php +++ b/php/class-utils.php @@ -545,15 +545,7 @@ public static function get_support_link( $args = array() ) { * @param string $javascript Inline JavaScript code. */ public static function print_inline_tag( $javascript ) { - if ( function_exists( 'wp_print_inline_script_tag' ) ) { - wp_print_inline_script_tag( $javascript ); - - return; - } - - $javascript = "\n" . trim( $javascript, "\n\r " ) . "\n"; - - printf( "\n", $javascript ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped + wp_print_inline_script_tag( $javascript ); } /** @@ -768,13 +760,7 @@ public static function svg_encoded( $width = '600px', $height = '400px', $color * @return WP_Post|null */ public static function get_post_parent( $post = null ) { - // get_post_parent() was added in WP 6.0; keep a fallback for older supported versions. - if ( is_callable( 'get_post_parent' ) ) { // @phpstan-ignore function.alreadyNarrowedType - return get_post_parent( $post ); - } - - $wp_post = get_post( $post ); // @phpstan-ignore deadCode.unreachable - return ! empty( $wp_post->post_parent ) ? get_post( $wp_post->post_parent ) : null; + return get_post_parent( $post ); } /** diff --git a/php/connect/class-api.php b/php/connect/class-api.php index 606ccda88..b206e2a2e 100644 --- a/php/connect/class-api.php +++ b/php/connect/class-api.php @@ -527,7 +527,7 @@ public function upload( $attachment_id, $args, $headers = array(), $try_remote = * @return bool */ $use_original = apply_filters( 'cloudinary_use_original_image', true, $attachment_id ); - if ( $use_original && function_exists( 'wp_get_original_image_url' ) && wp_attachment_is_image( $attachment_id ) ) { + if ( $use_original && wp_attachment_is_image( $attachment_id ) ) { $file_url = wp_get_original_image_url( $attachment_id ); } else { $file_url = wp_get_attachment_url( $attachment_id ); diff --git a/php/media/class-gallery.php b/php/media/class-gallery.php index 93f925698..c22dab87e 100644 --- a/php/media/class-gallery.php +++ b/php/media/class-gallery.php @@ -667,7 +667,7 @@ protected function maybe_enqueue_scripts() { // Can if front end and have the block. if ( - function_exists( 'has_block' ) && has_block( 'cloudinary/gallery' ) + has_block( 'cloudinary/gallery' ) && ! is_admin() ) { diff --git a/php/media/class-video.php b/php/media/class-video.php index a1e8ea553..40fc7505d 100644 --- a/php/media/class-video.php +++ b/php/media/class-video.php @@ -195,6 +195,8 @@ public function admin_enqueue_scripts() { /** * Fallback for render_block_data filter. * + * @deprecated 3.3.10 The render_block_data filter is always available on the supported WordPress versions. + * * @param string $block_content The block content about to be appended. * @param array $block The full block, including name and attributes. * @@ -626,12 +628,7 @@ public function setup_hooks() { add_filter( 'cloudinary_default_freeform_transformations_video', array( $this, 'default_video_freeform_transformations' ), 10 ); if ( ! is_admin() ) { // Filter for block rendering. - if ( has_filter( 'render_block_data' ) ) { - add_filter( 'render_block_data', array( $this, 'filter_video_block_pre_render' ), 10, 2 ); - } else { - // The render_block_data filter was only introduced on WP 5.1.0. This is the fallback for 5.0.*. - add_filter( 'render_block', array( $this, 'filter_video_block_render_block' ), 10, 2 ); - } + add_filter( 'render_block_data', array( $this, 'filter_video_block_pre_render' ), 10, 2 ); } else { // Remove the _i query var in admin, when the video shortcode is used. add_filter( diff --git a/php/sync/class-download-sync.php b/php/sync/class-download-sync.php index c1fa49f96..1e81d844c 100644 --- a/php/sync/class-download-sync.php +++ b/php/sync/class-download-sync.php @@ -300,13 +300,8 @@ public function download_asset( $attachment_id, $source = null, $date = null ) { public function import_asset( $attachment_id, $file_path, $transformations = null ) { // Get the image and update the attachment. - $http_class = ABSPATH . WPINC . '/class-http.php'; - // Since WP 5.9. - if ( file_exists( ABSPATH . WPINC . '/class-wp-http.php' ) ) { - $http_class = ABSPATH . WPINC . '/class-wp-http.php'; - } if ( ! class_exists( 'WP_Http' ) ) { - require_once $http_class; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable + require_once ABSPATH . WPINC . '/class-wp-http.php'; } require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 6bc6255da..042e8120c 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -8,7 +8,8 @@ + WP 6.3+ polyfills only str_contains, str_starts_with and str_ends_with, + and only when WP is loaded, so keep flagging them for PHP 7.4. --> 5 From 6b09827a61eed8b85ab45cd3429fc9fb2d401d44 Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Wed, 2 Dec 2026 13:28:29 +0530 Subject: [PATCH 2/8] refactor(delivery): Parse tags with the WP HTML API Replace shortcode_parse_atts() and str_replace() tag handling with WP_HTML_Tag_Processor (WP 6.2+). - Utils::parse_html_tag() reads the tag name and attributes with the HTML API. Values are decoded and not unslashed, and a ">" inside a value no longer cuts the tag short. Delivery::parse_element() and Utils::get_tag_attributes() use it. - Filter::add_front_end_attributes() sets the missing class with set_attribute(), instead of inserting text before "/>", which did nothing on tags without a self-closing slash. - The content filter no longer stores loading="lazy" in post content. The check called wp_lazy_loading_enabled with the wrong arguments, and a stored value stops core from finding above the fold images. - Remove the old srcset before wp_image_add_srcset_and_sizes(), which appends a second srcset instead of replacing the first one. --- php/class-delivery.php | 33 +++++- php/class-utils.php | 40 ++++++- php/media/class-filter.php | 36 ++++-- .../tests/test-delivery-parse-element.php | 29 +++++ tests/phpunit/tests/test-wp-core-apis.php | 109 ++++++++++++++++++ 5 files changed, 228 insertions(+), 19 deletions(-) create mode 100644 tests/phpunit/tests/test-wp-core-apis.php diff --git a/php/class-delivery.php b/php/class-delivery.php index 3e1a7f0f9..6974ae0a4 100644 --- a/php/class-delivery.php +++ b/php/class-delivery.php @@ -1455,7 +1455,7 @@ public function rebuild_tag( $tag_element ) { $meta['cloudinary_id'] = $relationship->public_id; $meta['transformations'] = $tag_element['transformations']; // Add new srcset. - $element = wp_image_add_srcset_and_sizes( $tag_element['original'], $meta, $tag_element['id'] ); + $element = wp_image_add_srcset_and_sizes( self::remove_tag_attribute( $tag_element['original'], 'srcset' ), $meta, $tag_element['id'] ); $atts = Utils::get_tag_attributes( $element ); if ( ! empty( $atts['srcset'] ) ) { @@ -1502,6 +1502,26 @@ public function rebuild_tag( $tag_element ) { return apply_filters( "cloudinary_{$tag_element['type']}_tag", $replace, $tag_element ); } + /** + * Remove an attribute from the first tag in an HTML string. + * + * Used before wp_image_add_srcset_and_sizes(), which appends a srcset and does not replace one + * that is already there. + * + * @param string $html The HTML. + * @param string $attribute The attribute name. + * + * @return string + */ + public static function remove_tag_attribute( $html, $attribute ) { + $processor = new \WP_HTML_Tag_Processor( $html ); + if ( $processor->next_tag() ) { + $processor->remove_attribute( $attribute ); + } + + return $processor->get_updated_html(); + } + /** * Parse an html element into tag, and attributes. * @@ -1560,12 +1580,13 @@ public function parse_element( $element, $content = '' ) { 'height' => 0, 'base_url' => '', ); - // Cleanup element. - $element = trim( $element, '' ); - // Break element up. - $attributes = shortcode_parse_atts( $element ); - $tag_element['tag'] = array_shift( $attributes ); + $parsed = Utils::parse_html_tag( $element ); + $attributes = $parsed['atts']; + $tag_element['tag'] = $parsed['tag']; + if ( '' === $tag_element['tag'] ) { + return null; + } // Skip audio source tags. if ( ! empty( $attributes['type'] ) && 0 === strpos( $attributes['type'], 'audio/' ) && 'source' === $tag_element['tag'] ) { diff --git a/php/class-utils.php b/php/class-utils.php index 1eea37430..988266221 100644 --- a/php/class-utils.php +++ b/php/class-utils.php @@ -144,11 +144,9 @@ public static function is_webstory_post_type( $post_type ) { * @return array */ public static function get_tag_attributes( $tag ) { - $tag = strstr( $tag, ' ', false ); - $tag = trim( $tag, '> ' ); - $args = shortcode_parse_atts( $tag ); + $parsed = self::parse_html_tag( (string) $tag ); $return = array(); - foreach ( $args as $key => $value ) { + foreach ( $parsed['atts'] as $key => $value ) { if ( is_int( $key ) ) { $return[ $value ] = 'true'; continue; @@ -159,6 +157,40 @@ public static function get_tag_attributes( $tag ) { return $return; } + /** + * Parse the first HTML tag in a string with the WordPress HTML API. + * + * Attribute names are lowercase and values are decoded. Boolean attributes use numeric keys, + * the same as shortcode_parse_atts(), so Component::build_attributes() writes them back as is. + * + * @param string $html The HTML that starts with the tag. + * + * @return array{tag: string, atts: array} + */ + public static function parse_html_tag( $html ) { + $parsed = array( + 'tag' => '', + 'atts' => array(), + ); + $processor = new \WP_HTML_Tag_Processor( (string) $html ); + if ( ! $processor->next_tag() ) { + return $parsed; + } + + $parsed['tag'] = strtolower( $processor->get_tag() ); + $names = $processor->get_attribute_names_with_prefix( '' ); + foreach ( (array) $names as $name ) { + $value = $processor->get_attribute( $name ); + if ( true === $value ) { + $parsed['atts'][] = $name; + continue; + } + $parsed['atts'][ $name ] = (string) $value; + } + + return $parsed; + } + /** * Get the depth of an array. * diff --git a/php/media/class-filter.php b/php/media/class-filter.php index dd2876d94..36c72df32 100644 --- a/php/media/class-filter.php +++ b/php/media/class-filter.php @@ -342,15 +342,7 @@ public function filter_out_local( $content, $tags = 'img' ) { // Add front end features. if ( ! is_admin() ) { - // Check if there is a class set. ( for srcset images in case of a manual url added ). - if ( false === strpos( $new_tag, ' class=' ) ) { - // Add in the class name. - $new_tag = str_replace( '/>', ' class="wp-image-' . $attachment_id . '"/>', $new_tag ); - } - // Apply lazy loading attribute. - if ( apply_filters( 'wp_lazy_loading_enabled', true ) && false === strpos( $new_tag, 'loading="lazy"' ) ) { - $new_tag = str_replace( '/>', ' loading="lazy" />', $new_tag ); - } + $new_tag = $this->add_front_end_attributes( $new_tag, $attachment_id ); // If Cloudinary player is active, this is replaced there. if ( ! $this->media->video->player_enabled() ) { @@ -370,6 +362,32 @@ public function filter_out_local( $content, $tags = 'img' ) { return $this->filter_video_shortcodes( $content ); } + /** + * Add the front end attributes to a media tag. + * + * The loading and fetchpriority attributes are not added here. This content is saved to the + * database, and a stored loading="lazy" would stop WordPress core from detecting the above the + * fold images when it renders the content with wp_filter_content_tags(). + * + * @param string $tag The media tag. + * @param int $attachment_id The attachment ID. + * + * @return string + */ + public function add_front_end_attributes( $tag, $attachment_id ) { + $processor = new \WP_HTML_Tag_Processor( $tag ); + if ( ! $processor->next_tag() ) { + return $tag; + } + + // Add the class name for srcset images, in case of a manual URL added. + if ( null === $processor->get_attribute( 'class' ) ) { + $processor->set_attribute( 'class', 'wp-image-' . (int) $attachment_id ); + } + + return $processor->get_updated_html(); + } + /** * Maybe get an alternate ID if this url is from an edited image. * diff --git a/tests/phpunit/tests/test-delivery-parse-element.php b/tests/phpunit/tests/test-delivery-parse-element.php index 38795a46b..afbcb5b35 100644 --- a/tests/phpunit/tests/test-delivery-parse-element.php +++ b/tests/phpunit/tests/test-delivery-parse-element.php @@ -156,6 +156,35 @@ public function data_custom_transformations() { ); } + /** + * The tag name and attributes are read with the HTML API, so a ">" in a value and an + * unquoted attribute do not break the parsing. + * + * @return void + */ + public function test_tag_is_parsed_with_the_html_api() { + $delivery = $this->get_delivery(); + $url = $this->seed_known( $delivery ); + + $element = $delivery->parse_element( 'a > b' ); + + $this->assertSame( 'img', $element['tag'] ); + $this->assertSame( 'image', $element['type'] ); + $this->assertSame( self::$attachment_id, $element['id'] ); + $this->assertSame( 'a > b', $element['atts']['alt'] ); + $this->assertSame( 'high', $element['atts']['fetchpriority'] ); + $this->assertSame( array( 'one', 'two' ), $element['atts']['class'] ); + } + + /** + * A string that is not a tag is skipped. + * + * @return void + */ + public function test_non_tag_is_skipped() { + $this->assertNull( $this->get_delivery()->parse_element( 'not a tag' ) ); + } + /** * A Cloudinary src for a public ID Delivery doesn't know is left alone. * diff --git a/tests/phpunit/tests/test-wp-core-apis.php b/tests/phpunit/tests/test-wp-core-apis.php new file mode 100644 index 000000000..77dde3eec --- /dev/null +++ b/tests/phpunit/tests/test-wp-core-apis.php @@ -0,0 +1,109 @@ + ok" data-x=\'1\' hidden />' ); + + $this->assertSame( 'img', $parsed['tag'] ); + $this->assertSame( 'https://example.com/a.jpg?a=1&b=2', $parsed['atts']['src'] ); + $this->assertSame( 'Tom "Jr" > ok', $parsed['atts']['alt'] ); + $this->assertSame( '1', $parsed['atts']['data-x'] ); + $this->assertContains( 'hidden', $parsed['atts'] ); + } + + /** + * Values are not unslashed, which shortcode_parse_atts() did through stripcslashes(). + * + * @return void + */ + public function test_parse_html_tag_keeps_backslashes() { + $parsed = Utils::parse_html_tag( 'C:\new\table' ); + + $this->assertSame( 'C:\new\table', $parsed['atts']['alt'] ); + } + + /** + * Invalid HTML gives an empty result. + * + * @return void + */ + public function test_parse_html_tag_without_a_tag_is_empty() { + $this->assertSame( + array( + 'tag' => '', + 'atts' => array(), + ), + Utils::parse_html_tag( 'no tag here' ) + ); + } + + /** + * Boolean attributes keep the "true" value that get_tag_attributes() always returned. + * + * @return void + */ + public function test_get_tag_attributes_flags_boolean_attributes() { + $attributes = Utils::get_tag_attributes( '' ); + + $this->assertSame( 'https://example.com/a.mp4', $attributes['src'] ); + $this->assertSame( 'true', $attributes['controls'] ); + $this->assertSame( 'true', $attributes['autoplay'] ); + } + + /** + * The old srcset is removed before core adds the Cloudinary one, so the tag never has two. + * + * @return void + */ + public function test_remove_tag_attribute_drops_only_that_attribute() { + $html = \Cloudinary\Delivery::remove_tag_attribute( 'srcset', 'srcset' ); + + $this->assertSame( 'srcset', $html ); + $this->assertSame( '

no img

', \Cloudinary\Delivery::remove_tag_attribute( '

no img

', 'srcset' ) ); + } + + /** + * A class is added to a tag without one, and the tag stays valid without a self closing slash. + * + * @return void + */ + public function test_front_end_attributes_add_the_class_without_a_closing_slash() { + $filter = ( new ReflectionClass( Filter::class ) )->newInstanceWithoutConstructor(); + $tag = $filter->add_front_end_attributes( '', 12 ); + + $this->assertSame( 'wp-image-12', Utils::get_tag_attributes( $tag )['class'] ); + $this->assertStringNotContainsString( 'loading=', $tag ); + } + + /** + * An existing class is kept. + * + * @return void + */ + public function test_front_end_attributes_keep_an_existing_class() { + $filter = ( new ReflectionClass( Filter::class ) )->newInstanceWithoutConstructor(); + $tag = $filter->add_front_end_attributes( '', 12 ); + + $this->assertSame( 'hero', Utils::get_tag_attributes( $tag )['class'] ); + } +} From 4b6ef86201dd27c56fb6ba1a0f81944231217140 Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Wed, 2 Dec 2026 13:28:48 +0530 Subject: [PATCH 3/8] perf(lazy-load): Skip above the fold images Cloudinary lazy load replaced every image with a placeholder, including the LCP image, which delays the largest paint. Follow the WordPress 6.3 loading optimization decisions instead: - An image with fetchpriority="high" is the LCP candidate and is never lazy loaded, so core's fetchpriority now takes effect. - An image with loading="lazy" or fetchpriority="low" is below the fold and is lazy loaded. - Other images count towards wp_omit_loading_attr_threshold (3 by default) in document order. The first ones load eagerly. The new cloudinary_lazy_load_in_initial_viewport filter can change the result per image. Delivery rebuilds the tag after core adds sizes="auto" (WP 6.7+), so run wp_img_tag_add_auto_sizes() on the rebuilt tag to keep it. The breakpoints e2e fixture now marks its image loading="lazy", as it is the only image in the post and would otherwise load eagerly. --- php/class-delivery.php | 5 + php/delivery/class-lazy-load.php | 74 +++++++++ .../cloudinary-breakpoints-lazy-load.spec.js | 5 +- tests/phpunit/tests/test-wp-core-apis.php | 147 +++++++++++++++++- 4 files changed, 228 insertions(+), 3 deletions(-) diff --git a/php/class-delivery.php b/php/class-delivery.php index 6974ae0a4..952578f5d 100644 --- a/php/class-delivery.php +++ b/php/class-delivery.php @@ -1482,6 +1482,11 @@ public function rebuild_tag( $tag_element ) { // Setup new tag. $replace = HTML::build_tag( $tag_element['tag'], $tag_element['atts'] ); + // The tag is rebuilt after core adds sizes="auto" to lazy loaded images (WP 6.7+), so add it back. + if ( 'img' === $tag_element['tag'] && function_exists( 'wp_img_tag_add_auto_sizes' ) ) { + $replace = wp_img_tag_add_auto_sizes( $replace ); + } + // If the original tag used single quotes, we need to use them in the new tag. $single_quotes = (bool) preg_match( '/=\s*\'/', $tag_element['original'] ); if ( $single_quotes ) { diff --git a/php/delivery/class-lazy-load.php b/php/delivery/class-lazy-load.php index 6118880d5..2236b62ae 100644 --- a/php/delivery/class-lazy-load.php +++ b/php/delivery/class-lazy-load.php @@ -35,6 +35,20 @@ class Lazy_Load extends Delivery_Feature { */ protected $enable_slug = 'use_lazy_load'; + /** + * The initial viewport results, keyed by the original tag. + * + * @var array + */ + protected $viewport_checked = array(); + + /** + * The number of images without a loading hint that were checked for the initial viewport. + * + * @var int + */ + protected $viewport_count = 0; + /** * Lazy_Load constructor. * @@ -88,6 +102,11 @@ public function bypass_lazy_load( $bypass, $tag_element ) { $bypass = true; } + // Do not lazy load the images that are likely to show above the fold. + if ( ! $bypass && $this->is_in_initial_viewport( $tag_element ) ) { + $bypass = true; + } + /** * Filter the classes that bypass lazy loading. * @@ -119,6 +138,61 @@ public function bypass_lazy_load( $bypass, $tag_element ) { return $bypass; } + /** + * Check if an image tag is likely to show in the initial viewport. + * + * This follows the decisions of WordPress core: an image marked with fetchpriority="high" is the + * LCP candidate, and an image marked with loading="lazy" is below the fold. Any other image + * counts towards the wp_omit_loading_attr_threshold, in document order. + * + * @param array $tag_element The tag element. + * + * @return bool + */ + public function is_in_initial_viewport( $tag_element ) { + if ( empty( $tag_element['tag'] ) || 'img' !== $tag_element['tag'] || Utils::is_admin() || Utils::is_frontend_ajax() ) { + return false; + } + + $checked = &$this->viewport_checked; + $original = isset( $tag_element['original'] ) ? $tag_element['original'] : ''; + if ( '' !== $original && isset( $checked[ $original ] ) ) { + return $checked[ $original ]; + } + + $atts = isset( $tag_element['atts'] ) ? $tag_element['atts'] : array(); + $loading = isset( $atts['loading'] ) ? strtolower( (string) $atts['loading'] ) : ''; + $fetchpriority = isset( $atts['fetchpriority'] ) ? strtolower( (string) $atts['fetchpriority'] ) : ''; + + if ( 'high' === $fetchpriority ) { + $in_viewport = true; + } elseif ( 'lazy' === $loading || 'low' === $fetchpriority ) { + $in_viewport = false; + } else { + $in_viewport = $this->viewport_count < wp_omit_loading_attr_threshold(); + ++$this->viewport_count; + } + + /** + * Filter if an image is in the initial viewport. Images in the initial viewport are not lazy loaded. + * + * @hook cloudinary_lazy_load_in_initial_viewport + * @since 3.3.10 + * + * @param bool $in_viewport True if the image is likely to show above the fold. + * @param array $tag_element The tag element. + * + * @return bool + */ + $in_viewport = (bool) apply_filters( 'cloudinary_lazy_load_in_initial_viewport', $in_viewport, $tag_element ); + + if ( '' !== $original ) { + $checked[ $original ] = $in_viewport; + } + + return $in_viewport; + } + /** * Get the inline script for lazy load. * diff --git a/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js b/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js index 364e920ef..99806fb62 100644 --- a/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js +++ b/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js @@ -184,9 +184,12 @@ test.describe( data: fs.readFileSync( FIXTURE_PATH ), } ); + // loading="lazy" marks the image as below the fold. Without it, the + // plugin follows WordPress core and does not lazy load the first + // images in the content. const content = `\n` + - `
\n` + + `
\n` + ``; const post = await requestUtils.rest( { diff --git a/tests/phpunit/tests/test-wp-core-apis.php b/tests/phpunit/tests/test-wp-core-apis.php index 77dde3eec..d29508b67 100644 --- a/tests/phpunit/tests/test-wp-core-apis.php +++ b/tests/phpunit/tests/test-wp-core-apis.php @@ -2,12 +2,13 @@ /** * Tests for the code that uses the WordPress 6.3+ core APIs. * - * Covers the HTML API tag parsing in Utils and Delivery, and the front end attributes that the - * content filter adds. + * Covers the HTML API tag parsing in Utils and Delivery, the front end attributes that the content + * filter adds, and the initial viewport check that keeps above the fold images out of lazy loading. * * @package Cloudinary */ +use Cloudinary\Delivery\Lazy_Load; use Cloudinary\Media\Filter; use Cloudinary\Utils; @@ -16,6 +17,45 @@ */ class Test_WP_Core_APIs extends WP_UnitTestCase { + /** + * Reset the filters after each test. + * + * @return void + */ + public function tear_down() { + remove_all_filters( 'wp_omit_loading_attr_threshold' ); + remove_all_filters( 'cloudinary_lazy_load_in_initial_viewport' ); + wp_omit_loading_attr_threshold( true ); + parent::tear_down(); + } + + /** + * Build a Lazy_Load instance without running its constructor, which needs a connected plugin. + * + * @return Lazy_Load + */ + protected function get_lazy_load() { + $reflection = new ReflectionClass( Lazy_Load::class ); + + return $reflection->newInstanceWithoutConstructor(); + } + + /** + * Build an img tag element like Delivery::parse_element() does. + * + * @param string $original The original tag. + * @param array $atts The attributes. + * + * @return array + */ + protected function tag_element( $original, array $atts = array() ) { + return array( + 'tag' => 'img', + 'original' => $original, + 'atts' => array_merge( array( 'class' => array() ), $atts ), + ); + } + /** * The HTML API parser decodes values, keeps boolean attributes, and reads the tag name. * @@ -82,6 +122,28 @@ public function test_remove_tag_attribute_drops_only_that_attribute() { $this->assertSame( '

no img

', \Cloudinary\Delivery::remove_tag_attribute( '

no img

', 'srcset' ) ); } + /** + * Core adds "auto" to the sizes of a lazy loaded image that Delivery rebuilt, and skips eager ones. + * + * @return void + */ + public function test_core_auto_sizes_on_a_rebuilt_tag() { + $lazy = \Cloudinary\UI\Component\HTML::build_tag( + 'img', + array( + 'src' => 'https://res.cloudinary.com/test-cloud/a.jpg', + 'width' => '300', + 'loading' => 'lazy', + 'srcset' => 'https://res.cloudinary.com/test-cloud/a.jpg 300w', + 'sizes' => '(max-width: 300px) 100vw, 300px', + ) + ); + $eager = str_replace( 'loading="lazy"', 'fetchpriority="high"', $lazy ); + + $this->assertSame( 'auto, (max-width: 300px) 100vw, 300px', Utils::get_tag_attributes( wp_img_tag_add_auto_sizes( $lazy ) )['sizes'] ); + $this->assertSame( $eager, wp_img_tag_add_auto_sizes( $eager ) ); + } + /** * A class is added to a tag without one, and the tag stays valid without a self closing slash. * @@ -106,4 +168,85 @@ public function test_front_end_attributes_keep_an_existing_class() { $this->assertSame( 'hero', Utils::get_tag_attributes( $tag )['class'] ); } + + /** + * The first images up to the core threshold are in the initial viewport. + * + * @return void + */ + public function test_initial_viewport_follows_the_core_threshold() { + add_filter( + 'wp_omit_loading_attr_threshold', + static function () { + return 2; + } + ); + wp_omit_loading_attr_threshold( true ); + + $lazy = $this->get_lazy_load(); + + $this->assertTrue( $lazy->is_in_initial_viewport( $this->tag_element( '' ) ) ); + $this->assertTrue( $lazy->is_in_initial_viewport( $this->tag_element( '' ) ) ); + $this->assertFalse( $lazy->is_in_initial_viewport( $this->tag_element( '' ) ) ); + // The same tag gives the same result. + $this->assertTrue( $lazy->is_in_initial_viewport( $this->tag_element( '' ) ) ); + } + + /** + * The core loading hints decide first, and do not count towards the threshold. + * + * @return void + */ + public function test_initial_viewport_follows_the_core_hints() { + add_filter( + 'wp_omit_loading_attr_threshold', + static function () { + return 1; + } + ); + wp_omit_loading_attr_threshold( true ); + + $lazy = $this->get_lazy_load(); + + $this->assertFalse( $lazy->is_in_initial_viewport( $this->tag_element( '', array( 'loading' => 'lazy' ) ) ) ); + $this->assertFalse( $lazy->is_in_initial_viewport( $this->tag_element( '', array( 'fetchpriority' => 'low' ) ) ) ); + $this->assertTrue( $lazy->is_in_initial_viewport( $this->tag_element( '', array( 'fetchpriority' => 'high' ) ) ) ); + $this->assertTrue( $lazy->is_in_initial_viewport( $this->tag_element( '' ) ) ); + $this->assertFalse( $lazy->is_in_initial_viewport( $this->tag_element( '' ) ) ); + } + + /** + * Only img tags are checked. + * + * @return void + */ + public function test_initial_viewport_ignores_other_tags() { + $element = $this->tag_element( '' ); + $element['tag'] = 'source'; + + $this->assertFalse( $this->get_lazy_load()->is_in_initial_viewport( $element ) ); + } + + /** + * The result can be filtered. + * + * @return void + */ + public function test_initial_viewport_is_filterable() { + add_filter( 'cloudinary_lazy_load_in_initial_viewport', '__return_false' ); + + $this->assertFalse( $this->get_lazy_load()->is_in_initial_viewport( $this->tag_element( '', array( 'fetchpriority' => 'high' ) ) ) ); + } + + /** + * Above the fold images bypass the Cloudinary lazy load. + * + * @return void + */ + public function test_bypass_lazy_load_for_the_lcp_candidate() { + $lazy = $this->get_lazy_load(); + + $this->assertTrue( $lazy->bypass_lazy_load( false, $this->tag_element( '', array( 'fetchpriority' => 'high' ) ) ) ); + $this->assertFalse( $lazy->bypass_lazy_load( false, $this->tag_element( '', array( 'loading' => 'lazy' ) ) ) ); + } } From cd53de4bcc612b509de5cd1f07f56cde88794a90 Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Wed, 2 Dec 2026 14:43:38 +0530 Subject: [PATCH 4/8] fix(delivery): Keep backslashes in the tag cache The HTML API parser keeps backslashes in attribute values, which shortcode_parse_atts() used to strip. update_post_meta() unslashes the value, so the cached replacement for alt="C:\new" was saved as alt="C:new" and a cached page rendered a different tag than an uncached one. Slash the replacements before they are saved, and move the write into Delivery::update_context_cache() so it can be tested. --- php/class-delivery.php | 17 +++++++++-- tests/phpunit/tests/test-wp-core-apis.php | 36 +++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/php/class-delivery.php b/php/class-delivery.php index 952578f5d..60153d54e 100644 --- a/php/class-delivery.php +++ b/php/class-delivery.php @@ -1201,14 +1201,25 @@ function ( $tag ) use ( $content ) { // Update the post meta cache. if ( is_singular() ) { - $has_cache = array(); - $has_cache[ $type ] = $replacements; - update_post_meta( get_the_ID(), self::META_CACHE_KEY, $has_cache ); + $this->update_context_cache( $type, $replacements ); } return $replacements; } + /** + * Save the replacements to the post meta cache of the current post. + * + * @param string $type The cache type (http, https or amp). + * @param array $replacements The replacements, keyed by the original tag or URL. + */ + protected function update_context_cache( $type, $replacements ) { + $has_cache = array(); + $has_cache[ $type ] = $replacements; + // update_post_meta() unslashes the value, which would drop the backslashes in the tags. + update_post_meta( get_the_ID(), self::META_CACHE_KEY, wp_slash( $has_cache ) ); + } + /** * Cleanup and standardize the tag element structure. * diff --git a/tests/phpunit/tests/test-wp-core-apis.php b/tests/phpunit/tests/test-wp-core-apis.php index d29508b67..3d9541517 100644 --- a/tests/phpunit/tests/test-wp-core-apis.php +++ b/tests/phpunit/tests/test-wp-core-apis.php @@ -82,6 +82,24 @@ public function test_parse_html_tag_keeps_backslashes() { $this->assertSame( 'C:\new\table', $parsed['atts']['alt'] ); } + /** + * The replacement cache keeps the backslashes that the HTML API parser now keeps, so a cached + * page renders the same tag as an uncached one. + * + * @return void + */ + public function test_replacement_cache_keeps_backslashes() { + $post_id = self::factory()->post->create(); + $this->go_to( get_permalink( $post_id ) ); + + $delivery = new Test_WP_Core_APIs_Delivery( \Cloudinary\get_plugin_instance() ); + $tag = 'C:\new'; + $delivery->update_context_cache( 'https', array( '' => $tag ) ); + + $cache = get_post_meta( $post_id, \Cloudinary\Delivery::META_CACHE_KEY, true ); + $this->assertSame( $tag, $cache['https'][''] ); + } + /** * Invalid HTML gives an empty result. * @@ -250,3 +268,21 @@ public function test_bypass_lazy_load_for_the_lcp_candidate() { $this->assertFalse( $lazy->bypass_lazy_load( false, $this->tag_element( '', array( 'loading' => 'lazy' ) ) ) ); } } + +/** + * Delivery with the cache write made public for the test. + */ +class Test_WP_Core_APIs_Delivery extends \Cloudinary\Delivery { + + /** + * Save the replacements to the post meta cache. + * + * @param string $type The cache type. + * @param array $replacements The replacements. + * + * @return void + */ + public function update_context_cache( $type, $replacements ) { + parent::update_context_cache( $type, $replacements ); + } +} From a83a8bada6740a2b60abb5ede063628c95976190 Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Wed, 2 Dec 2026 15:00:06 +0530 Subject: [PATCH 5/8] test(e2e): Expect core sizes="auto" on lazy images The breakpoints fixture image is now natively lazy loaded, and Delivery keeps the "auto" that WordPress 6.7+ adds to the sizes of lazy loaded images. Update the expected sizes attribute. --- tests/e2e/cloudinary-breakpoints-lazy-load.spec.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js b/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js index 99806fb62..7e680cb51 100644 --- a/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js +++ b/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js @@ -268,8 +268,10 @@ test.describe( } } + // The image is natively lazy loaded, so WordPress 6.7+ prefixes + // `auto`, and the rebuilt tag keeps it. expect( attrs.sizes ).toBe( - `(max-width: ${ FIXTURE_WIDTH }px) 100vw, ${ FIXTURE_WIDTH }px` + `auto, (max-width: ${ FIXTURE_WIDTH }px) 100vw, ${ FIXTURE_WIDTH }px` ); } ); From 72331ec06f84ff9373785b48bb2fcf4bd22c498c Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Wed, 2 Dec 2026 16:51:55 +0530 Subject: [PATCH 6/8] fix(delivery): Address review findings - Video blocks: replace the src and poster through the HTML API in the new Video::replace_tag_urls(). get_tag_attributes() now returns decoded values, so str_replace() missed URLs with "&" in the HTML and left the local URL when the Cloudinary player is off. - Stop loading the plugin on WordPress below 6.3 and show a notice. The header only blocks activation from the admin, not updates with Composer or a zip file. - Clear the replacement cache on cloudinary_version_upgrade. Cached tags skip rebuild_tag(), so pages kept the old markup. - Check the lazy load bypass classes before the viewport check, so bypassed images do not use up the eager places. - Call _deprecated_function() in the deprecated video callback. - Move remove_tag_attribute() to Utils. - Tests: skip the sizes="auto" test before WP 6.7, compare attributes instead of exact markup, parse tags through get_media_tags(), cover the new code, and add an e2e case for the first image. --- cloudinary.php | 39 ++++++++-- php/class-delivery.php | 37 ++++----- php/class-utils.php | 17 ++++ php/delivery/class-lazy-load.php | 17 ++-- php/media/class-video.php | 39 +++++++++- .../cloudinary-breakpoints-lazy-load.spec.js | 43 ++++++++++- .../tests/test-delivery-parse-element.php | 29 +++++-- .../phpunit/tests/test-video-replace-urls.php | 77 +++++++++++++++++++ tests/phpunit/tests/test-wp-core-apis.php | 54 ++++++++++++- 9 files changed, 304 insertions(+), 48 deletions(-) create mode 100644 tests/phpunit/tests/test-video-replace-urls.php diff --git a/cloudinary.php b/cloudinary.php index fefa7f6b6..6bcd959e6 100644 --- a/cloudinary.php +++ b/cloudinary.php @@ -38,29 +38,29 @@ define( 'CLDN_CORE', __FILE__ ); define( 'CLDN_PATH', plugin_dir_path( __FILE__ ) ); -if ( version_compare( phpversion(), '7.4', '>=' ) ) { +if ( '' === version_requirement_text() ) { require_once __DIR__ . '/instance.php'; register_activation_hook( __FILE__, array( 'Cloudinary\Utils', 'install' ) ); register_deactivation_hook( __FILE__, array( 'Cloudinary\Analytics', 'record_deactivation' ) ); } else { // phpcs:ignore Universal.ControlStructures.DisallowLonelyIf.Found if ( defined( 'WP_CLI' ) ) { - WP_CLI::warning( php_version_text() ); + WP_CLI::warning( version_requirement_text() ); } else { add_action( 'admin_notices', __NAMESPACE__ . '\php_version_error' ); } } /** - * Admin notice for incompatible versions of PHP. + * Admin notice for incompatible versions of PHP or WordPress. */ function php_version_error() { if ( function_exists( 'wp_admin_notice' ) ) { - wp_admin_notice( esc_html( php_version_text() ), array( 'type' => 'error' ) ); + wp_admin_notice( esc_html( version_requirement_text() ), array( 'type' => 'error' ) ); return; } - printf( '

%s

', esc_html( php_version_text() ) ); + printf( '

%s

', esc_html( version_requirement_text() ) ); } /** @@ -71,3 +71,32 @@ function php_version_error() { function php_version_text() { return __( 'Cloudinary plugin error: Your version of PHP is too old to run this plugin. You must be running PHP 7.4 or higher.', 'cloudinary' ); } + +/** + * String describing the minimum WordPress version. + * + * The plugin header only stops activation from the admin. Sites that update with Composer or a + * zip file still load the plugin, so this check stops it before it calls newer core APIs. + * + * @return string + */ +function wp_version_text() { + return __( 'Cloudinary plugin error: Your version of WordPress is too old to run this plugin. You must be running WordPress 6.3 or higher.', 'cloudinary' ); +} + +/** + * Get the message for the first version requirement that is not met. + * + * @return string An empty string when all requirements are met. + */ +function version_requirement_text() { + if ( version_compare( phpversion(), '7.4', '<' ) ) { + return php_version_text(); + } + + if ( version_compare( get_bloginfo( 'version' ), '6.3', '<' ) ) { + return wp_version_text(); + } + + return ''; +} diff --git a/php/class-delivery.php b/php/class-delivery.php index 60153d54e..cdfb3e983 100644 --- a/php/class-delivery.php +++ b/php/class-delivery.php @@ -134,6 +134,19 @@ public function __construct( Plugin $plugin ) { $this->plugin = $plugin; add_action( 'cloudinary_connected', array( $this, 'init' ) ); + add_action( 'cloudinary_version_upgrade', array( $this, 'clear_replacement_cache' ) ); + } + + /** + * Clear the replacement cache after a plugin update. + * + * The cached tags skip rebuild_tag(), so without this, a page keeps the markup of the old + * version until the post is saved or the delivery settings change. + * + * @hook cloudinary_version_upgrade + */ + public function clear_replacement_cache() { + $this->do_clear_cache( false ); } /** @@ -1465,8 +1478,8 @@ public function rebuild_tag( $tag_element ) { $meta['overwrite_transformations'] = $tag_element['overwrite_transformations']; $meta['cloudinary_id'] = $relationship->public_id; $meta['transformations'] = $tag_element['transformations']; - // Add new srcset. - $element = wp_image_add_srcset_and_sizes( self::remove_tag_attribute( $tag_element['original'], 'srcset' ), $meta, $tag_element['id'] ); + // Add new srcset. Remove the old one first, as core appends a srcset and does not replace it. + $element = wp_image_add_srcset_and_sizes( Utils::remove_tag_attribute( $tag_element['original'], 'srcset' ), $meta, $tag_element['id'] ); $atts = Utils::get_tag_attributes( $element ); if ( ! empty( $atts['srcset'] ) ) { @@ -1518,26 +1531,6 @@ public function rebuild_tag( $tag_element ) { return apply_filters( "cloudinary_{$tag_element['type']}_tag", $replace, $tag_element ); } - /** - * Remove an attribute from the first tag in an HTML string. - * - * Used before wp_image_add_srcset_and_sizes(), which appends a srcset and does not replace one - * that is already there. - * - * @param string $html The HTML. - * @param string $attribute The attribute name. - * - * @return string - */ - public static function remove_tag_attribute( $html, $attribute ) { - $processor = new \WP_HTML_Tag_Processor( $html ); - if ( $processor->next_tag() ) { - $processor->remove_attribute( $attribute ); - } - - return $processor->get_updated_html(); - } - /** * Parse an html element into tag, and attributes. * diff --git a/php/class-utils.php b/php/class-utils.php index 988266221..13fe94ec3 100644 --- a/php/class-utils.php +++ b/php/class-utils.php @@ -191,6 +191,23 @@ public static function parse_html_tag( $html ) { return $parsed; } + /** + * Remove an attribute from the first tag in an HTML string. + * + * @param string $html The HTML. + * @param string $attribute The attribute name. + * + * @return string + */ + public static function remove_tag_attribute( $html, $attribute ) { + $processor = new \WP_HTML_Tag_Processor( (string) $html ); + if ( $processor->next_tag() ) { + $processor->remove_attribute( $attribute ); + } + + return $processor->get_updated_html(); + } + /** * Get the depth of an array. * diff --git a/php/delivery/class-lazy-load.php b/php/delivery/class-lazy-load.php index 2236b62ae..faeffa1b1 100644 --- a/php/delivery/class-lazy-load.php +++ b/php/delivery/class-lazy-load.php @@ -102,11 +102,6 @@ public function bypass_lazy_load( $bypass, $tag_element ) { $bypass = true; } - // Do not lazy load the images that are likely to show above the fold. - if ( ! $bypass && $this->is_in_initial_viewport( $tag_element ) ) { - $bypass = true; - } - /** * Filter the classes that bypass lazy loading. * @@ -135,6 +130,12 @@ public function bypass_lazy_load( $bypass, $tag_element ) { $bypass = true; } + // Do not lazy load the images that are likely to show above the fold. This runs last, so the + // images bypassed above do not count towards the threshold. + if ( ! $bypass && $this->is_in_initial_viewport( $tag_element ) ) { + $bypass = true; + } + return $bypass; } @@ -150,7 +151,7 @@ public function bypass_lazy_load( $bypass, $tag_element ) { * @return bool */ public function is_in_initial_viewport( $tag_element ) { - if ( empty( $tag_element['tag'] ) || 'img' !== $tag_element['tag'] || Utils::is_admin() || Utils::is_frontend_ajax() ) { + if ( empty( $tag_element['tag'] ) || 'img' !== $tag_element['tag'] ) { return false; } @@ -160,6 +161,10 @@ public function is_in_initial_viewport( $tag_element ) { return $checked[ $original ]; } + if ( Utils::is_admin() || Utils::is_frontend_ajax() ) { + return false; + } + $atts = isset( $tag_element['atts'] ) ? $tag_element['atts'] : array(); $loading = isset( $atts['loading'] ) ? strtolower( (string) $atts['loading'] ) : ''; $fetchpriority = isset( $atts['fetchpriority'] ) ? strtolower( (string) $atts['fetchpriority'] ) : ''; diff --git a/php/media/class-video.php b/php/media/class-video.php index 40fc7505d..9831d2d02 100644 --- a/php/media/class-video.php +++ b/php/media/class-video.php @@ -203,6 +203,8 @@ public function admin_enqueue_scripts() { * @return string */ public function filter_video_block_render_block( $block_content, array $block ) { + _deprecated_function( __METHOD__, '3.3.10', __CLASS__ . '::filter_video_block_pre_render()' ); + if ( 'core/video' === $block['blockName'] ) { remove_filter( 'render_block', array( $this, 'filter_video_block_render_block' ), 10 ); @@ -215,6 +217,33 @@ public function filter_video_block_render_block( $block_content, array $block ) return $block_content; } + /** + * Replace the src and poster URLs of the first video tag in an HTML string. + * + * The URLs are compared decoded, as Utils::get_tag_attributes() returns them, so a URL with + * "&" in the HTML still matches. + * + * @param string $html The HTML that contains the video tag. + * @param array $replacements The new URLs, keyed by the decoded old URL. + * + * @return string + */ + public function replace_tag_urls( $html, $replacements ) { + $processor = new \WP_HTML_Tag_Processor( $html ); + if ( ! $processor->next_tag( array( 'tag_name' => 'VIDEO' ) ) ) { + return $html; + } + + foreach ( array( 'src', 'poster' ) as $name ) { + $value = $processor->get_attribute( $name ); + if ( is_string( $value ) && ! empty( $replacements[ $value ] ) ) { + $processor->set_attribute( $name, $replacements[ $value ] ); + } + } + + return $processor->get_updated_html(); + } + /** * Recursively check if a block contains a video. * @@ -261,8 +290,10 @@ public function filter_video_block_pre_render( $block, $source_block ) { unset( $attributes['src'] ); $content = $this->build_video_embed( $attachment_id, $attributes, $overwrite_transformations ); } else { - $url = $this->media->cloudinary_url( $attachment_id ); - $content = str_replace( $attributes['src'], $url, $content ); + $replacements = array(); + if ( ! empty( $attributes['src'] ) ) { + $replacements[ $attributes['src'] ] = $this->media->cloudinary_url( $attachment_id ); + } if ( ! empty( $attributes['poster'] ) ) { // Maybe local URL. @@ -270,10 +301,12 @@ public function filter_video_block_pre_render( $block, $source_block ) { $post_id = Utils::attachment_url_to_postid( $attributes['poster'] ); $url = $this->media->cloudinary_url( $post_id ); if ( $url ) { - $content = str_replace( $attributes['poster'], $url, $content ); + $replacements[ $attributes['poster'] ] = $url; } } } + + $content = $this->replace_tag_urls( $content, $replacements ); } } } elseif ( $this->player_enabled() ) { diff --git a/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js b/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js index 7e680cb51..f2d1bbc54 100644 --- a/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js +++ b/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js @@ -133,16 +133,17 @@ function attachmentWidths( attachmentId ) { * * @param {import('@playwright/test').Browser} browser * @param {string} baseURL + * @param {string} [postLink] Post to load. Defaults to the lazy fixture post. * @return {Promise<{ attrs: Record, html: string }>} Image attributes and the page HTML. */ -async function serverMarkup( browser, baseURL ) { +async function serverMarkup( browser, baseURL, postLink = created.postLink ) { const context = await browser.newContext( { baseURL, javaScriptEnabled: false, } ); try { const page = await context.newPage(); - await page.goto( created.postLink ); + await page.goto( postLink ); const img = page .locator( `.wp-block-image img.wp-image-${ created.attachmentId }` ) .first(); @@ -202,10 +203,24 @@ test.describe( }, } ); + // The same image with no loading hint, as the first image of the + // content. WordPress counts it as above the fold. + const eagerPost = await requestUtils.rest( { + method: 'POST', + path: '/wp/v2/posts', + data: { + status: 'publish', + title: `Cloudinary above the fold e2e ${ Date.now() }`, + content: content.replace( ' loading="lazy"', '' ), + }, + } ); + created = { postId: post.id, + eagerPostId: eagerPost.id, attachmentId: media.id, postLink: post.link, + eagerPostLink: eagerPost.link, }; // Same reason as the image delivery spec: sync synchronously @@ -221,12 +236,12 @@ test.describe( if ( ! created ) { return; } - const { postId, attachmentId } = created; + const { postId, eagerPostId, attachmentId } = created; created = null; // WP-CLI rather than REST for the same reason as the image // delivery spec: `force=true` on a `?rest_route=` URL is fragile. - for ( const id of [ postId, attachmentId ] ) { + for ( const id of [ postId, eagerPostId, attachmentId ] ) { try { wpCli( [ 'post', 'delete', String( id ), '--force' ] ); } catch ( e ) { @@ -363,6 +378,26 @@ test.describe( expectCloudinaryUrl( await img.getAttribute( 'src' ), cloudName ); } ); + test( 'lazy load skips the first image above the fold', async ( { + browser, + baseURL, + } ) => { + configure( { breakpoints: true, lazyLoad: true } ); + + const { attrs } = await serverMarkup( + browser, + baseURL, + created.eagerPostLink + ); + + // WordPress does not lazy load the first content images, so the + // plugin serves the Cloudinary URL straight from the server. + expect( attrs[ 'data-cloudinary' ] ).toBeUndefined(); + expect( attrs.loading ).toBeUndefined(); + expectCloudinaryUrl( attrs.src, cloudName ); + expect( attrs[ 'data-public-id' ] ).toBeTruthy(); + } ); + test( 'disabling lazy load removes the placeholder markup', async ( { browser, baseURL, diff --git a/tests/phpunit/tests/test-delivery-parse-element.php b/tests/phpunit/tests/test-delivery-parse-element.php index afbcb5b35..e48bcad3b 100644 --- a/tests/phpunit/tests/test-delivery-parse-element.php +++ b/tests/phpunit/tests/test-delivery-parse-element.php @@ -157,25 +157,44 @@ public function data_custom_transformations() { } /** - * The tag name and attributes are read with the HTML API, so a ">" in a value and an - * unquoted attribute do not break the parsing. + * A tag found in content is read with the HTML API: the tag name is lowercase, an unquoted + * attribute is read, and an encoded value is decoded. * * @return void */ - public function test_tag_is_parsed_with_the_html_api() { + public function test_tag_from_content_is_parsed_with_the_html_api() { $delivery = $this->get_delivery(); $url = $this->seed_known( $delivery ); + $content = '

a > b & c

'; - $element = $delivery->parse_element( 'a > b' ); + $tags = $delivery->get_media_tags( $content, 'img' ); + $element = $delivery->parse_element( reset( $tags ), $content ); $this->assertSame( 'img', $element['tag'] ); $this->assertSame( 'image', $element['type'] ); $this->assertSame( self::$attachment_id, $element['id'] ); - $this->assertSame( 'a > b', $element['atts']['alt'] ); + $this->assertSame( 'a > b & c', $element['atts']['alt'] ); $this->assertSame( 'high', $element['atts']['fetchpriority'] ); $this->assertSame( array( 'one', 'two' ), $element['atts']['class'] ); } + /** + * A raw ">" in a value makes get_media_tags() cut the tag short. The incomplete tag is skipped, + * so no broken markup is built from it. + * + * @return void + */ + public function test_tag_cut_short_by_a_raw_greater_than_is_skipped() { + $delivery = $this->get_delivery(); + $url = $this->seed_known( $delivery ); + $content = '

a > b

'; + + $tags = $delivery->get_media_tags( $content, 'img' ); + + $this->assertSame( 'a >', reset( $tags ) );
+		$this->assertNull( $delivery->parse_element( reset( $tags ), $content ) );
+	}
+
 	/**
 	 * A string that is not a tag is skipped.
 	 *
diff --git a/tests/phpunit/tests/test-video-replace-urls.php b/tests/phpunit/tests/test-video-replace-urls.php
new file mode 100644
index 000000000..d4a140373
--- /dev/null
+++ b/tests/phpunit/tests/test-video-replace-urls.php
@@ -0,0 +1,77 @@
+<?php
+/**
+ * Tests for Cloudinary\Media\Video::replace_tag_urls().
+ *
+ * The video block filter swaps the local src and poster URLs for Cloudinary ones when the
+ * Cloudinary player is off. The URLs are read decoded through the HTML API, so the swap has to
+ * work on attributes, not on the raw HTML, where newInstanceWithoutConstructor(); + } + + /** + * A src with an entity encoded query string is replaced. + * + * @return void + */ + public function test_entity_encoded_src_is_replaced() { + $html = '
'; + + $new = $this->get_video()->replace_tag_urls( + $html, + array( 'https://example.com/a.mp4?a=1&b=2' => 'https://res.cloudinary.com/demo/video/upload/a.mp4' ) + ); + + $this->assertStringContainsString( 'src="https://res.cloudinary.com/demo/video/upload/a.mp4"', $new ); + $this->assertStringNotContainsString( 'example.com', $new ); + $this->assertStringContainsString( '
', $new ); + } + + /** + * The poster is replaced too, and an attribute with another value is left alone. + * + * @return void + */ + public function test_poster_is_replaced_and_other_attributes_kept() { + $html = ''; + + $new = $this->get_video()->replace_tag_urls( + $html, + array( + 'https://example.com/a.mp4' => 'https://res.cloudinary.com/demo/a.mp4', + 'https://example.com/p.jpg?x=1&y=2' => 'https://res.cloudinary.com/demo/p.jpg', + ) + ); + + $this->assertStringContainsString( 'src="https://res.cloudinary.com/demo/a.mp4"', $new ); + $this->assertStringContainsString( 'poster="https://res.cloudinary.com/demo/p.jpg"', $new ); + $this->assertStringContainsString( 'data-x="https://example.com/a.mp4?keep"', $new ); + } + + /** + * HTML without a video tag is returned as is. + * + * @return void + */ + public function test_html_without_a_video_is_unchanged() { + $html = '

No video

'; + + $this->assertSame( $html, $this->get_video()->replace_tag_urls( $html, array( 'a' => 'b' ) ) ); + } +} diff --git a/tests/phpunit/tests/test-wp-core-apis.php b/tests/phpunit/tests/test-wp-core-apis.php index 3d9541517..0be534be3 100644 --- a/tests/phpunit/tests/test-wp-core-apis.php +++ b/tests/phpunit/tests/test-wp-core-apis.php @@ -134,10 +134,16 @@ public function test_get_tag_attributes_flags_boolean_attributes() { * @return void */ public function test_remove_tag_attribute_drops_only_that_attribute() { - $html = \Cloudinary\Delivery::remove_tag_attribute( 'srcset', 'srcset' ); + $html = Utils::remove_tag_attribute( 'srcset', 'srcset' ); - $this->assertSame( 'srcset', $html ); - $this->assertSame( '

no img

', \Cloudinary\Delivery::remove_tag_attribute( '

no img

', 'srcset' ) ); + $this->assertSame( + array( + 'src' => 'a.jpg', + 'alt' => 'srcset', + ), + Utils::get_tag_attributes( $html ) + ); + $this->assertSame( '

no img

', Utils::remove_tag_attribute( '

no img

', 'srcset' ) ); } /** @@ -146,6 +152,10 @@ public function test_remove_tag_attribute_drops_only_that_attribute() { * @return void */ public function test_core_auto_sizes_on_a_rebuilt_tag() { + if ( ! function_exists( 'wp_img_tag_add_auto_sizes' ) ) { + $this->markTestSkipped( 'wp_img_tag_add_auto_sizes() needs WordPress 6.7 or higher.' ); + } + $lazy = \Cloudinary\UI\Component\HTML::build_tag( 'img', array( @@ -256,6 +266,44 @@ public function test_initial_viewport_is_filterable() { $this->assertFalse( $this->get_lazy_load()->is_in_initial_viewport( $this->tag_element( '', array( 'fetchpriority' => 'high' ) ) ) ); } + /** + * Images with a bypass class do not use up the eager places of the threshold. + * + * @return void + */ + public function test_bypass_class_images_do_not_count_towards_the_threshold() { + add_filter( + 'wp_omit_loading_attr_threshold', + static function () { + return 1; + } + ); + wp_omit_loading_attr_threshold( true ); + + $lazy = $this->get_lazy_load(); + + $skipped = $this->tag_element( '', array( 'class' => array( 'cld-bypass-lazy' ) ) ); + $this->assertTrue( $lazy->bypass_lazy_load( false, $skipped ) ); + $this->assertTrue( $lazy->bypass_lazy_load( false, $this->tag_element( '' ) ) ); + $this->assertFalse( $lazy->bypass_lazy_load( false, $this->tag_element( '' ) ) ); + } + + /** + * A plugin update clears the replacement cache, so pages are rebuilt with the new markup. + * + * @return void + */ + public function test_version_upgrade_clears_the_replacement_cache() { + $post_id = self::factory()->post->create(); + update_post_meta( $post_id, \Cloudinary\Delivery::META_CACHE_KEY, array( 'https' => array( 'a' => 'b' ) ) ); + + $delivery = new \Cloudinary\Delivery( \Cloudinary\get_plugin_instance() ); + $delivery->clear_replacement_cache(); + + $this->assertSame( '', get_post_meta( $post_id, \Cloudinary\Delivery::META_CACHE_KEY, true ) ); + $this->assertNotFalse( has_action( 'cloudinary_version_upgrade', array( $delivery, 'clear_replacement_cache' ) ) ); + } + /** * Above the fold images bypass the Cloudinary lazy load. * From 024fd9fd2ba2b699cc0d23f18a0e45c6d291385a Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Thu, 3 Dec 2026 15:26:08 +0530 Subject: [PATCH 7/8] chore(release): Tag new APIs for 3.4.0 The new lazy load filter and the deprecated video callback ship in 3.4.0, not 3.3.10. --- php/delivery/class-lazy-load.php | 2 +- php/media/class-video.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/php/delivery/class-lazy-load.php b/php/delivery/class-lazy-load.php index faeffa1b1..29e5000fc 100644 --- a/php/delivery/class-lazy-load.php +++ b/php/delivery/class-lazy-load.php @@ -182,7 +182,7 @@ public function is_in_initial_viewport( $tag_element ) { * Filter if an image is in the initial viewport. Images in the initial viewport are not lazy loaded. * * @hook cloudinary_lazy_load_in_initial_viewport - * @since 3.3.10 + * @since 3.4.0 * * @param bool $in_viewport True if the image is likely to show above the fold. * @param array $tag_element The tag element. diff --git a/php/media/class-video.php b/php/media/class-video.php index 9831d2d02..6cab94a09 100644 --- a/php/media/class-video.php +++ b/php/media/class-video.php @@ -195,7 +195,7 @@ public function admin_enqueue_scripts() { /** * Fallback for render_block_data filter. * - * @deprecated 3.3.10 The render_block_data filter is always available on the supported WordPress versions. + * @deprecated 3.4.0 The render_block_data filter is always available on the supported WordPress versions. * * @param string $block_content The block content about to be appended. * @param array $block The full block, including name and attributes. @@ -203,7 +203,7 @@ public function admin_enqueue_scripts() { * @return string */ public function filter_video_block_render_block( $block_content, array $block ) { - _deprecated_function( __METHOD__, '3.3.10', __CLASS__ . '::filter_video_block_pre_render()' ); + _deprecated_function( __METHOD__, '3.4.0', __CLASS__ . '::filter_video_block_pre_render()' ); if ( 'core/video' === $block['blockName'] ) { remove_filter( 'render_block', array( $this, 'filter_video_block_render_block' ), 10 ); From b6f8c3fce5a66d82506a2fdabc9060afea55c31d Mon Sep 17 00:00:00 2001 From: Utkarsh Patel Date: Thu, 3 Dec 2026 21:06:12 +0530 Subject: [PATCH 8/8] fix(lazy-load): Follow core and keep counts out of cache - Treat an image core processed and left without a loading attribute as eager, without counting it. Core adds decoding="async" to every image it processes and only decides the loading of images with a width and height. Only images core never saw, such as header and template images, count towards the threshold. Before, a logo and header images used up the threshold and the first content image was lazy loaded against core's decision. - Leave the counted tags, and tags whose result the viewport filter changed, out of the replacement cache. Their result depends on the page, and the cache of one post is reused on archives and loops. - Escape attribute values that are unchanged from the original tag with double encoding on, so a value showing entity text, such as alt="Use &lt;img&gt;", is not decoded one level too far. --- php/class-delivery.php | 11 +- php/class-utils.php | 33 +++++ php/delivery/class-lazy-load.php | 64 ++++++++- tests/phpunit/tests/test-wp-core-apis.php | 159 ++++++++++++++++++++++ 4 files changed, 262 insertions(+), 5 deletions(-) diff --git a/php/class-delivery.php b/php/class-delivery.php index cdfb3e983..0a46f2297 100644 --- a/php/class-delivery.php +++ b/php/class-delivery.php @@ -13,6 +13,7 @@ use Cloudinary\Media\Global_Transformations; use Cloudinary\UI\Component\HTML; use Cloudinary\Delivery\Bypass; +use Cloudinary\Delivery\Lazy_Load; use Cloudinary\Relate\Relationship; /** @@ -907,7 +908,7 @@ public function process_featured_image( $html, $post_id, $attachment_id ) { $tag_element['atts']['class'][] = 'cld-overwrite'; } - $new_tag = HTML::build_tag( $tag_element['tag'], $tag_element['atts'] ); + $new_tag = HTML::build_tag( $tag_element['tag'], Utils::escape_original_attributes( $tag_element['atts'], $tag_element['original'] ) ); $html = str_replace( $tag_element['original'], $new_tag, $html ); } @@ -1227,6 +1228,12 @@ function ( $tag ) use ( $content ) { * @param array $replacements The replacements, keyed by the original tag or URL. */ protected function update_context_cache( $type, $replacements ) { + // Lazy loading of these tags depends on their position on this page, so they are rebuilt on every page. + $lazy_load = $this->plugin->get_component( 'lazy_load' ); + if ( $lazy_load instanceof Lazy_Load ) { + $replacements = array_diff_key( $replacements, array_flip( $lazy_load->get_position_dependent_tags() ) ); + } + $has_cache = array(); $has_cache[ $type ] = $replacements; // update_post_meta() unslashes the value, which would drop the backslashes in the tags. @@ -1504,7 +1511,7 @@ public function rebuild_tag( $tag_element ) { $tag_element = apply_filters( "cloudinary_pre_{$tag_element['type']}_tag", $tag_element ); // Setup new tag. - $replace = HTML::build_tag( $tag_element['tag'], $tag_element['atts'] ); + $replace = HTML::build_tag( $tag_element['tag'], Utils::escape_original_attributes( $tag_element['atts'], $tag_element['original'] ) ); // The tag is rebuilt after core adds sizes="auto" to lazy loaded images (WP 6.7+), so add it back. if ( 'img' === $tag_element['tag'] && function_exists( 'wp_img_tag_add_auto_sizes' ) ) { diff --git a/php/class-utils.php b/php/class-utils.php index 13fe94ec3..f559c2c15 100644 --- a/php/class-utils.php +++ b/php/class-utils.php @@ -191,6 +191,39 @@ public static function parse_html_tag( $html ) { return $parsed; } + /** + * Escape the attribute values that are unchanged from an original tag, so they render as before. + * + * The values from parse_html_tag() are decoded. Component::build_attributes() escapes them again with + * esc_attr(), which does not encode the entities it finds, so a value that shows entity text + * (alt="Use &lt;img&gt;", shown as "Use <img>") would be decoded one level too + * far and render as "Use ". Escaping it here with double encoding on restores it. + * + * Values that differ from the original tag are left as they are, as other code may pass them + * already escaped. A value with no "&" is left as is too, as esc_attr() handles it the same way. + * + * @param array $atts The attributes to build the tag from. + * @param string $original The original tag the attributes were parsed from. + * + * @return array + */ + public static function escape_original_attributes( $atts, $original ) { + $original_atts = self::parse_html_tag( (string) $original )['atts']; + foreach ( $atts as $name => $value ) { + if ( + is_string( $name ) + && is_string( $value ) + && false !== strpos( $value, '&' ) + && isset( $original_atts[ $name ] ) + && $original_atts[ $name ] === $value + ) { + $atts[ $name ] = htmlspecialchars( $value, ENT_QUOTES, get_bloginfo( 'charset' ), true ); + } + } + + return $atts; + } + /** * Remove an attribute from the first tag in an HTML string. * diff --git a/php/delivery/class-lazy-load.php b/php/delivery/class-lazy-load.php index 29e5000fc..f1e0007dc 100644 --- a/php/delivery/class-lazy-load.php +++ b/php/delivery/class-lazy-load.php @@ -49,6 +49,13 @@ class Lazy_Load extends Delivery_Feature { */ protected $viewport_count = 0; + /** + * The original tags whose result depends on their position on the page, as keys. + * + * @var array + */ + protected $position_dependent = array(); + /** * Lazy_Load constructor. * @@ -142,9 +149,19 @@ public function bypass_lazy_load( $bypass, $tag_element ) { /** * Check if an image tag is likely to show in the initial viewport. * - * This follows the decisions of WordPress core: an image marked with fetchpriority="high" is the - * LCP candidate, and an image marked with loading="lazy" is below the fold. Any other image - * counts towards the wp_omit_loading_attr_threshold, in document order. + * This follows the markup WordPress core outputs, as it sees the page in parts (content, header + * template part, featured image, ...) and the plugin only sees the final HTML: + * + * - fetchpriority="high" is the LCP candidate: eager. + * - loading="lazy" or fetchpriority="low" is below the fold: lazy. + * - An image core processed with no loading attribute is eager, without counting. Core adds + * decoding="async" to every image it processes, and only decides the loading of images with a + * width and height, so such an image without a loading attribute is one core left eager. + * - Any other image, which core never processed, counts towards wp_omit_loading_attr_threshold in + * document order. This also applies to every image when native lazy loading is disabled with the + * wp_lazy_loading_enabled filter, as a missing loading attribute then means nothing. + * + * Only the counted images depend on their position on the page. See get_position_dependent_tags(). * * @param array $tag_element The tag element. * @@ -169,18 +186,26 @@ public function is_in_initial_viewport( $tag_element ) { $loading = isset( $atts['loading'] ) ? strtolower( (string) $atts['loading'] ) : ''; $fetchpriority = isset( $atts['fetchpriority'] ) ? strtolower( (string) $atts['fetchpriority'] ) : ''; + $counted = false; if ( 'high' === $fetchpriority ) { $in_viewport = true; } elseif ( 'lazy' === $loading || 'low' === $fetchpriority ) { $in_viewport = false; + } elseif ( $this->is_left_eager_by_core( $original ) ) { + $in_viewport = true; } else { $in_viewport = $this->viewport_count < wp_omit_loading_attr_threshold(); ++$this->viewport_count; + $counted = true; } + $computed = $in_viewport; /** * Filter if an image is in the initial viewport. Images in the initial viewport are not lazy loaded. * + * A tag whose result this filter changes is not saved in the replacement cache, so the filter + * runs again on every page that shows it. + * * @hook cloudinary_lazy_load_in_initial_viewport * @since 3.4.0 * @@ -193,11 +218,44 @@ public function is_in_initial_viewport( $tag_element ) { if ( '' !== $original ) { $checked[ $original ] = $in_viewport; + if ( $counted || $computed !== $in_viewport ) { + $this->position_dependent[ $original ] = true; + } } return $in_viewport; } + /** + * Get the original tags whose lazy loading depends on where they are on the page. + * + * These are the tags counted towards the threshold, and the tags whose result was changed by the + * cloudinary_lazy_load_in_initial_viewport filter. They must not be cached with the replacement, + * as the same tag can be above the fold on one page and below it on another. + * + * @return string[] + */ + public function get_position_dependent_tags() { + return array_keys( $this->position_dependent ); + } + + /** + * Check if WordPress core processed an image tag and left it without a loading attribute. + * + * @param string $original The original image tag. + * + * @return bool + */ + protected function is_left_eager_by_core( $original ) { + if ( '' === $original || ! wp_lazy_loading_enabled( 'img', 'the_content' ) ) { + return false; + } + + $atts = Utils::parse_html_tag( $original )['atts']; + + return isset( $atts['decoding'], $atts['width'], $atts['height'] ) && ! isset( $atts['loading'] ); + } + /** * Get the inline script for lazy load. * diff --git a/tests/phpunit/tests/test-wp-core-apis.php b/tests/phpunit/tests/test-wp-core-apis.php index 0be534be3..966edbf10 100644 --- a/tests/phpunit/tests/test-wp-core-apis.php +++ b/tests/phpunit/tests/test-wp-core-apis.php @@ -304,6 +304,165 @@ public function test_version_upgrade_clears_the_replacement_cache() { $this->assertNotFalse( has_action( 'cloudinary_version_upgrade', array( $delivery, 'clear_replacement_cache' ) ) ); } + /** + * Header and template images that core never processed must not use up the eager places of a content + * image core already left eager. + * + * @return void + */ + public function test_image_left_eager_by_core_is_eager_and_not_counted() { + add_filter( + 'wp_omit_loading_attr_threshold', + static function () { + return 1; + } + ); + wp_omit_loading_attr_threshold( true ); + + $lazy = $this->get_lazy_load(); + + // A logo and a header image that core never processed use up the threshold. + $this->assertTrue( $lazy->is_in_initial_viewport( $this->tag_element( '' ) ) ); + $this->assertFalse( $lazy->is_in_initial_viewport( $this->tag_element( '' ) ) ); + + // The first content image, which core processed and left without a loading attribute, stays eager. + $content = ''; + $this->assertTrue( $lazy->is_in_initial_viewport( $this->tag_element( $content ) ) ); + + // A content image core lazy loaded stays lazy. + $below = ''; + $this->assertFalse( $lazy->is_in_initial_viewport( $this->tag_element( $below, array( 'loading' => 'lazy' ) ) ) ); + } + + /** + * Core only decides the loading of images with a width and height, and only adds the attribute when native lazy + * loading is on. In both other cases, a missing loading attribute means nothing, so the image is counted. + * + * @return void + */ + public function test_missing_loading_attribute_only_counts_as_core_decision_when_core_decided() { + add_filter( + 'wp_omit_loading_attr_threshold', + static function () { + return 0; + } + ); + wp_omit_loading_attr_threshold( true ); + + $lazy = $this->get_lazy_load(); + + // No width and height: core didn't decide, so it is counted, and lazy with a threshold of 0. + $this->assertFalse( $lazy->is_in_initial_viewport( $this->tag_element( '' ) ) ); + + // Native lazy loading off: core adds no loading attribute anywhere, so it is counted too. + add_filter( 'wp_lazy_loading_enabled', '__return_false' ); + $this->assertFalse( $lazy->is_in_initial_viewport( $this->tag_element( '' ) ) ); + remove_filter( 'wp_lazy_loading_enabled', '__return_false' ); + } + + /** + * Only the tags whose result depends on their position on the page are reported, so only those are kept out of + * the replacement cache. + * + * @return void + */ + public function test_only_position_dependent_tags_are_reported() { + add_filter( + 'wp_omit_loading_attr_threshold', + static function () { + return 1; + } + ); + wp_omit_loading_attr_threshold( true ); + + $lazy = $this->get_lazy_load(); + $counted = ''; + $core = ''; + $hinted = ''; + + $lazy->is_in_initial_viewport( $this->tag_element( $counted ) ); + $lazy->is_in_initial_viewport( $this->tag_element( $core ) ); + $lazy->is_in_initial_viewport( $this->tag_element( $hinted, array( 'fetchpriority' => 'high' ) ) ); + + $this->assertSame( array( $counted ), $lazy->get_position_dependent_tags() ); + + // A tag whose result the filter changes is reported too, as the filter may depend on the page. + add_filter( 'cloudinary_lazy_load_in_initial_viewport', '__return_false' ); + $filtered = ''; + $lazy->is_in_initial_viewport( $this->tag_element( $filtered ) ); + $this->assertContains( $filtered, $lazy->get_position_dependent_tags() ); + } + + /** + * Position dependent tags are left out of the replacement cache, so they are rebuilt on every page. + * + * @return void + */ + public function test_replacement_cache_skips_position_dependent_tags() { + $post_id = self::factory()->post->create(); + $this->go_to( get_permalink( $post_id ) ); + + $plugin = \Cloudinary\get_plugin_instance(); + $lazy = $this->get_lazy_load(); + $counted = ''; + $core = ''; + $lazy->is_in_initial_viewport( $this->tag_element( $counted ) ); + $lazy->is_in_initial_viewport( $this->tag_element( $core ) ); + + $previous = isset( $plugin->components['lazy_load'] ) ? $plugin->components['lazy_load'] : null; + $plugin->components['lazy_load'] = $lazy; + try { + $delivery = new Test_WP_Core_APIs_Delivery( $plugin ); + $delivery->update_context_cache( + 'https', + array( + $counted => '', + $core => '', + 'https:' => 'alias', + ) + ); + } finally { + $plugin->components['lazy_load'] = $previous; + } + + $cache = get_post_meta( $post_id, \Cloudinary\Delivery::META_CACHE_KEY, true ); + $this->assertArrayNotHasKey( $counted, $cache['https'] ); + $this->assertSame( '', $cache['https'][ $core ] ); + $this->assertSame( 'alias', $cache['https']['https:'] ); + } + + /** + * A value that shows entity text keeps its meaning through the parse and rebuild round trip. + * + * @return void + */ + public function test_unchanged_attributes_keep_their_entities() { + $original = 'Use &lt;img&gt;'; + $atts = Utils::parse_html_tag( $original )['atts']; + $this->assertSame( 'Use <img>', $atts['alt'] ); + + // The plugin changes the src; the alt and title are unchanged. + $atts['src'] = 'https://res.cloudinary.com/demo/a.jpg?x=1&y=2'; + $built = \Cloudinary\UI\Component\HTML::build_tag( 'img', Utils::escape_original_attributes( $atts, $original ) ); + + $rebuilt = Utils::parse_html_tag( $built )['atts']; + $this->assertSame( 'Use <img>', $rebuilt['alt'], 'The alt must still show the entity text, not a real tag.' ); + $this->assertSame( 'Tom & Jerry', $rebuilt['title'] ); + $this->assertSame( 'https://res.cloudinary.com/demo/a.jpg?x=1&y=2', $rebuilt['src'] ); + } + + /** + * A value another filter changed is left as it is, as it may already be escaped. + * + * @return void + */ + public function test_changed_attributes_are_not_escaped_again() { + $original = 'Old & value'; + $atts = array( 'alt' => 'New & value' ); + + $this->assertSame( $atts, Utils::escape_original_attributes( $atts, $original ) ); + } + /** * Above the fold images bypass the Cloudinary lazy load. *