From 750051f05e88573fd7d8d7c59be02938c47c0dda Mon Sep 17 00:00:00 2001 From: khushalsains Date: Thu, 5 Nov 2026 18:53:08 +0530 Subject: [PATCH 01/10] Replace media files in place to preserve attachment URLs `wp media replace` sideloaded the replacement into the current uploads directory, so the attachment kept its ID but its path and URL changed. Existing links to the file, such as those the block editor writes, then broke. Write the replacement over the attachment's existing file by default. The command validates the file like a normal upload and refuses an in-place replacement when the file type does not match the attachment, because the old extension cannot serve the new bytes. Add `--new-file-name` to keep the old sideload behavior when a new URL is wanted. Handle big-image `-scaled` files so the URL stays the same, and delete old sizes only after the new metadata is written. Writes are atomic, so a failed copy cannot truncate the existing file. Add Behat coverage for in-place replacement, custom upload folders, big-image scaling, file-type mismatches, and the opt-out flag. --- README.md | 32 ++- features/media-replace.feature | 261 +++++++++++++++++- src/Media_Command.php | 471 +++++++++++++++++++++++++++++---- 3 files changed, 706 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 791c0f65..b181df6e 100644 --- a/README.md +++ b/README.md @@ -343,8 +343,22 @@ wp media regenerate [...] [--image_size=...] [--skip- Replaces the file for an existing attachment while preserving its identity. +By default, the replacement is written over the attachment's existing file, +keeping its path and URL intact. This is a change from earlier versions, +which sideloaded the replacement into the current uploads directory and +therefore changed the attachment's URL. Use --new-file-name to restore that +behavior. + +When replacing an image that is not itself a WordPress big-image "-scaled" +variant with one larger than the big-image threshold, the full-resolution +file is kept at the existing URL and the generated "-scaled" file is +discarded, so the URL still does not change. WordPress re-applies big-image +scaling whenever attachment metadata is regenerated, so a later +`wp media regenerate` may point the attachment at a "-scaled" file; use +--new-file-name if you want WordPress's standard big-image handling instead. + ~~~ -wp media replace [--skip-delete] [--porcelain] +wp media replace [--skip-delete] [--new-file-name] [--porcelain] ~~~ **OPTIONS** @@ -356,7 +370,12 @@ wp media replace [--skip-delete] [--porcelain] Path to the replacement file. Supports local paths and URLs. [--skip-delete] - Skip deletion of old thumbnail files after replacement. + Skip deletion of the previous files after replacement. + + [--new-file-name] + Store the replacement under its own file name in the current uploads + directory instead of overwriting the attachment's existing file. This + changes the attachment's URL. [--porcelain] Output just the attachment ID after replacement. @@ -366,12 +385,17 @@ wp media replace [--skip-delete] [--porcelain] # Replace an attachment file with a local file. $ wp media replace 123 ~/new-image.jpg Replaced file for attachment ID 123 with '/home/user/new-image.jpg'. - Success: Replaced 1 of 1 images. + Success: Replaced 1 of 1 attachments. # Replace an attachment file with a file from a URL. $ wp media replace 123 'http://example.com/image.jpg' Replaced file for attachment ID 123 with 'http://example.com/image.jpg'. - Success: Replaced 1 of 1 images. + Success: Replaced 1 of 1 attachments. + + # Replace a file and use the replacement's own name, changing the attachment URL. + $ wp media replace 123 ~/new-image.jpg --new-file-name + Replaced file for attachment ID 123 with '/home/user/new-image.jpg'. + Success: Replaced 1 of 1 attachments. # Replace and output just the attachment ID. $ wp media replace 123 ~/new-image.jpg --porcelain diff --git a/features/media-replace.feature b/features/media-replace.feature index 4a51fc1a..011ade69 100644 --- a/features/media-replace.feature +++ b/features/media-replace.feature @@ -23,6 +23,253 @@ Feature: Replace WordPress attachment files Success: Replaced 1 of 1 attachments. """ + Scenario: Replace an attachment file and keep its existing file name + Given download: + | path | url | + | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + | {CACHE_DIR}/replacement.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + And I run `wp option update uploads_use_yearmonth_folders 0` + + When I run `wp media import {CACHE_DIR}/canola.jpg --porcelain` + Then save STDOUT as {ATTACHMENT_ID} + + When I run `wp post meta get {ATTACHMENT_ID} _wp_attached_file` + Then save STDOUT as {OLD_FILE} + + When I run `wp media replace {ATTACHMENT_ID} {CACHE_DIR}/replacement.jpg` + Then STDOUT should contain: + """ + Success: Replaced 1 of 1 attachments. + """ + + When I run `wp post meta get {ATTACHMENT_ID} _wp_attached_file` + Then STDOUT should be: + """ + {OLD_FILE} + """ + And the wp-content/uploads/{OLD_FILE} file should exist + And the wp-content/uploads/replacement.jpg file should not exist + + Scenario: Replace an attachment file and keep its existing upload folder + Given download: + | path | url | + | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + | {CACHE_DIR}/replacement.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + And a move-attachment.php file: + """ + @@ -826,7 +840,12 @@ public function import( $args, $assoc_args = array() ) { * : Path to the replacement file. Supports local paths and URLs. * * [--skip-delete] - * : Skip deletion of old thumbnail files after replacement. + * : Skip deletion of the previous files after replacement. + * + * [--new-file-name] + * : Store the replacement under its own file name in the current uploads + * directory instead of overwriting the attachment's existing file. This + * changes the attachment's URL. * * [--porcelain] * : Output just the attachment ID after replacement. @@ -836,19 +855,24 @@ public function import( $args, $assoc_args = array() ) { * # Replace an attachment file with a local file. * $ wp media replace 123 ~/new-image.jpg * Replaced file for attachment ID 123 with '/home/user/new-image.jpg'. - * Success: Replaced 1 of 1 images. + * Success: Replaced 1 of 1 attachments. * * # Replace an attachment file with a file from a URL. * $ wp media replace 123 'http://example.com/image.jpg' * Replaced file for attachment ID 123 with 'http://example.com/image.jpg'. - * Success: Replaced 1 of 1 images. + * Success: Replaced 1 of 1 attachments. + * + * # Replace a file and use the replacement's own name, changing the attachment URL. + * $ wp media replace 123 ~/new-image.jpg --new-file-name + * Replaced file for attachment ID 123 with '/home/user/new-image.jpg'. + * Success: Replaced 1 of 1 attachments. * * # Replace and output just the attachment ID. * $ wp media replace 123 ~/new-image.jpg --porcelain * 123 * * @param string[] $args Positional arguments. - * @param array{'skip-delete'?: bool, porcelain?: bool} $assoc_args Associative arguments. + * @param array{'skip-delete'?: bool, 'new-file-name'?: bool, 'porcelain'?: bool} $assoc_args Associative arguments. * @return void */ public function replace( $args, $assoc_args = array() ) { @@ -861,6 +885,17 @@ public function replace( $args, $assoc_args = array() ) { WP_CLI::error( "Invalid attachment ID {$attachment_id}." ); } + // Resolve the attachment's current file before anything else so that a + // failure here does not leave a downloaded temporary file behind. + $old_attached_path = get_attached_file( $attachment_id ); + if ( false === $old_attached_path || '' === $old_attached_path ) { + WP_CLI::error( "Unable to determine the current file for attachment {$attachment_id}." ); + } + $old_original_path = $this->get_attached_file( $attachment_id ); + $old_metadata = wp_get_attachment_metadata( $attachment_id ); + $preserve_path = ! Utils\get_flag_value( $assoc_args, 'new-file-name', false ); + $skip_delete = (bool) Utils\get_flag_value( $assoc_args, 'skip-delete', false ); + // Handle remote vs local file (same pattern as import). // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- parse_url will only be used in absence of wp_parse_url. $is_file_remote = function_exists( 'wp_parse_url' ) ? wp_parse_url( $file, PHP_URL_HOST ) : parse_url( $file, PHP_URL_HOST ); @@ -887,53 +922,36 @@ public function replace( $args, $assoc_args = array() ) { $name = (string) strtok( Path::basename( $file ), '?' ); } - // Get old metadata before replacement for cleanup. - $old_fullsizepath = $this->get_attached_file( $attachment_id ); - $old_metadata = wp_get_attachment_metadata( $attachment_id ); - - // Move the temp file into the uploads directory. - $file_array = array( - 'name' => $name, - 'tmp_name' => $tempfile, - ); - - $uploaded = wp_handle_sideload( $file_array, array( 'test_form' => false ) ); - - if ( isset( $uploaded['error'] ) ) { - if ( isset( $tempfile ) && is_string( $tempfile ) && file_exists( $tempfile ) ) { - unlink( $tempfile ); - } - WP_CLI::error( "Failed to process file '{$orig_filename}': {$uploaded['error']}" ); - } - - $new_file_path = $uploaded['file']; - $new_mime_type = $uploaded['type']; + if ( $preserve_path ) { + /* + * When the attachment is a big-image scaled variant, write the replacement + * to the pre-scaled original file. WordPress recreates the "-scaled" sibling + * when the replacement is still above the big-image threshold, keeping the + * same URL; when it is smaller, reconcile_attachment_path() moves the file + * onto the existing "-scaled" URL. + */ + $is_scaled = is_string( $old_original_path ) && $old_original_path !== $old_attached_path; + $write_path = $is_scaled ? $old_original_path : $old_attached_path; - // Delete old thumbnail files unless asked to skip. - if ( ! Utils\get_flag_value( $assoc_args, 'skip-delete', false ) - && false !== $old_fullsizepath - && is_array( $old_metadata ) - ) { - $this->remove_old_images( $old_metadata, $old_fullsizepath, array() ); + $new_mime_type = $this->replace_file_in_place( $tempfile, $name, $write_path, $old_attached_path, $attachment->post_mime_type, $orig_filename ); + } else { + // Move the temp file into the current uploads directory. + $file_array = array( + 'name' => $name, + 'tmp_name' => $tempfile, + ); - // Also delete the previous full-size file itself to avoid leaving an orphan. - if ( $old_fullsizepath !== $new_file_path && file_exists( $old_fullsizepath ) ) { - @unlink( $old_fullsizepath ); - } + $uploaded = wp_handle_sideload( $file_array, array( 'test_form' => false ) ); - // For big-image scaling (WP 5.3+), delete the original image if present in metadata. - $original_image = isset( $old_metadata['original_image'] ) ? (string) $old_metadata['original_image'] : ''; - if ( '' !== $original_image && ! empty( $old_metadata['file'] ) ) { - $uploads = wp_get_upload_dir(); - if ( ! empty( $uploads['basedir'] ) ) { - $dirname = dirname( $old_metadata['file'] ); - $original_image_rel = ( '.' === $dirname || '/' === $dirname ) ? $original_image : $dirname . '/' . $original_image; - $original_image_abspath = $uploads['basedir'] . '/' . $original_image_rel; - if ( $original_image_abspath !== $new_file_path && file_exists( $original_image_abspath ) ) { - @unlink( $original_image_abspath ); - } + if ( isset( $uploaded['error'] ) ) { + if ( isset( $tempfile ) && is_string( $tempfile ) && file_exists( $tempfile ) ) { + unlink( $tempfile ); } + WP_CLI::error( "Failed to process file '{$orig_filename}': {$uploaded['error']}" ); } + + $write_path = $uploaded['file']; + $new_mime_type = $uploaded['type']; } // Update the attachment's MIME type. @@ -951,16 +969,41 @@ public function replace( $args, $assoc_args = array() ) { } // Update the attached file path. - update_attached_file( $attachment_id, $new_file_path ); + update_attached_file( $attachment_id, $write_path ); // Generate and update new attachment metadata. - $new_metadata = wp_generate_attachment_metadata( $attachment_id, $new_file_path ); + $new_metadata = wp_generate_attachment_metadata( $attachment_id, $write_path ); if ( is_array( $new_metadata ) && ! empty( $new_metadata ) ) { + if ( $preserve_path ) { + $new_metadata = $this->reconcile_attachment_path( $attachment_id, $new_metadata, $old_attached_path ); + } wp_update_attachment_metadata( $attachment_id, $new_metadata ); + + // Clean up the previous files only now that the replacement succeeded. + if ( ! $skip_delete ) { + $keep_paths = $this->get_metadata_paths( $new_metadata ); + + if ( is_array( $old_metadata ) ) { + $this->remove_old_images( $old_metadata, $old_attached_path, array(), $keep_paths ); + } + + // Delete the previous full-size files to avoid leaving orphans behind. + $old_paths = array( wp_normalize_path( (string) $old_attached_path ) ); + if ( is_string( $old_original_path ) ) { + $old_paths[] = wp_normalize_path( $old_original_path ); + } + + $write_path_normalized = wp_normalize_path( $write_path ); + foreach ( array_unique( $old_paths ) as $old_path ) { + if ( ! in_array( $old_path, $keep_paths, true ) && $old_path !== $write_path_normalized && file_exists( $old_path ) ) { + @unlink( $old_path ); + } + } + } } else { WP_CLI::warning( sprintf( - 'Failed to generate new attachment metadata for attachment ID %d. Existing metadata has been preserved.', + 'Failed to generate new attachment metadata for attachment ID %d. The file was replaced but its image sizes may be stale; run wp media regenerate to rebuild them.', $attachment_id ) ); @@ -976,6 +1019,325 @@ public function replace( $args, $assoc_args = array() ) { } } + /** + * Writes a replacement file over an existing attachment file. + * + * The replacement is validated like a normal upload and written in place, so + * the attachment URL does not change. The write is atomic: the bytes are + * copied to a temporary file in the same directory and then renamed over the + * destination, so a failed copy never truncates the existing file. + * + * @param string $tempfile Path to the replacement file. + * @param string $name Original name of the replacement file. + * @param string $write_path Absolute path to write the replacement to. + * @param string $old_path Absolute path of the attachment's current file. + * @param string $old_mime_type MIME type currently recorded on the attachment. + * @param string $orig_filename Replacement file as provided by the user. + * @return string The MIME type of the replacement file. + */ + private function replace_file_in_place( $tempfile, $name, $write_path, $old_path, $old_mime_type, $orig_filename ) { + $wp_filetype = wp_check_filetype_and_ext( $tempfile, $name ); + if ( empty( $wp_filetype['type'] ) || empty( $wp_filetype['ext'] ) ) { + @unlink( $tempfile ); + WP_CLI::error( "Failed to process file '{$orig_filename}': Sorry, you are not allowed to upload this file type." ); + } + + $new_mime_type = (string) $wp_filetype['type']; + + /* + * An in-place replacement keeps the existing URL, so it must also keep the + * existing file type. Otherwise the web server would serve the new bytes + * with the Content-Type of the old extension. + */ + $existing_filetype = wp_check_filetype( $old_path ); + $existing_type = $existing_filetype['type']; + if ( empty( $existing_type ) && is_string( $old_mime_type ) ) { + // The stored extension is not mapped; fall back to the attachment's MIME type. + $existing_type = $old_mime_type; + } + + if ( ! empty( $existing_type ) && $existing_type !== $new_mime_type ) { + @unlink( $tempfile ); + WP_CLI::error( + sprintf( + "Failed to process file '%s': The attachment is a %s but the replacement is a %s. Use the --new-file-name flag to store the replacement under its own file name instead.", + $orig_filename, + $existing_type, + $new_mime_type + ) + ); + } + + if ( ! $this->is_within_uploads( $write_path ) ) { + @unlink( $tempfile ); + WP_CLI::error( "Failed to process file '{$orig_filename}': The attachment path is outside the uploads directory." ); + } + + // Replicate the validation WordPress runs for a normal upload. + $file_data = array( + 'name' => $name, + 'type' => $new_mime_type, + 'tmp_name' => $tempfile, + 'error' => 0, + 'size' => (int) @filesize( $tempfile ), + ); + + // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook. + $file_array = apply_filters( 'wp_handle_upload_prefilter', $file_data ); + + if ( ! empty( $file_array['error'] ) ) { + @unlink( $tempfile ); + WP_CLI::error( "Failed to process file '{$orig_filename}': {$file_array['error']}" ); + } + + if ( is_multisite() ) { + if ( ! function_exists( 'upload_is_user_over_quota' ) && defined( 'ABSPATH' ) ) { + require_once ABSPATH . 'wp-admin/includes/ms.php'; + } + + if ( function_exists( 'upload_is_user_over_quota' ) && upload_is_user_over_quota( false ) ) { + @unlink( $tempfile ); + WP_CLI::error( "Failed to process file '{$orig_filename}': Sorry, you have used your space allocation." ); + } + } + + if ( ! wp_mkdir_p( dirname( $write_path ) ) ) { + @unlink( $tempfile ); + WP_CLI::error( "Failed to process file '{$orig_filename}': Unable to create the upload directory." ); + } + + if ( ! $this->atomic_replace( $tempfile, $write_path ) ) { + @unlink( $tempfile ); + WP_CLI::error( "Failed to process file '{$orig_filename}': Unable to write the file to the upload directory." ); + } + + @unlink( $tempfile ); + + return $new_mime_type; + } + + /** + * Copies a file over another file without truncating the destination first. + * + * @param string $source Path to the source file. + * @param string $destination Path to the destination file. + * @return bool Whether the destination was replaced. + */ + private function atomic_replace( $source, $destination ) { + $temp = tempnam( dirname( $destination ), 'wp-cli-replace-' ); + if ( false === $temp ) { + return false; + } + + if ( ! copy( $source, $temp ) ) { + @unlink( $temp ); + return false; + } + + if ( defined( 'FS_CHMOD_FILE' ) ) { + // chmod() can fail on read-only or non-POSIX mounts; failure is non-fatal. + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged + @chmod( $temp, FS_CHMOD_FILE ); + } + + // On most filesystems rename() replaces the destination atomically. + if ( @rename( $temp, $destination ) ) { + return true; + } + + /* + * Some filesystems (notably Windows) do not overwrite on rename(). Move the + * destination aside first, and restore it if the second rename fails, so the + * existing file is never lost. + */ + $backup = $destination . '.wp-cli-backup'; + if ( ! @rename( $destination, $backup ) ) { + @unlink( $temp ); + return false; + } + + if ( @rename( $temp, $destination ) ) { + @unlink( $backup ); + return true; + } + + @rename( $backup, $destination ); + @unlink( $temp ); + + return false; + } + + /** + * Whether a path is a safe location inside the uploads directory. + * + * @param string $path Absolute path to check. + * @return bool True if the path is within the uploads directory, false otherwise. + */ + private function is_within_uploads( $path ) { + if ( ! is_string( $path ) || '' === $path ) { + return false; + } + + // Reject directory traversal segments. + if ( 1 === preg_match( '#(^|[/\\\\])\.\.([/\\\\]|$)#', $path ) ) { + return false; + } + + $uploads = wp_get_upload_dir(); + if ( empty( $uploads['basedir'] ) ) { + return false; + } + + $basedir = trailingslashit( wp_normalize_path( $uploads['basedir'] ) ); + + return 0 === strpos( wp_normalize_path( $path ), $basedir ); + } + + /** + * Collects the absolute paths referenced by attachment metadata. + * + * @param array $metadata Attachment metadata. + * @return string[] Absolute file paths. + */ + private function get_metadata_paths( $metadata ) { + $uploads = wp_get_upload_dir(); + if ( empty( $uploads['basedir'] ) || empty( $metadata['file'] ) || ! is_string( $metadata['file'] ) ) { + return array(); + } + + $main = wp_normalize_path( $uploads['basedir'] . '/' . $metadata['file'] ); + $dir = dirname( $main ); + $paths = array( $main ); + + if ( ! empty( $metadata['original_image'] ) && is_string( $metadata['original_image'] ) ) { + $paths[] = $dir . '/' . $metadata['original_image']; + } + + if ( ! empty( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) { + foreach ( $metadata['sizes'] as $size_info ) { + if ( is_array( $size_info ) && ! empty( $size_info['file'] ) && is_string( $size_info['file'] ) ) { + $paths[] = $dir . '/' . $size_info['file']; + } + } + } + + return array_map( 'wp_normalize_path', $paths ); + } + + /** + * Keeps an attachment's file at its existing path after metadata generation. + * + * WordPress may create a "-scaled" sibling for images above the big-image + * threshold and point the attachment at it, which changes the attachment URL. + * This method restores the attachment's existing path: + * + * - If the existing path already ends in "-scaled", the generated file is moved + * onto it so that URL is kept. + * - If the existing path is not itself a "-scaled" variant, the full-resolution + * file is kept at that path and the generated "-scaled" sibling is discarded so + * that URL is kept. + * + * The full-resolution file is never deleted. + * + * @param int $attachment_id Attachment ID. + * @param array $metadata Generated attachment metadata. + * @param string $canonical_path Absolute path the attachment should keep. + * @return array Updated attachment metadata. + */ + private function reconcile_attachment_path( $attachment_id, $metadata, $canonical_path ) { + $uploads = wp_get_upload_dir(); + if ( empty( $uploads['basedir'] ) || empty( $metadata['file'] ) || ! is_string( $metadata['file'] ) ) { + return $metadata; + } + + $canonical_path = wp_normalize_path( $canonical_path ); + + $canonical_rel = _wp_relative_upload_path( $canonical_path ); + $generated_path = wp_normalize_path( $uploads['basedir'] . '/' . $metadata['file'] ); + + // WordPress already stored the file at the path the attachment keeps. + if ( $canonical_rel === $metadata['file'] ) { + update_attached_file( $attachment_id, $canonical_path ); + + return $metadata; + } + + // The generated file is gone; keep pointing at the existing file, if any. + if ( ! file_exists( $generated_path ) ) { + if ( file_exists( $canonical_path ) ) { + update_attached_file( $attachment_id, $canonical_path ); + $metadata['file'] = $canonical_rel; + } + + return $metadata; + } + + $canonical_is_scaled = 1 === preg_match( '#-scaled\.[^./\\\\]+$#', $canonical_path ); + + if ( ! $canonical_is_scaled ) { + /* + * WordPress created a "-scaled" sibling for a URL that is not itself a + * scaled variant. Keep the full-resolution file at the original URL and + * drop the sibling, rather than replacing the original with the scaled copy. + */ + @unlink( $generated_path ); + $metadata['file'] = $canonical_rel; + unset( $metadata['original_image'] ); + + if ( file_exists( $canonical_path ) ) { + $metadata = $this->set_file_dimensions( $metadata, $canonical_path ); + update_attached_file( $attachment_id, $canonical_path ); + } + + return $metadata; + } + + // The URL points at a "-scaled" file but the replacement was too small to + // be scaled. Move it onto the existing URL so links keep working. + if ( ! $this->atomic_replace( $generated_path, $canonical_path ) ) { + WP_CLI::warning( + sprintf( 'Unable to move the replacement file for attachment %d to its existing path.', $attachment_id ) + ); + + return $metadata; + } + + // The generated file now lives at the canonical path; remove the duplicate. + @unlink( $generated_path ); + + $metadata['file'] = $canonical_rel; + $metadata = $this->set_file_dimensions( $metadata, $canonical_path ); + unset( $metadata['original_image'] ); + + update_attached_file( $attachment_id, $canonical_path ); + + return $metadata; + } + + /** + * Updates the filesize and pixel dimensions of attachment metadata from a file. + * + * @param array $metadata Attachment metadata. + * @param string $path Absolute path of the file to read. + * @return array Updated attachment metadata. + */ + private function set_file_dimensions( $metadata, $path ) { + if ( ! file_exists( $path ) ) { + return $metadata; + } + + $metadata['filesize'] = (int) @filesize( $path ); + + // The file was validated as an image before it was written here. + $imagesize = getimagesize( $path ); + if ( is_array( $imagesize ) ) { + $metadata['width'] = (int) $imagesize[0]; + $metadata['height'] = (int) $imagesize[1]; + } + + return $metadata; + } + /** * Lists image sizes registered with WordPress. * @@ -1485,9 +1847,10 @@ private function process_prune( $id, $image_sizes, $remove_abandoned, $progress, * @param array $metadata * @param string $fullsizepath * @param string[] $image_sizes + * @param string[] $keep_paths Absolute paths that must not be deleted. * @return void */ - private function remove_old_images( $metadata, $fullsizepath, $image_sizes ) { + private function remove_old_images( $metadata, $fullsizepath, $image_sizes, $keep_paths = array() ) { if ( empty( $metadata['sizes'] ) ) { return; @@ -1500,12 +1863,14 @@ private function remove_old_images( $metadata, $fullsizepath, $image_sizes ) { } } - $dir_path = dirname( $fullsizepath ) . '/'; + $dir_path = trailingslashit( wp_normalize_path( dirname( $fullsizepath ) ) ); + $fullsizepath = wp_normalize_path( $fullsizepath ); + $keep_paths = is_array( $keep_paths ) ? array_map( 'wp_normalize_path', $keep_paths ) : array(); foreach ( $metadata['sizes'] as $size_info ) { - $intermediate_path = $dir_path . $size_info['file']; + $intermediate_path = wp_normalize_path( $dir_path . $size_info['file'] ); - if ( $intermediate_path === $fullsizepath ) { + if ( $intermediate_path === $fullsizepath || in_array( $intermediate_path, $keep_paths, true ) ) { continue; } From cabb087270411e3c7cd13c174aade906d345b6c5 Mon Sep 17 00:00:00 2001 From: khushalsains Date: Thu, 5 Nov 2026 19:24:43 +0530 Subject: [PATCH 02/10] Tag big-image replace scenarios and cover error paths The big-image scenarios call `wp_get_original_image_path()`, which WordPress added in 5.3, and they assert that the pre-scaled master is removed during a replace. Both assumptions do not hold on older WordPress versions, so tag them `@require-wp-5.3`. Add scenarios for a disallowed file type, an attachment path outside the uploads directory, and an upload prefilter error. These cover the new error branches, which the Behat coverage run did not reach. --- features/media-replace.feature | 66 ++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/features/media-replace.feature b/features/media-replace.feature index 011ade69..090e913e 100644 --- a/features/media-replace.feature +++ b/features/media-replace.feature @@ -114,6 +114,7 @@ Feature: Replace WordPress attachment files """ And the wp-content/uploads/{OLD_FILE} file should exist + @require-wp-5.3 Scenario: Replace a scaled big image with another big image and keep its path Given download: | path | url | @@ -145,6 +146,7 @@ Feature: Replace WordPress attachment files 3264x2448 """ + @require-wp-5.3 Scenario: Replace a scaled big image with a smaller image and keep its path Given download: | path | url | @@ -238,6 +240,70 @@ Feature: Replace WordPress attachment files Success: Replaced 1 of 1 attachments. """ + Scenario: Reject a replacement with a file type WordPress does not allow + Given a replacement.php file: + """ + Date: Thu, 5 Nov 2026 19:43:37 +0530 Subject: [PATCH 03/10] Add Behat coverage for non-image replacements `wp media replace` supports attachments without image metadata, but no test reached that path. A text attachment has no `file` key, so `get_metadata_paths()` and `reconcile_attachment_path()` return early. Add a scenario that replaces a text attachment in place. It also checks that the new bytes are written over the existing file. --- features/media-replace.feature | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/features/media-replace.feature b/features/media-replace.feature index 090e913e..073811d9 100644 --- a/features/media-replace.feature +++ b/features/media-replace.feature @@ -304,6 +304,39 @@ Feature: Replace WordPress attachment files """ And the return code should be 1 + Scenario: Replace a non-image attachment file in place + Given a document.txt file: + """ + Old content. + """ + And a replacement.txt file: + """ + New content. + """ + And I run `wp option update uploads_use_yearmonth_folders 0` + + When I run `wp media import document.txt --porcelain` + Then save STDOUT as {ATTACHMENT_ID} + + When I run `wp post meta get {ATTACHMENT_ID} _wp_attached_file` + Then save STDOUT as {OLD_FILE} + + When I run `wp media replace {ATTACHMENT_ID} replacement.txt` + Then STDOUT should contain: + """ + Success: Replaced 1 of 1 attachments. + """ + + When I run `wp post meta get {ATTACHMENT_ID} _wp_attached_file` + Then STDOUT should be: + """ + {OLD_FILE} + """ + And the wp-content/uploads/{OLD_FILE} file should contain: + """ + New content. + """ + Scenario: Replace an attachment file with a new file name when requested Given download: | path | url | From 3e6e228157c054f6d7a2bdf091a05930bfc6f111 Mon Sep 17 00:00:00 2001 From: khushalsains Date: Thu, 5 Nov 2026 21:24:26 +0530 Subject: [PATCH 04/10] Test the failed download path instead of non-image files WordPress versions before 6.0 return empty metadata for non-image attachments, so the non-image scenario warns on older versions and fails the no-STDERR assertion. Replace it with the failed download path, which does not depend on the WordPress version. Mock a 404 response and assert the error and exit code. --- features/media-replace.feature | 36 ++++++++++++++-------------------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/features/media-replace.feature b/features/media-replace.feature index 073811d9..3e170b51 100644 --- a/features/media-replace.feature +++ b/features/media-replace.feature @@ -304,38 +304,32 @@ Feature: Replace WordPress attachment files """ And the return code should be 1 - Scenario: Replace a non-image attachment file in place - Given a document.txt file: - """ - Old content. - """ - And a replacement.txt file: + Scenario: Error when the replacement URL cannot be downloaded + Given download: + | path | url | + | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + And that HTTP requests to http://example.com/missing.jpg will respond with: """ - New content. + HTTP/1.1 404 + Content-Type: text/plain + + Not Found """ And I run `wp option update uploads_use_yearmonth_folders 0` - When I run `wp media import document.txt --porcelain` + When I run `wp media import {CACHE_DIR}/canola.jpg --porcelain` Then save STDOUT as {ATTACHMENT_ID} When I run `wp post meta get {ATTACHMENT_ID} _wp_attached_file` Then save STDOUT as {OLD_FILE} - When I run `wp media replace {ATTACHMENT_ID} replacement.txt` - Then STDOUT should contain: - """ - Success: Replaced 1 of 1 attachments. - """ - - When I run `wp post meta get {ATTACHMENT_ID} _wp_attached_file` - Then STDOUT should be: - """ - {OLD_FILE} - """ - And the wp-content/uploads/{OLD_FILE} file should contain: + When I try `wp media replace {ATTACHMENT_ID} http://example.com/missing.jpg` + Then STDERR should contain: """ - New content. + Unable to replace attachment """ + And the return code should be 1 + And the wp-content/uploads/{OLD_FILE} file should exist Scenario: Replace an attachment file with a new file name when requested Given download: From f98ca12418fff28da80d68f478047ca18e47ea6a Mon Sep 17 00:00:00 2001 From: khushalsains Date: Thu, 5 Nov 2026 21:54:52 +0530 Subject: [PATCH 05/10] Cover the missing attached file error path `wp media replace` stops when the attachment has no `_wp_attached_file` meta. The guard was added with the in-place replace work, but no test reached it. --- features/media-replace.feature | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/features/media-replace.feature b/features/media-replace.feature index 3e170b51..d7234abe 100644 --- a/features/media-replace.feature +++ b/features/media-replace.feature @@ -331,6 +331,24 @@ Feature: Replace WordPress attachment files And the return code should be 1 And the wp-content/uploads/{OLD_FILE} file should exist + Scenario: Error when the attachment has no attached file + Given download: + | path | url | + | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + And I run `wp option update uploads_use_yearmonth_folders 0` + + When I run `wp media import {CACHE_DIR}/canola.jpg --porcelain` + Then save STDOUT as {ATTACHMENT_ID} + + When I run `wp post meta delete {ATTACHMENT_ID} _wp_attached_file` + + And I try `wp media replace {ATTACHMENT_ID} {CACHE_DIR}/canola.jpg` + Then STDERR should contain: + """ + Unable to determine the current file for attachment + """ + And the return code should be 1 + Scenario: Replace an attachment file with a new file name when requested Given download: | path | url | From b6a456db2e3af2e20bc1bcdda283307fad9664fb Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 24 Nov 2026 13:24:59 +0000 Subject: [PATCH 06/10] Keep web-readable permissions on in-place replacements tempnam() creates the temporary file with mode 0600 and rename() keeps it, while FS_CHMOD_FILE is usually not defined in a WP-CLI run. The replaced file could then be unreadable by the web server. Keep the mode of the file being replaced, or derive it from the directory like wp_handle_sideload() does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/media-replace.feature | 23 +++++++++++++++++++++++ src/Media_Command.php | 18 ++++++++++++++---- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/features/media-replace.feature b/features/media-replace.feature index d7234abe..1cdaf866 100644 --- a/features/media-replace.feature +++ b/features/media-replace.feature @@ -50,6 +50,29 @@ Feature: Replace WordPress attachment files And the wp-content/uploads/{OLD_FILE} file should exist And the wp-content/uploads/replacement.jpg file should not exist + Scenario: Keep the file permissions when replacing an attachment file in place + Given download: + | path | url | + | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + | {CACHE_DIR}/replacement.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + And I run `wp option update uploads_use_yearmonth_folders 0` + + When I run `wp media import {CACHE_DIR}/canola.jpg --porcelain` + Then save STDOUT as {ATTACHMENT_ID} + + When I run `wp eval 'chmod( get_attached_file( {ATTACHMENT_ID} ), 0644 );'` + And I run `wp media replace {ATTACHMENT_ID} {CACHE_DIR}/replacement.jpg` + Then STDOUT should contain: + """ + Success: Replaced 1 of 1 attachments. + """ + + When I run `wp eval 'clearstatcache(); echo decoct( fileperms( get_attached_file( {ATTACHMENT_ID} ) ) & 0777 );'` + Then STDOUT should be: + """ + 644 + """ + Scenario: Replace an attachment file and keep its existing upload folder Given download: | path | url | diff --git a/src/Media_Command.php b/src/Media_Command.php index fbe8cafb..881f3b2d 100644 --- a/src/Media_Command.php +++ b/src/Media_Command.php @@ -1134,11 +1134,21 @@ private function atomic_replace( $source, $destination ) { return false; } - if ( defined( 'FS_CHMOD_FILE' ) ) { - // chmod() can fail on read-only or non-POSIX mounts; failure is non-fatal. - // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged - @chmod( $temp, FS_CHMOD_FILE ); + /* + * tempnam() creates the file with mode 0600. Keep the mode of the file being + * replaced, or derive it from the directory like wp_handle_sideload() does, + * so the web server can still read the file. + */ + $perms = file_exists( $destination ) ? fileperms( $destination ) : false; + if ( false !== $perms ) { + $perms = $perms & 0777; + } else { + $stat = stat( dirname( $destination ) ); + $perms = $stat ? $stat['mode'] & 0000666 : 0644; } + // chmod() can fail on read-only or non-POSIX mounts; failure is non-fatal. + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged + @chmod( $temp, $perms ); // On most filesystems rename() replaces the destination atomically. if ( @rename( $temp, $destination ) ) { From 59bc58013881302ac1e2f6e9b69c54e812df8bc5 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Tue, 24 Nov 2026 15:18:31 +0000 Subject: [PATCH 07/10] Harden in-place media replace against data-loss edge cases - Run wp_handle_sideload_prefilter (the hook wp_handle_sideload() fires, as before this change) instead of wp_handle_upload_prefilter, so sites that reject sideloads still reject in-place replacements. - Allow --new-file-name to repair an attachment without _wp_attached_file. - Treat filesize-only image metadata as a failed generation: keep the existing path and old image sizes instead of cleaning them up. - Move the replacement onto any derived attached file ("-rotated" as well as "-scaled") instead of deleting the replacement. - Never delete the file at the existing URL during cleanup, even if moving the replacement onto it failed. - Warn with the backup path if the rename fallback cannot restore the original file. - Make the in-place scenario use a different replacement image and check the bytes actually changed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/media-replace.feature | 115 +++++++++++++++++++++++++++++++-- src/Media_Command.php | 102 ++++++++++++++++++++++------- 2 files changed, 188 insertions(+), 29 deletions(-) diff --git a/features/media-replace.feature b/features/media-replace.feature index 1cdaf866..a8afbdc7 100644 --- a/features/media-replace.feature +++ b/features/media-replace.feature @@ -25,9 +25,9 @@ Feature: Replace WordPress attachment files Scenario: Replace an attachment file and keep its existing file name Given download: - | path | url | - | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | - | {CACHE_DIR}/replacement.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + | path | url | + | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + | {CACHE_DIR}/replacement.jpg | http://wp-cli.github.io/behat-data/white-150-square.jpg | And I run `wp option update uploads_use_yearmonth_folders 0` When I run `wp media import {CACHE_DIR}/canola.jpg --porcelain` @@ -50,6 +50,13 @@ Feature: Replace WordPress attachment files And the wp-content/uploads/{OLD_FILE} file should exist And the wp-content/uploads/replacement.jpg file should not exist + # The file at the existing path must now hold the replacement's bytes. + When I run `wp eval '$s = getimagesize( get_attached_file( {ATTACHMENT_ID} ) ); echo $s[0] . "x" . $s[1];'` + Then STDOUT should be: + """ + 150x150 + """ + Scenario: Keep the file permissions when replacing an attachment file in place Given download: | path | url | @@ -302,7 +309,7 @@ Feature: Replace WordPress attachment files """ And the return code should be 1 - Scenario: Refuse a replacement rejected by the upload prefilter + Scenario: Refuse a replacement rejected by the sideload prefilter Given download: | path | url | | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | @@ -314,7 +321,7 @@ Feature: Replace WordPress attachment files Given a wp-content/mu-plugins/reject-uploads.php file: """ 123 ) : $metadata; + }, 10, 3 ); + """ + + When I try `wp media replace {ATTACHMENT_ID} {CACHE_DIR}/canola.jpg` + Then STDERR should contain: + """ + Failed to generate new attachment metadata + """ + + When I run `wp post meta get {ATTACHMENT_ID} _wp_attached_file` + Then STDOUT should be: + """ + {OLD_FILE} + """ + And the wp-content/uploads/{OLD_FILE} file should exist + And the wp-content/uploads/large-image-1024x768.jpg file should exist + Scenario: Replace an attachment file with a new file name when requested Given download: | path | url | diff --git a/src/Media_Command.php b/src/Media_Command.php index 881f3b2d..9e27f23e 100644 --- a/src/Media_Command.php +++ b/src/Media_Command.php @@ -887,14 +887,17 @@ public function replace( $args, $assoc_args = array() ) { // Resolve the attachment's current file before anything else so that a // failure here does not leave a downloaded temporary file behind. + $preserve_path = ! Utils\get_flag_value( $assoc_args, 'new-file-name', false ); + $skip_delete = (bool) Utils\get_flag_value( $assoc_args, 'skip-delete', false ); $old_attached_path = get_attached_file( $attachment_id ); - if ( false === $old_attached_path || '' === $old_attached_path ) { + $has_old_path = is_string( $old_attached_path ) && '' !== $old_attached_path; + // An in-place replacement needs the current path; --new-file-name can repair an attachment without one. + if ( ! $has_old_path && $preserve_path ) { WP_CLI::error( "Unable to determine the current file for attachment {$attachment_id}." ); } - $old_original_path = $this->get_attached_file( $attachment_id ); + $old_attached_path = $has_old_path ? (string) $old_attached_path : ''; + $old_original_path = $has_old_path ? $this->get_attached_file( $attachment_id ) : false; $old_metadata = wp_get_attachment_metadata( $attachment_id ); - $preserve_path = ! Utils\get_flag_value( $assoc_args, 'new-file-name', false ); - $skip_delete = (bool) Utils\get_flag_value( $assoc_args, 'skip-delete', false ); // Handle remote vs local file (same pattern as import). // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- parse_url will only be used in absence of wp_parse_url. @@ -973,9 +976,22 @@ public function replace( $args, $assoc_args = array() ) { // Generate and update new attachment metadata. $new_metadata = wp_generate_attachment_metadata( $attachment_id, $write_path ); - if ( is_array( $new_metadata ) && ! empty( $new_metadata ) ) { + + /* + * On a read error WordPress returns only the filesize for an image. Treat that + * like a failure when the previous file had full image metadata, so the old + * sizes are not deleted and the attachment keeps its existing path. + */ + $metadata_incomplete = is_array( $new_metadata ) + && 1 === count( $new_metadata ) + && array_key_exists( 'filesize', $new_metadata ) + && 0 === strpos( $new_mime_type, 'image/' ) + && is_array( $old_metadata ) + && ! empty( $old_metadata['file'] ); + + if ( is_array( $new_metadata ) && ! empty( $new_metadata ) && ! $metadata_incomplete ) { if ( $preserve_path ) { - $new_metadata = $this->reconcile_attachment_path( $attachment_id, $new_metadata, $old_attached_path ); + $new_metadata = $this->reconcile_attachment_path( $attachment_id, $new_metadata, $old_attached_path, $write_path ); } wp_update_attachment_metadata( $attachment_id, $new_metadata ); @@ -983,7 +999,13 @@ public function replace( $args, $assoc_args = array() ) { if ( ! $skip_delete ) { $keep_paths = $this->get_metadata_paths( $new_metadata ); - if ( is_array( $old_metadata ) ) { + if ( $preserve_path ) { + // Never delete the file behind the attachment's existing URL, even if + // moving the replacement onto it failed. + $keep_paths[] = wp_normalize_path( $old_attached_path ); + } + + if ( is_array( $old_metadata ) && $has_old_path ) { $this->remove_old_images( $old_metadata, $old_attached_path, array(), $keep_paths ); } @@ -1001,6 +1023,11 @@ public function replace( $args, $assoc_args = array() ) { } } } else { + if ( $preserve_path && $write_path !== $old_attached_path ) { + // Keep the attachment at its existing path, which the old metadata still describes. + update_attached_file( $attachment_id, $old_attached_path ); + } + WP_CLI::warning( sprintf( 'Failed to generate new attachment metadata for attachment ID %d. The file was replaced but its image sizes may be stale; run wp media regenerate to rebuild them.', @@ -1073,7 +1100,10 @@ private function replace_file_in_place( $tempfile, $name, $write_path, $old_path WP_CLI::error( "Failed to process file '{$orig_filename}': The attachment path is outside the uploads directory." ); } - // Replicate the validation WordPress runs for a normal upload. + /* + * Replicate the validation WordPress runs in wp_handle_sideload(), which is + * what this command used before and still uses with --new-file-name. + */ $file_data = array( 'name' => $name, 'type' => $new_mime_type, @@ -1083,11 +1113,12 @@ private function replace_file_in_place( $tempfile, $name, $write_path, $old_path ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook. - $file_array = apply_filters( 'wp_handle_upload_prefilter', $file_data ); + $file_array = apply_filters( 'wp_handle_sideload_prefilter', $file_data ); - if ( ! empty( $file_array['error'] ) ) { + if ( is_array( $file_array ) && ! empty( $file_array['error'] ) ) { @unlink( $tempfile ); - WP_CLI::error( "Failed to process file '{$orig_filename}': {$file_array['error']}" ); + $error = is_string( $file_array['error'] ) ? $file_array['error'] : 'The replacement was rejected.'; + WP_CLI::error( "Failed to process file '{$orig_filename}': {$error}" ); } if ( is_multisite() ) { @@ -1171,9 +1202,14 @@ private function atomic_replace( $source, $destination ) { return true; } - @rename( $backup, $destination ); @unlink( $temp ); + if ( ! @rename( $backup, $destination ) ) { + WP_CLI::warning( + sprintf( "Unable to restore '%s'. The original file was kept at '%s'.", $destination, $backup ) + ); + } + return false; } @@ -1241,20 +1277,23 @@ private function get_metadata_paths( $metadata ) { * threshold and point the attachment at it, which changes the attachment URL. * This method restores the attachment's existing path: * - * - If the existing path already ends in "-scaled", the generated file is moved - * onto it so that URL is kept. - * - If the existing path is not itself a "-scaled" variant, the full-resolution - * file is kept at that path and the generated "-scaled" sibling is discarded so - * that URL is kept. + * - If the existing path is a file WordPress derived from the original (a + * "-scaled" or "-rotated" variant), the replacement was written to the + * original and the generated file is moved onto the existing path so that URL + * is kept. + * - If the existing path is the file that was written, the full-resolution file + * is kept at that path and any generated "-scaled" sibling is discarded so that + * URL is kept. * * The full-resolution file is never deleted. * * @param int $attachment_id Attachment ID. * @param array $metadata Generated attachment metadata. * @param string $canonical_path Absolute path the attachment should keep. + * @param string $write_path Absolute path the replacement was written to. * @return array Updated attachment metadata. */ - private function reconcile_attachment_path( $attachment_id, $metadata, $canonical_path ) { + private function reconcile_attachment_path( $attachment_id, $metadata, $canonical_path, $write_path ) { $uploads = wp_get_upload_dir(); if ( empty( $uploads['basedir'] ) || empty( $metadata['file'] ) || ! is_string( $metadata['file'] ) ) { return $metadata; @@ -1282,9 +1321,10 @@ private function reconcile_attachment_path( $attachment_id, $metadata, $canonica return $metadata; } - $canonical_is_scaled = 1 === preg_match( '#-scaled\.[^./\\\\]+$#', $canonical_path ); + // The existing path is a derived variant when the replacement went to the original instead. + $canonical_is_derived = wp_normalize_path( $write_path ) !== $canonical_path; - if ( ! $canonical_is_scaled ) { + if ( ! $canonical_is_derived ) { /* * WordPress created a "-scaled" sibling for a URL that is not itself a * scaled variant. Keep the full-resolution file at the original URL and @@ -1302,11 +1342,20 @@ private function reconcile_attachment_path( $attachment_id, $metadata, $canonica return $metadata; } - // The URL points at a "-scaled" file but the replacement was too small to - // be scaled. Move it onto the existing URL so links keep working. + /* + * The URL points at a derived file, but WordPress did not recreate that exact + * file for the replacement (for example, it was too small to be scaled, or + * needed no rotation). Move the generated file onto the existing URL so links + * keep working. + */ if ( ! $this->atomic_replace( $generated_path, $canonical_path ) ) { WP_CLI::warning( - sprintf( 'Unable to move the replacement file for attachment %d to its existing path.', $attachment_id ) + sprintf( + "Unable to move the replacement file for attachment %d to its existing path '%s'. The attachment now uses '%s'.", + $attachment_id, + $canonical_path, + $generated_path + ) ); return $metadata; @@ -1317,7 +1366,12 @@ private function reconcile_attachment_path( $attachment_id, $metadata, $canonica $metadata['file'] = $canonical_rel; $metadata = $this->set_file_dimensions( $metadata, $canonical_path ); - unset( $metadata['original_image'] ); + + // Keep "original_image" only if it still names a separate full-resolution file. + if ( ! empty( $metadata['original_image'] ) && is_string( $metadata['original_image'] ) + && wp_normalize_path( dirname( $canonical_path ) . '/' . $metadata['original_image'] ) === $generated_path ) { + unset( $metadata['original_image'] ); + } update_attached_file( $attachment_id, $canonical_path ); From bbad5d3512e5a22287bfbaa6fbaec7663df546f3 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 25 Nov 2026 11:09:58 +0000 Subject: [PATCH 08/10] Record displayed dimensions for in-place replacements with EXIF rotation When the replacement is kept as uploaded at the existing URL, it can still carry an EXIF orientation that turns it by 90 degrees. Swap the recorded width and height in that case, so they match what WordPress records for the rotated image and what browsers display. Also narrow the attachment to WP_Post before reading its properties. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/media-replace.feature | 43 ++++++++++++++++++++++++++++++++++ src/Media_Command.php | 20 +++++++++++++--- 2 files changed, 60 insertions(+), 3 deletions(-) diff --git a/features/media-replace.feature b/features/media-replace.feature index a8afbdc7..4e3aa81b 100644 --- a/features/media-replace.feature +++ b/features/media-replace.feature @@ -441,6 +441,49 @@ Feature: Replace WordPress attachment files 150x150 """ + @require-wp-5.3 + Scenario: Record the displayed dimensions of a replacement with an EXIF orientation + Given download: + | path | url | + | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + And a add-orientation.php file: + """ + post_type ) { + if ( ! $attachment instanceof WP_Post || 'attachment' !== $attachment->post_type ) { WP_CLI::error( "Invalid attachment ID {$attachment_id}." ); } @@ -1395,8 +1395,22 @@ private function set_file_dimensions( $metadata, $path ) { // The file was validated as an image before it was written here. $imagesize = getimagesize( $path ); if ( is_array( $imagesize ) ) { - $metadata['width'] = (int) $imagesize[0]; - $metadata['height'] = (int) $imagesize[1]; + $width = (int) $imagesize[0]; + $height = (int) $imagesize[1]; + + /* + * A file kept as uploaded may still carry an EXIF orientation that turns it + * by 90 degrees when displayed. WordPress records the displayed dimensions, + * so swap them to match. + */ + $image_meta = wp_read_image_metadata( $path ); + $orientation = is_array( $image_meta ) && isset( $image_meta['orientation'] ) && is_numeric( $image_meta['orientation'] ) ? (int) $image_meta['orientation'] : 1; + if ( $orientation >= 5 && $orientation <= 8 ) { + list( $width, $height ) = array( $height, $width ); + } + + $metadata['width'] = $width; + $metadata['height'] = $height; } return $metadata; From 300275dd3633b49861c1c00243704619e171b6b3 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 25 Nov 2026 11:51:16 +0000 Subject: [PATCH 09/10] Address media replace review findings - When metadata generation comes back incomplete, restore both the attached file and the previous metadata for in-place replacements. WordPress may already have stored new metadata or pointed the attachment at a generated "-scaled" file, also when the replacement was written to the existing path. - Run the wp_handle_sideload_prefilter filter first, as WordPress does, and continue with the file and name it returns. - When an image_editor_output_format mapping made WordPress save the generated full-size file in another format, convert it back before moving it onto the existing path, so the URL keeps serving the type its extension promises. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- features/media-replace.feature | 115 ++++++++++++++++++++++++++++++++ src/Media_Command.php | 116 ++++++++++++++++++++++++++------- 2 files changed, 207 insertions(+), 24 deletions(-) diff --git a/features/media-replace.feature b/features/media-replace.feature index 4e3aa81b..7c879d9f 100644 --- a/features/media-replace.feature +++ b/features/media-replace.feature @@ -520,6 +520,121 @@ Feature: Replace WordPress attachment files And the wp-content/uploads/{OLD_FILE} file should exist And the wp-content/uploads/large-image-1024x768.jpg file should exist + # WordPress stored metadata for the replacement before the filter ran; the old metadata must be restored. + When I run `wp eval '$m = wp_get_attachment_metadata( {ATTACHMENT_ID} ); echo $m["file"] . " " . $m["width"] . "x" . $m["height"];'` + Then STDOUT should be: + """ + {OLD_FILE} 2560x1920 + """ + + @require-wp-5.3 + Scenario: Keep the existing path and metadata when generation fails after WordPress scaled the replacement + Given download: + | path | url | + | {CACHE_DIR}/large-image.jpg | http://wp-cli.github.io/behat-data/large-image.jpg | + | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + And I run `wp option update uploads_use_yearmonth_folders 0` + + When I run `wp media import {CACHE_DIR}/canola.jpg --porcelain` + Then save STDOUT as {ATTACHMENT_ID} + + Given a wp-content/mu-plugins/read-error.php file: + """ + 123 ) : $metadata; + }, 10, 3 ); + """ + + When I try `wp media replace {ATTACHMENT_ID} {CACHE_DIR}/large-image.jpg` + Then STDERR should contain: + """ + Failed to generate new attachment metadata + """ + + When I run `wp post meta get {ATTACHMENT_ID} _wp_attached_file` + Then STDOUT should be: + """ + canola.jpg + """ + + When I run `wp eval '$m = wp_get_attachment_metadata( {ATTACHMENT_ID} ); echo $m["file"] . " " . $m["width"] . "x" . $m["height"];'` + Then STDOUT should be: + """ + canola.jpg 640x480 + """ + + Scenario: Replace an attachment file with the file returned by the sideload prefilter + Given download: + | path | url | + | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + + When I run `wp media import {CACHE_DIR}/canola.jpg --porcelain` + Then save STDOUT as {ATTACHMENT_ID} + + Given a wp-content/mu-plugins/shrink.php file: + """ + resize( 100, 100 ); + $saved = $editor->save( get_temp_dir() . 'wp-cli-shrunk.jpg', 'image/jpeg' ); + $file['tmp_name'] = $saved['path']; + return $file; + } ); + """ + + When I run `wp media replace {ATTACHMENT_ID} {CACHE_DIR}/canola.jpg` + Then STDOUT should contain: + """ + Success: Replaced 1 of 1 attachments. + """ + + When I run `wp eval '$s = getimagesize( get_attached_file( {ATTACHMENT_ID} ) ); echo $s[0] . "x" . $s[1];'` + Then STDOUT should be: + """ + 100x75 + """ + + @require-wp-5.8 + Scenario: Keep the file type of a scaled image path when WordPress converts the replacement + Given download: + | path | url | + | {CACHE_DIR}/large-image.jpg | http://wp-cli.github.io/behat-data/large-image.jpg | + | {CACHE_DIR}/canola.jpg | http://wp-cli.github.io/behat-data/canola.jpg | + And I run `wp option update uploads_use_yearmonth_folders 0` + + When I run `wp media import {CACHE_DIR}/large-image.jpg --porcelain` + Then save STDOUT as {ATTACHMENT_ID} + + Given a wp-content/mu-plugins/webp.php file: + """ + $name, + 'type' => (string) wp_check_filetype( $name )['type'], + 'tmp_name' => $tempfile, + 'error' => 0, + 'size' => (int) @filesize( $tempfile ), + ); + + // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook. + $file_array = apply_filters( 'wp_handle_sideload_prefilter', $file_data ); + + if ( is_array( $file_array ) && ! empty( $file_array['error'] ) ) { + @unlink( $tempfile ); + $error = is_string( $file_array['error'] ) ? $file_array['error'] : 'The replacement was rejected.'; + WP_CLI::error( "Failed to process file '{$orig_filename}': {$error}" ); + } + + // A filter may hand back a processed copy of the file under a new name. + if ( is_array( $file_array ) && ! empty( $file_array['tmp_name'] ) && is_string( $file_array['tmp_name'] ) && $file_array['tmp_name'] !== $tempfile ) { + @unlink( $tempfile ); + $tempfile = $file_array['tmp_name']; + if ( ! is_file( $tempfile ) ) { + WP_CLI::error( "Failed to process file '{$orig_filename}': The file returned by the wp_handle_sideload_prefilter filter does not exist." ); + } + } + if ( is_array( $file_array ) && ! empty( $file_array['name'] ) && is_string( $file_array['name'] ) ) { + $name = $file_array['name']; + } + $wp_filetype = wp_check_filetype_and_ext( $tempfile, $name ); if ( empty( $wp_filetype['type'] ) || empty( $wp_filetype['ext'] ) ) { @unlink( $tempfile ); @@ -1100,27 +1141,6 @@ private function replace_file_in_place( $tempfile, $name, $write_path, $old_path WP_CLI::error( "Failed to process file '{$orig_filename}': The attachment path is outside the uploads directory." ); } - /* - * Replicate the validation WordPress runs in wp_handle_sideload(), which is - * what this command used before and still uses with --new-file-name. - */ - $file_data = array( - 'name' => $name, - 'type' => $new_mime_type, - 'tmp_name' => $tempfile, - 'error' => 0, - 'size' => (int) @filesize( $tempfile ), - ); - - // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook. - $file_array = apply_filters( 'wp_handle_sideload_prefilter', $file_data ); - - if ( is_array( $file_array ) && ! empty( $file_array['error'] ) ) { - @unlink( $tempfile ); - $error = is_string( $file_array['error'] ) ? $file_array['error'] : 'The replacement was rejected.'; - WP_CLI::error( "Failed to process file '{$orig_filename}': {$error}" ); - } - if ( is_multisite() ) { if ( ! function_exists( 'upload_is_user_over_quota' ) && defined( 'ABSPATH' ) ) { require_once ABSPATH . 'wp-admin/includes/ms.php'; @@ -1348,7 +1368,7 @@ private function reconcile_attachment_path( $attachment_id, $metadata, $canonica * needed no rotation). Move the generated file onto the existing URL so links * keep working. */ - if ( ! $this->atomic_replace( $generated_path, $canonical_path ) ) { + if ( ! $this->move_into_format( $generated_path, $canonical_path ) ) { WP_CLI::warning( sprintf( "Unable to move the replacement file for attachment %d to its existing path '%s'. The attachment now uses '%s'.", @@ -1378,6 +1398,54 @@ private function reconcile_attachment_path( $attachment_id, $metadata, $canonica return $metadata; } + /** + * Puts a generated image file at a path, keeping the file type of that path. + * + * When an `image_editor_output_format` mapping made WordPress save the + * generated file in another format (for example a WebP for a JPEG), the image + * is converted back, because the existing URL keeps its file extension. + * + * @param string $source Path to the generated file. + * @param string $destination Path the file should be stored at. + * @return bool Whether the destination was replaced. + */ + private function move_into_format( $source, $destination ) { + $source_ext = strtolower( pathinfo( $source, PATHINFO_EXTENSION ) ); + $destination_ext = strtolower( pathinfo( $destination, PATHINFO_EXTENSION ) ); + if ( $source_ext === $destination_ext ) { + return $this->atomic_replace( $source, $destination ); + } + + $filetype = wp_check_filetype( $destination ); + $editor = wp_get_image_editor( $source ); + if ( empty( $filetype['type'] ) || is_wp_error( $editor ) ) { + return false; + } + + $mime_type = $filetype['type']; + + // Save in the format of the destination, ignoring any output format mapping for it. + $keep_format = static function ( $formats ) use ( $mime_type ) { + if ( is_array( $formats ) ) { + unset( $formats[ $mime_type ] ); + } + return $formats; + }; + add_filter( 'image_editor_output_format', $keep_format, PHP_INT_MAX ); + $temp = dirname( $destination ) . '/' . uniqid( 'wp-cli-replace-' ) . '.' . $destination_ext; + $saved = $editor->save( $temp, $mime_type ); + remove_filter( 'image_editor_output_format', $keep_format, PHP_INT_MAX ); + + if ( is_wp_error( $saved ) || empty( $saved['path'] ) ) { + return false; + } + + $replaced = $this->atomic_replace( $saved['path'], $destination ); + @unlink( $saved['path'] ); + + return $replaced; + } + /** * Updates the filesize and pixel dimensions of attachment metadata from a file. * From 3c7eca42248976b8884f2745feed53e3b5d0d22a Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Wed, 25 Nov 2026 12:26:07 +0000 Subject: [PATCH 10/10] Ignore the WordPress 5.8 compat warning for image_editor_output_format Before 5.8 there is no output format mapping, so the filter is never applied and there is nothing to undo. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx --- src/Media_Command.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Media_Command.php b/src/Media_Command.php index 06655d83..444c0f11 100644 --- a/src/Media_Command.php +++ b/src/Media_Command.php @@ -1431,6 +1431,8 @@ private function move_into_format( $source, $destination ) { } return $formats; }; + // Before WordPress 5.8 there is no output format mapping, so the filter is never applied and nothing needs undoing. + // @phpstan-ignore WPCompat.filterNotAvailable.imageeditoroutputformat add_filter( 'image_editor_output_format', $keep_format, PHP_INT_MAX ); $temp = dirname( $destination ) . '/' . uniqid( 'wp-cli-replace-' ) . '.' . $destination_ext; $saved = $editor->save( $temp, $mime_type );