Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions cloudinary.php
Original file line number Diff line number Diff line change
Expand Up @@ -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+
Expand Down Expand Up @@ -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( '<div class="error"><p>%s</p></div>', esc_html( php_version_text() ) );
if ( function_exists( 'wp_admin_notice' ) ) {
wp_admin_notice( esc_html( version_requirement_text() ), array( 'type' => 'error' ) );

return;
}

printf( '<div class="notice notice-error"><p>%s</p></div>', esc_html( version_requirement_text() ) );
}

/**
Expand All @@ -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 '';
}
61 changes: 49 additions & 12 deletions php/class-delivery.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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 );
}

/**
Expand Down Expand Up @@ -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 );
}

Expand Down Expand Up @@ -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 );

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The above-the-fold decision depends on where the image sits on the page, but the result ends up in this cache, keyed only by the original tag. get_context_cache() then merges the caches of every post that went through the_post, so a decision made on one page gets reused on another:

  • Archives / blog home: each post's cache comes from its singular view, where its first image was eager. On an archive with 10 posts, the first image of post 8 is still served eager (no placeholder), even though it is far below the fold.
  • Related posts / query loops on a singular page: the same thing happens for the posts in the loop.
  • Mixed cached/uncached: cached tags skip rebuild_tag(), so they never increment viewport_count. An uncached image further down the page starts counting from 0 and can be made eager too.

Before this PR the lazy/eager result didn't depend on position, so caching the rebuilt tag was safe. Now it isn't.

A few options:

  1. Keep the viewport decision out of the cache. For example, cache the lazy version and apply the eager bypass when the replacements are applied.
  2. Don't cache img tags that went through the viewport check (simple, but we lose some of the cache benefit).
  3. Only apply the viewport check when the cache we read was written for the current post (is_singular() and the current queried object).

I don't mind which. What do you think?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, you're right. I had checked this on the blog home before, but only for images core marks loading="lazy" on the archive, where the tag differs and so does the cache key. Your case, where core leaves the tag the same and only our count differs, does leak.

Fixed in b6f8c3f with a mix of your options 1 and 2:

  • With the change for your other comment, an image core processed is decided from its own markup (fetchpriority, loading, or core's decoding="async" with no loading). The tag is the cache key, so that decision is safe to cache: when core decides differently on another page, the tag differs too.
  • Only the tags counted towards the threshold, and the tags whose result the cloudinary_lazy_load_in_initial_viewport filter changed, depend on the page. Those are now left out of _cld_replacements, so they are rebuilt on every page. That should also cover the mixed cached/uncached case, as a counted tag is never read from the cache, so it is always counted (I haven't tested that case separately).

Checked on the local site, with the post's cache cleared, then written by a visit to the single post: the blog home listing that post rendered exactly the same eager/lazy result as before the cache existed. Note this post's content images all come through core, so none of them is counted; the "counted tags are left out" part is covered by test_replacement_cache_skips_position_dependent_tags, not by this check.

}

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.
*
Expand Down Expand Up @@ -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'] ) ) {
Expand All @@ -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'] );
Expand Down Expand Up @@ -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'] ) {
Expand Down
7 changes: 2 additions & 5 deletions php/class-media.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
}

Expand Down Expand Up @@ -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 );
}

Expand Down
2 changes: 1 addition & 1 deletion php/class-sync.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down
108 changes: 88 additions & 20 deletions php/class-utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<int|string, string>}
*/
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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit / edge case: values are now decoded here, and HTML::build_tag() writes them back with esc_attr(), which does not double-encode existing entities. So a value that contains entity text gets decoded one level too far on the round trip. For example, alt="Use &amp;lt;img&amp;gt;" (an alt text that literally shows &lt;img&gt;) is decoded to Use &lt;img&gt;, and esc_attr() keeps it as is, so the browser now shows Use <img>.

It's a rare case and I wouldn't block on it, but since rebuild_tag() writes every attribute back, it might be worth either encoding the decoded values with double-encoding on (htmlspecialchars( $value, ENT_QUOTES, 'UTF-8', true )) when the tag is rebuilt, or adding a line about it in the Merge Danger section next to the backslash note.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in b6f8c3f. rebuild_tag() and process_featured_image() now escape the attribute values that are unchanged from the original tag with double encoding on (Utils::escape_original_attributes()), so alt="Use &amp;lt;img&amp;gt;" comes out the same as it went in. Values another filter changed (e.g. on cloudinary_pre_image_tag) are left as they are, as they may already be escaped, and so are values with no &.

There are 6 new unit tests across the three fixes. On the previous commit, 5 fail; the sixth (test_missing_loading_attribute_only_counts_as_core_decision_when_core_decided) guards the fallback case and passes on both. Unit tests (148), phpcs, PHPStan and the image, video, asset edit and breakpoints e2e specs (10 tests) pass locally.

}

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 &amp;lt;img&amp;gt;", shown as "Use &lt;img&gt;") would be decoded one level too
* far and render as "Use <img>". 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.
*
Expand Down Expand Up @@ -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( "<script type='text/javascript'>%s</script>\n", $javascript ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
wp_print_inline_script_tag( $javascript );
}

/**
Expand Down Expand Up @@ -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 );
}

/**
Expand Down
2 changes: 1 addition & 1 deletion php/connect/class-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down
Loading
Loading