diff --git a/cloudinary.php b/cloudinary.php
index fa6a53a10..6bcd959e6 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+
@@ -36,23 +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() {
- printf( '
', esc_html( php_version_text() ) );
+ if ( function_exists( 'wp_admin_notice' ) ) {
+ wp_admin_notice( esc_html( version_requirement_text() ), array( 'type' => 'error' ) );
+
+ return;
+ }
+
+ printf( '', esc_html( version_requirement_text() ) );
}
/**
@@ -63,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 3e1a7f0f9..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;
/**
@@ -134,6 +135,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 );
}
/**
@@ -894,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 );
}
@@ -1201,14 +1215,31 @@ 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 ) {
+ // 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.
+ update_post_meta( get_the_ID(), self::META_CACHE_KEY, wp_slash( $has_cache ) );
+ }
+
/**
* Cleanup and standardize the tag element structure.
*
@@ -1454,8 +1485,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( $tag_element['original'], $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'] ) ) {
@@ -1480,7 +1511,12 @@ 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' ) ) {
+ $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'] );
@@ -1560,12 +1596,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-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..f559c2c15 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,90 @@ 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;
+ }
+
+ /**
+ * 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 <img>", 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.
+ *
+ * @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.
*
@@ -545,15 +627,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 +842,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/delivery/class-lazy-load.php b/php/delivery/class-lazy-load.php
index 6118880d5..f1e0007dc 100644
--- a/php/delivery/class-lazy-load.php
+++ b/php/delivery/class-lazy-load.php
@@ -35,6 +35,27 @@ 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;
+
+ /**
+ * The original tags whose result depends on their position on the page, as keys.
+ *
+ * @var array
+ */
+ protected $position_dependent = array();
+
/**
* Lazy_Load constructor.
*
@@ -116,9 +137,125 @@ 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;
}
+ /**
+ * Check if an image tag is likely to show in the initial viewport.
+ *
+ * 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.
+ *
+ * @return bool
+ */
+ public function is_in_initial_viewport( $tag_element ) {
+ if ( empty( $tag_element['tag'] ) || 'img' !== $tag_element['tag'] ) {
+ return false;
+ }
+
+ $checked = &$this->viewport_checked;
+ $original = isset( $tag_element['original'] ) ? $tag_element['original'] : '';
+ if ( '' !== $original && isset( $checked[ $original ] ) ) {
+ 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'] ) : '';
+
+ $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
+ *
+ * @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;
+ 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/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/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..6cab94a09 100644
--- a/php/media/class-video.php
+++ b/php/media/class-video.php
@@ -195,12 +195,16 @@ public function admin_enqueue_scripts() {
/**
* Fallback for render_block_data filter.
*
+ * @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.
*
* @return string
*/
public function filter_video_block_render_block( $block_content, array $block ) {
+ _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 );
@@ -213,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.
*
@@ -259,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.
@@ -268,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() ) {
@@ -626,12 +661,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
diff --git a/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js b/tests/e2e/cloudinary-breakpoints-lazy-load.spec.js
index 364e920ef..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();
@@ -184,9 +185,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( {
@@ -199,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
@@ -218,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 ) {
@@ -265,8 +283,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`
);
} );
@@ -358,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 38795a46b..e48bcad3b 100644
--- a/tests/phpunit/tests/test-delivery-parse-element.php
+++ b/tests/phpunit/tests/test-delivery-parse-element.php
@@ -156,6 +156,54 @@ public function data_custom_transformations() {
);
}
+ /**
+ * 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_from_content_is_parsed_with_the_html_api() {
+ $delivery = $this->get_delivery();
+ $url = $this->seed_known( $delivery );
+ $content = '
';
+
+ $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 & 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 = '
';
+
+ $tags = $delivery->get_media_tags( $content, 'img' );
+
+ $this->assertSame( '
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
new file mode 100644
index 000000000..966edbf10
--- /dev/null
+++ b/tests/phpunit/tests/test-wp-core-apis.php
@@ -0,0 +1,495 @@
+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.
+ *
+ * @return void
+ */
+ public function test_parse_html_tag_reads_tag_and_attributes() {
+ $parsed = Utils::parse_html_tag( '
' );
+
+ $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( '
' );
+
+ $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 = '
';
+ $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.
+ *
+ * @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 = Utils::remove_tag_attribute( '
', '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' ) );
+ }
+
+ /**
+ * 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() {
+ 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(
+ '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.
+ *
+ * @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'] );
+ }
+
+ /**
+ * 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' ) ) ) );
+ }
+
+ /**
+ * 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' ) ) );
+ }
+
+ /**
+ * 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 = '
';
+ $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 = '
';
+ $atts = array( 'alt' => 'New & value' );
+
+ $this->assertSame( $atts, Utils::escape_original_attributes( $atts, $original ) );
+ }
+
+ /**
+ * 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' ) ) ) );
+ }
+}
+
+/**
+ * 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 );
+ }
+}