Skip to content
Merged
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
3 changes: 3 additions & 0 deletions backport-changelog/7.0/11015.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
https://github.com/WordPress/wordpress-develop/pull/11015

* https://github.com/WordPress/gutenberg/pull/75817
86 changes: 53 additions & 33 deletions lib/media/class-gutenberg-rest-attachments-controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,41 +20,44 @@ class Gutenberg_REST_Attachments_Controller extends WP_REST_Attachments_Controll
public function register_routes(): void {
parent::register_routes();

// Only register the sideload route if the parent class doesn't already have it.
if ( ! method_exists( get_parent_class( $this ), 'sideload_item' ) ) {
$valid_image_sizes = array_keys( wp_get_registered_image_subsizes() );

// Special case to set 'original_image' in attachment metadata.
$valid_image_sizes[] = 'original';
// Used for PDF thumbnails.
$valid_image_sizes[] = 'full';

register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<id>[\d]+)/sideload',
// Override the parent's sideload route so that 'scaled' is included
// in the image_size enum. Without the override, core's handler
// validates first and rejects 'scaled' before ours is tried.
$valid_image_sizes = array_keys( wp_get_registered_image_subsizes() );

// Special case to set 'original_image' in attachment metadata.
$valid_image_sizes[] = 'original';
// Client-side big image threshold: sideload the scaled version.
$valid_image_sizes[] = 'scaled';
// Used for PDF thumbnails.
$valid_image_sizes[] = 'full';

register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<id>[\d]+)/sideload',
array(
array(
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'sideload_item' ),
'permission_callback' => array( $this, 'sideload_item_permissions_check' ),
'args' => array(
'id' => array(
'description' => __( 'Unique identifier for the attachment.', 'gutenberg' ),
'type' => 'integer',
),
'image_size' => array(
'description' => __( 'Image size.', 'gutenberg' ),
'type' => 'string',
'enum' => $valid_image_sizes,
'required' => true,
),
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'sideload_item' ),
'permission_callback' => array( $this, 'sideload_item_permissions_check' ),
'args' => array(
'id' => array(
'description' => __( 'Unique identifier for the attachment.', 'gutenberg' ),
'type' => 'integer',
),
'image_size' => array(
'description' => __( 'Image size.', 'gutenberg' ),
'type' => 'string',
'enum' => $valid_image_sizes,
'required' => true,
),
),
'allow_batch' => $this->allow_batch,
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
),
'allow_batch' => $this->allow_batch,
'schema' => array( $this, 'get_public_item_schema' ),
),
true // Override core's route so 'scaled' is included in the enum.
);
}

/**
Expand Down Expand Up @@ -210,6 +213,8 @@ public function create_item( $request ) {
// Disable server-side EXIF rotation so the client can handle it.
// This preserves the original orientation value in the metadata.
add_filter( 'wp_image_maybe_exif_rotate', '__return_false', 100 );
// Disable server-side big image scaling since the client handles it.
add_filter( 'big_image_size_threshold', '__return_zero', 100 );
}

if ( ! $request['convert_format'] ) {
Expand All @@ -221,6 +226,7 @@ public function create_item( $request ) {
remove_filter( 'intermediate_image_sizes_advanced', '__return_empty_array', 100 );
remove_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 );
remove_filter( 'wp_image_maybe_exif_rotate', '__return_false', 100 );
remove_filter( 'big_image_size_threshold', '__return_zero', 100 );
remove_filter( 'image_editor_output_format', '__return_empty_array', 100 );

return $response;
Expand Down Expand Up @@ -275,7 +281,7 @@ private static function filter_wp_unique_filename( $filename, $dir, $number, $at
}

$matches = array();
if ( preg_match( '/(.*)(-\d+x\d+)-' . $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;
Expand Down Expand Up @@ -381,6 +387,20 @@ public function sideload_item( WP_REST_Request $request ) {

if ( 'original' === $image_size ) {
$metadata['original_image'] = wp_basename( $path );
} elseif ( 'scaled' === $image_size ) {
// The current attached file is the original; record it as original_image.
$current_file = get_attached_file( $attachment_id, true );
$metadata['original_image'] = wp_basename( $current_file );

// Update the attached file to point to the scaled version.
update_attached_file( $attachment_id, $path );

$size = wp_getimagesize( $path );

$metadata['width'] = $size ? $size[0] : 0;
$metadata['height'] = $size ? $size[1] : 0;
$metadata['filesize'] = wp_filesize( $path );
$metadata['file'] = _wp_relative_upload_path( $path );
} else {
$metadata['sizes'] = $metadata['sizes'] ?? array();

Expand Down
69 changes: 51 additions & 18 deletions packages/upload-media/src/store/private-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -717,22 +717,7 @@ export function prepareItem( id: QueueItemId ) {

// For images that can be processed by vips, check if we need to scale down based on threshold.
if ( isImage && isVipsSupported ) {
const { bigImageSizeThreshold, imageOutputFormats } = settings;

// If a threshold is set, add a resize operation to scale down large images.
// This matches WordPress core's behavior in wp_create_image_subsizes().
if ( bigImageSizeThreshold ) {
operations.push( [
OperationType.ResizeCrop,
{
resize: {
width: bigImageSizeThreshold,
height: bigImageSizeThreshold,
},
isThresholdResize: true,
},
] );
}
const { imageOutputFormats } = settings;

// Check if we need to transcode to a different format.
// Uses WordPress image_editor_output_format filter settings.
Expand Down Expand Up @@ -1126,8 +1111,8 @@ export function generateThumbnails( id: QueueItemId ) {
// Use sourceFile for thumbnail generation to preserve quality.
// WordPress core generates thumbnails from the original (unscaled) image.
// Vips will auto-rotate based on EXIF orientation during thumbnail generation.
const file = attachment.media_filename
? renameFile( item.sourceFile, attachment.media_filename )
const file = attachment.filename
? renameFile( item.sourceFile, attachment.filename )
: item.sourceFile;
const batchId = uuidv4();

Expand Down Expand Up @@ -1205,6 +1190,54 @@ export function generateThumbnails( id: QueueItemId ) {
operations: thumbnailOperations,
} );
}

// Create and sideload the scaled version.
const { bigImageSizeThreshold } = settings;
if ( bigImageSizeThreshold && attachment.id ) {
// Rename sourceFile to match the server attachment filename.
const sourceForScaled = attachment.filename
? renameFile( item.sourceFile, attachment.filename )
: item.sourceFile;

// Add scaling to queue.
const scaledOperations: Operation[] = [
[
OperationType.ResizeCrop,
{
resize: {
width: bigImageSizeThreshold,
height: bigImageSizeThreshold,
},
isThresholdResize: true,
},
],
];

// Add transcoding if format conversion is configured.
if ( thumbnailTranscodeOperation ) {
scaledOperations.push( thumbnailTranscodeOperation );
}

scaledOperations.push( OperationType.Upload );

dispatch.addSideloadItem( {
file: sourceForScaled,
onChange: ( [ updatedAttachment ] ) => {
if ( isBlobURL( updatedAttachment.url ) ) {
return;
}
item.onChange?.( [ updatedAttachment ] );
},
batchId,
parentId: item.id,
additionalData: {
post: attachment.id,
image_size: 'scaled',
convert_format: false,
},
operations: scaledOperations,
} );
}
}

dispatch.finishOperation( id, {} );
Expand Down
1 change: 0 additions & 1 deletion packages/upload-media/src/store/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,6 @@ export interface Attachment {
mime_type: string;
featured_media?: number;
missing_image_sizes?: string[];
media_filename?: string;
poster?: string;
/**
* EXIF orientation value from the original image.
Expand Down
66 changes: 66 additions & 0 deletions packages/upload-media/src/test/convert-blob-to-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
* Internal dependencies
*/
import { convertBlobToFile } from '../utils';

describe( 'convertBlobToFile', () => {
it( 'should return a File unchanged', () => {
const file = new File( [ 'content' ], 'photo.jpg', {
type: 'image/jpeg',
} );
const result = convertBlobToFile( file );
expect( result ).toBe( file );
expect( result.name ).toBe( 'photo.jpg' );
} );

it( 'should convert a Blob with a default name', () => {
const blob = new Blob( [ 'content' ], { type: 'image/png' } );
const result = convertBlobToFile( blob );
expect( result ).toBeInstanceOf( File );
expect( result.name ).toBe( 'image.png' );
expect( result.type ).toBe( 'image/png' );
} );

it( 'should use "document" prefix for PDF blobs', () => {
const blob = new Blob( [ 'content' ], { type: 'application/pdf' } );
const result = convertBlobToFile( blob );
expect( result.name ).toBe( 'document.pdf' );
} );

it( 'should preserve the name from cross-realm File objects', () => {
// Simulate a cross-realm File object (e.g., from an iframe).
// These objects have a `name` property but fail `instanceof File`.
const crossRealmFile = new Blob( [ 'content' ], {
type: 'image/jpeg',
} );
Object.defineProperty( crossRealmFile, 'name', {
value: 'IMG_7977.jpg',
writable: false,
} );
Object.defineProperty( crossRealmFile, 'lastModified', {
value: 1700000000000,
writable: false,
} );

const result = convertBlobToFile( crossRealmFile );
expect( result ).toBeInstanceOf( File );
expect( result.name ).toBe( 'IMG_7977.jpg' );
expect( result.type ).toBe( 'image/jpeg' );
expect( result.lastModified ).toBe( 1700000000000 );
} );

it( 'should preserve the name for non-image cross-realm File objects', () => {
const crossRealmFile = new Blob( [ 'content' ], {
type: 'application/pdf',
} );
Object.defineProperty( crossRealmFile, 'name', {
value: 'my-document.pdf',
writable: false,
} );

const result = convertBlobToFile( crossRealmFile );
expect( result ).toBeInstanceOf( File );
expect( result.name ).toBe( 'my-document.pdf' );
expect( result.type ).toBe( 'application/pdf' );
} );
} );
18 changes: 18 additions & 0 deletions packages/upload-media/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import { _x } from '@wordpress/i18n';
*
* If it is already a File object, it is returned unchanged.
*
* Handles cross-realm File objects (e.g., from iframes) that have a `name`
* property but fail `instanceof File` checks because the File constructor
* differs between browsing contexts.
*
* @param fileOrBlob Blob object.
* @return File object.
*/
Expand All @@ -17,6 +21,20 @@ export function convertBlobToFile( fileOrBlob: Blob | File ): File {
return fileOrBlob;
}

// Handle cross-realm File objects (e.g., from iframes where the block
// editor canvas renders). These objects have a `name` property but fail
// the `instanceof File` check because each browsing context has its own
// File constructor.
if (
'name' in fileOrBlob &&
typeof ( fileOrBlob as File ).name === 'string'
) {
return new File( [ fileOrBlob ], ( fileOrBlob as File ).name, {
type: fileOrBlob.type,
lastModified: ( fileOrBlob as File ).lastModified,
} );
}

// Extension is only an approximation.
// The server will override it if incorrect.
const ext = fileOrBlob.type.split( '/' )[ 1 ];
Expand Down
Loading
Loading