Skip to content

REST API: Add 'scaled' to sideload route image_size enum#11015

Open
adamsilverstein wants to merge 20 commits intoWordPress:trunkfrom
adamsilverstein:add-scaled-to-sideload-route
Open

REST API: Add 'scaled' to sideload route image_size enum#11015
adamsilverstein wants to merge 20 commits intoWordPress:trunkfrom
adamsilverstein:add-scaled-to-sideload-route

Conversation

@adamsilverstein
Copy link
Member

@adamsilverstein adamsilverstein commented Feb 23, 2026

Summary

When client-side media processing handles big image scaling, the client creates a -scaled version and sideloads it back via the REST API. The sideload route's image_size enum was missing scaled, causing 400 validation errors.

This PR:

  • Adds 'scaled' to the image_size enum in the sideload route registration
  • Adds handling in sideload_item() to record the original file as original_image and update the attachment to point to the scaled version
  • Updates the filter_wp_unique_filename() regex to recognize the -scaled suffix, preventing unwanted numeric suffixes

Test plan

  • Upload a large image (>2560px) with client-side media processing enabled
  • Confirm the scaled sideload request no longer returns a 400 error
  • Verify that other sideload image_sizes (thumbnail, medium, etc.) still work
  • Verify the attachment metadata correctly records original_image and the scaled file dimensions
  • Test with and without the Gutenberg plugin active

Trac ticket: https://core.trac.wordpress.org/ticket/64737

When client-side media processing handles big image scaling,
the client creates a -scaled version and sideloads it back.
The sideload route's image_size enum was missing 'scaled',
causing 400 validation errors.

This adds 'scaled' to the enum, adds handling in sideload_item()
to record the original file and update the attachment to point
to the scaled version, and updates the unique filename filter
regex to recognize the -scaled suffix.
@github-actions
Copy link

github-actions bot commented Feb 23, 2026

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

Core Committers: Use this line as a base for the props when committing in SVN:

Props adamsilverstein, huzaifaalmesbah, westonruter.

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

@github-actions
Copy link

Test using WordPress Playground

The changes in this pull request can previewed and tested using a WordPress Playground instance.

WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Some things to be aware of

  • All changes will be lost when closing a tab with a Playground instance.
  • All changes will be lost when refreshing the page.
  • A fresh instance is created each time the link below is clicked.
  • Every time this pull request is updated, a new ZIP file containing all changes is created. If changes are not reflected in the Playground instance,
    it's possible that the most recent build failed, or has not completed. Check the list of workflow runs to be sure.

For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation.

Test this pull request with WordPress Playground.

adamsilverstein and others added 5 commits February 26, 2026 18:15
Add 'scaled' to the image_size enum in wp-api-generated.js to match the
PHP route registration change, fixing the git diff --exit-code CI check.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add tests for the new 'scaled' image_size enum value in the sideload
endpoint: verifying metadata updates, authentication requirements,
route schema, and unique filename handling for the -scaled suffix.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
get_attached_file() can return false when no file is
attached. Add a guard to return a WP_Error before calling
wp_basename() with a falsy value.
The sideload route uses edit_media_item_permissions_check
which returns rest_cannot_edit_image, not rest_forbidden.
@adamsilverstein adamsilverstein requested review from huzaifaalmesbah, swissspidy and westonruter and removed request for huzaifaalmesbah March 2, 2026 04:24

$matches = array();
if ( preg_match( '/(.*)(-\d+x\d+)-' . $number . '$/', $name, $matches ) ) {
if ( preg_match( '/(.*)(-\d+x\d+|-scaled)-' . $number . '$/', $name, $matches ) ) {
Copy link
Member

Choose a reason for hiding this comment

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

According to the PHPDoc, $number can be a string. When? What would it be in that case? Does it need to be escaped?

Copy link
Member Author

Choose a reason for hiding this comment

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

maybe it can't be a string, let me check. escaping is rarely a bad idea.

Copy link
Member Author

Choose a reason for hiding this comment

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

I decided to cast this as int for safety. According to Claude here is the logic (and why it can be a string):

Looking at wp_unique_filename() in src/wp-includes/functions.php:

  • $number is initialized as '' (empty string) at line 2561
  • Set to integer 1 at line 2588 when the filename matches a subsize pattern
  • Incremented via (int) $number + 1 in while loops (lines 2624, 2697, 2758)
  • Passed to the wp_unique_filename filter at line 2799

Possible values: empty string '' or positive integers (1, 2, 3, ...).

Copy link
Member Author

@adamsilverstein adamsilverstein Mar 3, 2026

Choose a reason for hiding this comment

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

Copy link
Member

Choose a reason for hiding this comment

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

Ah, I see. It passes an empty string in case it is not used, per the phpdoc. In that case, what about:

--- a/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php
+++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php
@@ -2135,7 +2135,7 @@ class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller {
 	 * @return string Filtered file name.
 	 */
 	private static function filter_wp_unique_filename( $filename, $dir, $number, $attachment_filename ) {
-		if ( empty( $number ) || ! $attachment_filename ) {
+		if ( ! is_int( $number ) || ! $attachment_filename ) {
 			return $filename;
 		}
 
@@ -2148,7 +2148,7 @@ class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller {
 		}
 
 		$matches = array();
-		if ( preg_match( '/(.*)(-\d+x\d+|-scaled)-' . (int) $number . '$/', $name, $matches ) ) {
+		if ( preg_match( '/(.*)(-\d+x\d+|-scaled)-' . $number . '$/', $name, $matches ) ) {
 			$filename_without_suffix = $matches[1] . $matches[2] . ".$ext";
 			if ( $matches[1] === $orig_name && ! file_exists( "$dir/$filename_without_suffix" ) ) {
 				return $filename_without_suffix;

Copy link
Member Author

Choose a reason for hiding this comment

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

updated

Addresses review feedback to assert the value of
metadata['file'], not just its existence.
Avoids repeating the string literal for the array key
in the enum assertion test.
@adamsilverstein adamsilverstein self-assigned this Mar 3, 2026
Verifies that sideloading a scaled image retains the
numeric suffix when a file with the same name already
exists from a different attachment.
The $number parameter in filter_wp_unique_filename is
typed as int|string. Casting to (int) before interpolation
into the preg_match pattern ensures regex safety regardless
of any future changes to what $number might contain.
@adamsilverstein
Copy link
Member Author

@westonruter I believe I have addressed all of your feedback. Thanks!


$metadata['width'] = $size ? $size[0] : 0;
$metadata['height'] = $size ? $size[1] : 0;
$metadata['filesize'] = wp_filesize( $path );
Copy link
Member

Choose a reason for hiding this comment

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

Note that wp_filesize() is filterable and can return 0. Does it make sense to proceed with any of this if any of these are zero?

Should these checks be done first and then if all of them aren't zero, then proceed with update_attached_file( $attachment_id, $path )? Otherwise, if one is zero, short-circuit with an error?

Copy link
Member Author

Choose a reason for hiding this comment

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

maybe, let me check the existing pattern in core since i'm just trying to store meta data for the image.


$matches = array();
if ( preg_match( '/(.*)(-\d+x\d+)-' . $number . '$/', $name, $matches ) ) {
if ( preg_match( '/(.*)(-\d+x\d+|-scaled)-' . (int) $number . '$/', $name, $matches ) ) {
Copy link
Member

Choose a reason for hiding this comment

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

cf. changes done in #11100

Copy link
Member Author

@adamsilverstein adamsilverstein Mar 3, 2026

Choose a reason for hiding this comment

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

I'll move the changes there here, the change belongs here

adamsilverstein and others added 7 commits March 3, 2026 16:58
Co-authored-by: Weston Ruter <westonruter@gmail.com>
Co-authored-by: Weston Ruter <westonruter@gmail.com>
Check whether _wp_attached_file already matches $path before
calling update_attached_file(), since a false return could
mean the value is unchanged. Return a WP_Error when the meta
value differs but the update still fails.
Per review feedback, use ! is_int( $number ) as the guard
since $number is either an int or an empty string. This is
more precise than empty() and allows removing the (int) cast
in the regex since $number is guaranteed to be an int.
Checks image dimensions and filesize before calling
update_attached_file() to avoid leaving the attachment
in a bad state if the scaled file is unreadable or empty.
Move the literal dash outside the capture group so the regex
reads `/(.*)-(\d+x\d+|scaled)-/` instead of alternating
`(-\d+x\d+|-scaled)`. This keeps the dash handling consistent
and simplifies the filename reconstruction.

Props westonruter.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Copy link
Member

@westonruter westonruter left a comment

Choose a reason for hiding this comment

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

One last suggestion, but otherwise pre-approving.


// Update the attached file to point to the scaled version.
if (
get_post_meta( $attachment_id, '_wp_attached_file', true ) !== $path &&
Copy link
Member

Choose a reason for hiding this comment

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

Gemini wisely pointed out that the _wp_attached_file post meta is stored as a relative path, whereas $path is an absolute path. So this actually will never be equal. It suggests this instead, which also looks cleaner:

Suggested change
get_post_meta( $attachment_id, '_wp_attached_file', true ) !== $path &&
get_attached_file( $attachment_id, true ) !== $path &&

The true prevents filters from applying.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants