From e5d0f4e45b566f4682ac8952d6ac5e8bf9d32337 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Wed, 11 Nov 2026 20:30:08 +0200 Subject: [PATCH 01/11] fix: move and delete attachment files only inside the uploads directory Rename, replace and offload build file paths from attachment metadata. Those paths are now checked against the uploads directory before a file is moved, deleted or offloaded. --- inc/media_offload.php | 7 ++- inc/media_rename/attachment_rename.php | 14 +++++- inc/media_rename/attachment_replace.php | 7 ++- inc/v2/Media/UploadsPath.php | 37 +++++++++++++++ tests/media_rename/test-attachment-rename.php | 47 +++++++++++++++++++ .../media_rename/test-attachment-replace.php | 29 ++++++++++++ tests/test-uploads-path.php | 27 +++++++++++ 7 files changed, 163 insertions(+), 5 deletions(-) create mode 100644 inc/v2/Media/UploadsPath.php create mode 100644 tests/test-uploads-path.php diff --git a/inc/media_offload.php b/inc/media_offload.php index c0080bcb2..7477cf151 100644 --- a/inc/media_offload.php +++ b/inc/media_offload.php @@ -6,6 +6,7 @@ * @author Optimole */ +use OptimoleWP\Media\UploadsPath; use OptimoleWP\Offload\Loader; use Optimole\Sdk\Exception\InvalidArgumentException; use Optimole\Sdk\Exception\InvalidUploadApiResponseException; @@ -1463,7 +1464,8 @@ public function generate_image_meta( $meta, $attachment_id ) { do_action( 'optml_log', 'file after replace' ); do_action( 'optml_log', $local_file ); } - if ( ! file_exists( $local_file ) ) { + // The path comes from attachment metadata, so a file outside the uploads directory is treated as missing. + if ( ! file_exists( $local_file ) || ! UploadsPath::contains( $local_file ) ) { update_post_meta( $attachment_id, self::META_KEYS['offload_error'], 'true' ); do_action( 'optml_log', 'missing file' ); do_action( 'optml_log', $local_file ); @@ -1616,7 +1618,8 @@ public function generate_image_meta( $meta, $attachment_id ) { if ( isset( $meta['sizes'] ) ) { foreach ( $meta['sizes'] as $key => $value ) { $generated_image_size_path = str_replace( $original_name, $meta['sizes'][ $key ]['file'], $local_file ); - file_exists( $generated_image_size_path ) && unlink( $generated_image_size_path ); + // Size files come from attachment metadata too, so only those inside the uploads directory are deleted. + file_exists( $generated_image_size_path ) && UploadsPath::contains( $generated_image_size_path ) && unlink( $generated_image_size_path ); $meta['sizes'][ $key ]['file'] = $file_name; } } diff --git a/inc/media_rename/attachment_rename.php b/inc/media_rename/attachment_rename.php index 15cba758d..92ce217aa 100644 --- a/inc/media_rename/attachment_rename.php +++ b/inc/media_rename/attachment_rename.php @@ -1,5 +1,7 @@ exists( $file_path ) ) { return new WP_Error( 'optml_attachment_file_not_found', __( 'Error renaming file.', 'optimole-wp' ) ); @@ -87,7 +94,9 @@ public function rename() { $new_scaled_file_path = $base_dir . $scaled_new_file_with_ext; // Move the scaled image. We also override any leftover scaled files. - $wp_filesystem->move( $scaled_old_file_path, $new_scaled_file_path, true ); + if ( UploadsPath::contains( $scaled_old_file_path ) && UploadsPath::contains( $new_scaled_file_path ) ) { + $wp_filesystem->move( $scaled_old_file_path, $new_scaled_file_path, true ); + } } // Update attachment metadata @@ -186,6 +195,9 @@ private function update_attachment_metadata( $new_path ) { $old_size_file_path = sprintf( '%s/%s', $this->attachment->get_dir_path(), $size_data['file'] ); $new_size_file_path = sprintf( '%s/%s', $this->attachment->get_dir_path(), $new_size_file ); + if ( ! UploadsPath::contains( $old_size_file_path ) || ! UploadsPath::contains( $new_size_file_path ) ) { + continue; + } $move = $wp_filesystem->move( $old_size_file_path, $new_size_file_path ); diff --git a/inc/media_rename/attachment_replace.php b/inc/media_rename/attachment_replace.php index 31424def3..88216a3e7 100644 --- a/inc/media_rename/attachment_replace.php +++ b/inc/media_rename/attachment_replace.php @@ -1,5 +1,7 @@ delete( $path ); } } @@ -223,7 +226,7 @@ private function handle_scaled_images() { // replace the old year/month/item-scaled.ext with the new year/month/item.ext $scaled_path = str_replace( $unscaled_file, $old_scaled_file, $this->attachment->get_source_file_path() ); - if ( file_exists( $scaled_path ) ) { + if ( file_exists( $scaled_path ) && UploadsPath::contains( $scaled_path ) ) { $wp_filesystem->delete( $scaled_path ); } diff --git a/inc/v2/Media/UploadsPath.php b/inc/v2/Media/UploadsPath.php new file mode 100644 index 000000000..e1fd1d034 --- /dev/null +++ b/inc/v2/Media/UploadsPath.php @@ -0,0 +1,37 @@ +test_rename( self::$scaled_id, self::$scaled_model, 'big-file-rename', true ); } + public function test_rename_leaves_size_files_outside_uploads_in_place(): void { + $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/rename-unscaled.jpg' ); + $outside = self::outside_uploads_file( 'optml-outside-size.txt' ); + $meta = wp_get_attachment_metadata( $id ); + $meta['sizes']['thumbnail']['file'] = self::relative_from( ( new Optml_Attachment_Model( $id ) )->get_dir_path(), $outside ); + wp_update_attachment_metadata( $id, $meta ); + + ( new Optml_Attachment_Rename( $id, 'outside-size-renamed' ) )->rename(); + + $this->assertFileExists( $outside, 'A size file outside uploads must not be moved.' ); + wp_delete_post( $id, true ); + unlink( $outside ); + } + + public function test_rename_refuses_a_main_file_outside_uploads(): void { + $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/rename-unscaled.jpg' ); + $outside = self::outside_uploads_file( 'optml-outside-main.jpg' ); + update_post_meta( $id, '_wp_attached_file', self::relative_from( wp_get_upload_dir()['basedir'], $outside ) ); + + $result = ( new Optml_Attachment_Rename( $id, 'outside-main-renamed' ) )->rename(); + + $this->assertWPError( $result ); + $this->assertFileExists( $outside, 'A main file outside uploads must not be moved.' ); + wp_delete_post( $id, true ); + unlink( $outside ); + } + + /** + * Create a file next to the uploads directory, outside it. + */ + private static function outside_uploads_file( string $name ): string { + $path = dirname( wp_get_upload_dir()['basedir'] ) . '/' . $name; + file_put_contents( $path, 'keep' ); + + return $path; + } + + /** + * Build the `../` path from a folder inside uploads to a file next to the uploads directory. + */ + private static function relative_from( string $dir, string $file ): string { + $parent = dirname( wp_get_upload_dir()['basedir'] ); + $depth = substr_count( trim( substr( $dir, strlen( $parent ) ), '/' ), '/' ) + 1; + + return str_repeat( '../', $depth ) . basename( $file ); + } + private function test_rename( $id, $model, $new_filename, $scaled = false ) { $renamer = new Optml_Attachment_Rename( $id, $new_filename ); $result = $renamer->rename(); diff --git a/tests/media_rename/test-attachment-replace.php b/tests/media_rename/test-attachment-replace.php index b5007b140..0f22a5a85 100644 --- a/tests/media_rename/test-attachment-replace.php +++ b/tests/media_rename/test-attachment-replace.php @@ -109,6 +109,35 @@ private function test_replace_unscaled_to_unscaled() { $this->do_replace_test( self::$unscaled_unscaled_id, $replace_file, false, false ); } + public function test_replace_does_not_delete_size_files_outside_uploads() { + global $wp_filesystem; + + $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/sample-test.jpg' ); + $model = new Optml_Attachment_Model( $id ); + $parent = dirname( wp_get_upload_dir()['basedir'] ); + $outside = $parent . '/optml-outside-replace.txt'; + file_put_contents( $outside, 'keep' ); + $depth = substr_count( trim( substr( $model->get_dir_path(), strlen( $parent ) ), '/' ), '/' ) + 1; + $meta = wp_get_attachment_metadata( $id ); + $meta['sizes']['thumbnail']['file'] = str_repeat( '../', $depth ) . basename( $outside ); + wp_update_attachment_metadata( $id, $meta ); + + $tmp_file = self::FILESTASH . 'replace-outside.jpg'; + $wp_filesystem->copy( OPTML_PATH . 'tests/assets/small-1.jpg', $tmp_file, true ); + ( new Optml_Attachment_Replace( + $id, + [ + 'name' => 'replace-outside.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => $tmp_file, + ] + ) )->replace(); + + $this->assertFileExists( $outside, 'A size file outside uploads must not be deleted.' ); + wp_delete_post( $id, true ); + unlink( $outside ); + } + /** * A 0600 upload tmp file must not leave the replaced attachment unreadable to the web server. */ diff --git a/tests/test-uploads-path.php b/tests/test-uploads-path.php new file mode 100644 index 000000000..b1bcedd28 --- /dev/null +++ b/tests/test-uploads-path.php @@ -0,0 +1,27 @@ +assertTrue( UploadsPath::contains( wp_get_upload_dir()['basedir'] . '/photo.jpg' ) ); + } + + public function test_file_reached_with_dot_dot_is_refused(): void { + $this->assertFalse( UploadsPath::contains( wp_get_upload_dir()['basedir'] . '/../wp-config.php' ) ); + } + + public function test_file_in_a_folder_that_does_not_exist_is_refused(): void { + $this->assertFalse( UploadsPath::contains( wp_get_upload_dir()['basedir'] . '/optml-missing-folder/photo.jpg' ) ); + } +} From c80a201b81c9b8171b2d5f339b5eebda4478f6d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Wed, 11 Nov 2026 23:11:16 +0200 Subject: [PATCH 02/11] fix: replace only attachment files inside the uploads directory Replace now refuses a main file path outside uploads before it moves the uploaded file. The uploads check also compares normalized paths, so Windows paths match. --- inc/media_rename/attachment_replace.php | 5 ++++ inc/v2/Media/UploadsPath.php | 6 ++-- .../media_rename/test-attachment-replace.php | 27 +++++++++++++++++ tests/test-media.php | 30 +++++++++++++++++++ 4 files changed, 66 insertions(+), 2 deletions(-) diff --git a/inc/media_rename/attachment_replace.php b/inc/media_rename/attachment_replace.php index 88216a3e7..b79500c80 100644 --- a/inc/media_rename/attachment_replace.php +++ b/inc/media_rename/attachment_replace.php @@ -72,6 +72,11 @@ public function replace() { return new WP_Error( 'file_error', __( 'Original file does not exist.', 'optimole-wp' ) ); } + // The path comes from attachment metadata, so only a file inside the uploads directory is overwritten. + if ( ! UploadsPath::contains( $original_file ) ) { + return new WP_Error( 'optml_attachment_path_outside_uploads', __( 'Error uploading file.', 'optimole-wp' ) ); + } + $original_filetype = wp_check_filetype( $original_file ); $uploaded_filetype = wp_check_filetype( $this->file['name'] ); diff --git a/inc/v2/Media/UploadsPath.php b/inc/v2/Media/UploadsPath.php index e1fd1d034..9964f5591 100644 --- a/inc/v2/Media/UploadsPath.php +++ b/inc/v2/Media/UploadsPath.php @@ -14,7 +14,8 @@ class UploadsPath { /** * Check whether a file path, existing or not, is inside the uploads directory. * - * The folder holding the file must exist; `..` and symlinks are resolved before the check. + * The folder holding the file must exist; `..` and symlinks in that folder are resolved before the check. + * A symlink at the file itself is not followed: creating one needs write access to the server files. * * @param string $path Absolute file path. * @@ -32,6 +33,7 @@ public static function contains( string $path ): bool { return false; } - return 0 === strpos( trailingslashit( $dir ), trailingslashit( $uploads ) ); + // realpath() returns backslashes on Windows, so both sides are normalized before the prefix check. + return 0 === strpos( trailingslashit( wp_normalize_path( $dir ) ), trailingslashit( wp_normalize_path( $uploads ) ) ); } } diff --git a/tests/media_rename/test-attachment-replace.php b/tests/media_rename/test-attachment-replace.php index 0f22a5a85..3a47af20a 100644 --- a/tests/media_rename/test-attachment-replace.php +++ b/tests/media_rename/test-attachment-replace.php @@ -138,6 +138,33 @@ public function test_replace_does_not_delete_size_files_outside_uploads() { unlink( $outside ); } + public function test_replace_refuses_a_main_file_outside_uploads() { + global $wp_filesystem; + + $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/sample-test.jpg' ); + $outside = dirname( wp_get_upload_dir()['basedir'] ) . '/optml-outside-replace-main.jpg'; + copy( OPTML_PATH . 'tests/assets/sample-test.jpg', $outside ); + $before = md5_file( $outside ); + update_post_meta( $id, '_wp_attached_file', '../' . basename( $outside ) ); + + $tmp_file = self::FILESTASH . 'replace-outside-main.jpg'; + $wp_filesystem->copy( OPTML_PATH . 'tests/assets/small-1.jpg', $tmp_file, true ); + $result = ( new Optml_Attachment_Replace( + $id, + [ + 'name' => 'replace-outside-main.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => $tmp_file, + ] + ) )->replace(); + + $this->assertWPError( $result ); + $this->assertSame( $before, md5_file( $outside ), 'A main file outside uploads must not be overwritten.' ); + wp_delete_post( $id, true ); + unlink( $outside ); + file_exists( $tmp_file ) && unlink( $tmp_file ); + } + /** * A 0600 upload tmp file must not leave the replaced attachment unreadable to the web server. */ diff --git a/tests/test-media.php b/tests/test-media.php index ea134de47..4a78e6bc1 100644 --- a/tests/test-media.php +++ b/tests/test-media.php @@ -255,6 +255,36 @@ public function test_upload_during_rollback_stays_local(): void { $this->assertFileExists( get_attached_file( $attachment_id ) ); } + public function test_offload_treats_a_main_file_outside_uploads_as_missing(): void { + Optml_Media_Offload::instance()->rollback_and_update_images( [ self::$sample_attachement ] ); + $outside = dirname( wp_get_upload_dir()['basedir'] ) . '/optml-outside-offload.jpg'; + copy( OPTML_PATH . 'tests/assets/sample-test.jpg', $outside ); + update_post_meta( self::$sample_attachement, '_wp_attached_file', '../' . basename( $outside ) ); + + Optml_Media_Offload::instance()->upload_and_update_existing_images( [ self::$sample_attachement ] ); + + $this->assertSame( 'true', get_post_meta( self::$sample_attachement, Optml_Media_Offload::META_KEYS['offload_error'], true ) ); + $this->assertFileExists( $outside, 'A main file outside uploads must not be offloaded and deleted.' ); + unlink( $outside ); + } + + public function test_offload_keeps_size_files_outside_uploads(): void { + Optml_Media_Offload::instance()->rollback_and_update_images( [ self::$sample_attachement ] ); + $parent = dirname( wp_get_upload_dir()['basedir'] ); + $outside = $parent . '/optml-outside-offload-size.jpg'; + file_put_contents( $outside, 'keep' ); + $depth = substr_count( trim( substr( dirname( get_attached_file( self::$sample_attachement ) ), strlen( $parent ) ), '/' ), '/' ) + 1; + $meta = wp_get_attachment_metadata( self::$sample_attachement ); + $meta['sizes']['thumbnail']['file'] = str_repeat( '../', $depth ) . basename( $outside ); + wp_update_attachment_metadata( self::$sample_attachement, $meta ); + + Optml_Media_Offload::instance()->upload_and_update_existing_images( [ self::$sample_attachement ] ); + + $this->assertTrue( Optml_Media_Offload::is_uploaded_image( wp_get_attachment_metadata( self::$sample_attachement )['file'] ) ); + $this->assertFileExists( $outside, 'A size file outside uploads must not be deleted.' ); + unlink( $outside ); + } + public function test_retryable_error() { Optml_Media_Offload::instance()->rollback_and_update_images([self::$sample_attachement]); self::$error_mark = true; From dcbbcbd7ef26ff2c0f5240dd5b29756845a60a59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Wed, 11 Nov 2026 23:30:10 +0200 Subject: [PATCH 03/11] fix: check the scaled offload path and keep backslashes in folder names Offload checks the scaled file path before it deletes it, because the extension is replaced in the whole path. Only the separator of the running system is normalized, so a backslash in a folder name does not pass the uploads check. --- inc/media_offload.php | 3 +- inc/v2/Media/UploadsPath.php | 8 +++-- .../media_rename/test-attachment-replace.php | 31 +++++++++++++++++++ tests/test-media.php | 31 +++++++++++++++++++ tests/test-uploads-path.php | 11 +++++++ 5 files changed, 81 insertions(+), 3 deletions(-) diff --git a/inc/media_offload.php b/inc/media_offload.php index 7477cf151..785c2a2b1 100644 --- a/inc/media_offload.php +++ b/inc/media_offload.php @@ -1629,7 +1629,8 @@ public function generate_image_meta( $meta, $attachment_id ) { if ( isset( $meta['original_image'] ) ) { $ext = $this->get_ext( $local_file ); $scaled_path = str_replace( '.' . $ext, '-scaled.' . $ext, $local_file ); - file_exists( $scaled_path ) && unlink( $scaled_path ); + // The extension is replaced in the whole path, so folder names change too. + file_exists( $scaled_path ) && UploadsPath::contains( $scaled_path ) && unlink( $scaled_path ); } $duplicated_images = apply_filters( 'optml_offload_duplicated_images', [], $attachment_id ); diff --git a/inc/v2/Media/UploadsPath.php b/inc/v2/Media/UploadsPath.php index 9964f5591..1e4ba22c3 100644 --- a/inc/v2/Media/UploadsPath.php +++ b/inc/v2/Media/UploadsPath.php @@ -33,7 +33,11 @@ public static function contains( string $path ): bool { return false; } - // realpath() returns backslashes on Windows, so both sides are normalized before the prefix check. - return 0 === strpos( trailingslashit( wp_normalize_path( $dir ) ), trailingslashit( wp_normalize_path( $uploads ) ) ); + // realpath() returns backslashes on Windows. Elsewhere a backslash is a filename character, so only the + // separator of this system is normalized. + $dir = str_replace( DIRECTORY_SEPARATOR, '/', $dir ); + $uploads = str_replace( DIRECTORY_SEPARATOR, '/', $uploads ); + + return 0 === strpos( trailingslashit( $dir ), trailingslashit( $uploads ) ); } } diff --git a/tests/media_rename/test-attachment-replace.php b/tests/media_rename/test-attachment-replace.php index 3a47af20a..245b3bb68 100644 --- a/tests/media_rename/test-attachment-replace.php +++ b/tests/media_rename/test-attachment-replace.php @@ -165,6 +165,37 @@ public function test_replace_refuses_a_main_file_outside_uploads() { file_exists( $tmp_file ) && unlink( $tmp_file ); } + public function test_replace_refuses_an_original_image_outside_uploads() { + global $wp_filesystem; + + $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/sample-test.jpg' ); + $parent = dirname( wp_get_upload_dir()['basedir'] ); + $outside = $parent . '/optml-outside-replace-original.jpg'; + copy( OPTML_PATH . 'tests/assets/sample-test.jpg', $outside ); + $before = md5_file( $outside ); + $depth = substr_count( trim( substr( dirname( get_attached_file( $id ) ), strlen( $parent ) ), '/' ), '/' ) + 1; + $meta = wp_get_attachment_metadata( $id ); + $meta['original_image'] = str_repeat( '../', $depth ) . basename( $outside ); + wp_update_attachment_metadata( $id, $meta ); + + $tmp_file = self::FILESTASH . 'replace-outside-original.jpg'; + $wp_filesystem->copy( OPTML_PATH . 'tests/assets/small-1.jpg', $tmp_file, true ); + $result = ( new Optml_Attachment_Replace( + $id, + [ + 'name' => 'replace-outside-original.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => $tmp_file, + ] + ) )->replace(); + + $this->assertWPError( $result ); + $this->assertSame( $before, md5_file( $outside ), 'An original image outside uploads must not be overwritten.' ); + wp_delete_post( $id, true ); + unlink( $outside ); + file_exists( $tmp_file ) && unlink( $tmp_file ); + } + /** * A 0600 upload tmp file must not leave the replaced attachment unreadable to the web server. */ diff --git a/tests/test-media.php b/tests/test-media.php index 4a78e6bc1..b250c72fe 100644 --- a/tests/test-media.php +++ b/tests/test-media.php @@ -285,6 +285,37 @@ public function test_offload_keeps_size_files_outside_uploads(): void { unlink( $outside ); } + public function test_offload_keeps_a_scaled_file_outside_uploads(): void { + Optml_Media_Offload::instance()->rollback_and_update_images( [ self::$sample_attachement ] ); + // The uploads folder name holds the extension, so the scaled path built from it points to another folder. + $basedir = WP_CONTENT_DIR . '/optml-media.jpg'; + $outside = WP_CONTENT_DIR . '/optml-media-scaled.jpg/sample-test-scaled.jpg'; + wp_mkdir_p( $basedir ); + wp_mkdir_p( dirname( $outside ) ); + copy( get_attached_file( self::$sample_attachement ), $basedir . '/sample-test.jpg' ); + file_put_contents( $outside, 'keep' ); + $uploads = static function ( array $dir ) use ( $basedir ): array { + $dir['basedir'] = $basedir; + + return $dir; + }; + add_filter( 'upload_dir', $uploads ); + update_post_meta( self::$sample_attachement, '_wp_attached_file', 'sample-test.jpg' ); + $meta = wp_get_attachment_metadata( self::$sample_attachement ); + $meta['original_image'] = 'sample-test-original.jpg'; + wp_update_attachment_metadata( self::$sample_attachement, $meta ); + + Optml_Media_Offload::instance()->upload_and_update_existing_images( [ self::$sample_attachement ] ); + remove_filter( 'upload_dir', $uploads ); + + $this->assertTrue( Optml_Media_Offload::is_uploaded_image( wp_get_attachment_metadata( self::$sample_attachement )['file'] ) ); + $this->assertFileExists( $outside, 'A scaled file outside uploads must not be deleted.' ); + unlink( $outside ); + rmdir( dirname( $outside ) ); + file_exists( $basedir . '/sample-test.jpg' ) && unlink( $basedir . '/sample-test.jpg' ); + rmdir( $basedir ); + } + public function test_retryable_error() { Optml_Media_Offload::instance()->rollback_and_update_images([self::$sample_attachement]); self::$error_mark = true; diff --git a/tests/test-uploads-path.php b/tests/test-uploads-path.php index b1bcedd28..2adb3d395 100644 --- a/tests/test-uploads-path.php +++ b/tests/test-uploads-path.php @@ -21,6 +21,17 @@ public function test_file_reached_with_dot_dot_is_refused(): void { $this->assertFalse( UploadsPath::contains( wp_get_upload_dir()['basedir'] . '/../wp-config.php' ) ); } + public function test_backslash_in_a_folder_name_is_not_taken_as_a_separator(): void { + $basedir = wp_get_upload_dir()['basedir']; + $sibling = $basedir . '\\private'; + wp_mkdir_p( $sibling ); + + $contains = UploadsPath::contains( $basedir . '/../' . basename( $sibling ) . '/victim.jpg' ); + rmdir( $sibling ); + + $this->assertFalse( $contains ); + } + public function test_file_in_a_folder_that_does_not_exist_is_refused(): void { $this->assertFalse( UploadsPath::contains( wp_get_upload_dir()['basedir'] . '/optml-missing-folder/photo.jpg' ) ); } From d6849fa8963bdb269c88f607c372638f20c731ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Wed, 11 Nov 2026 23:41:27 +0200 Subject: [PATCH 04/11] test: cover backslash folder names inside uploads and the replace error code --- tests/media_rename/test-attachment-replace.php | 2 ++ tests/test-uploads-path.php | 12 ++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/media_rename/test-attachment-replace.php b/tests/media_rename/test-attachment-replace.php index 245b3bb68..431decba5 100644 --- a/tests/media_rename/test-attachment-replace.php +++ b/tests/media_rename/test-attachment-replace.php @@ -159,6 +159,7 @@ public function test_replace_refuses_a_main_file_outside_uploads() { ) )->replace(); $this->assertWPError( $result ); + $this->assertSame( 'optml_attachment_path_outside_uploads', $result->get_error_code() ); $this->assertSame( $before, md5_file( $outside ), 'A main file outside uploads must not be overwritten.' ); wp_delete_post( $id, true ); unlink( $outside ); @@ -190,6 +191,7 @@ public function test_replace_refuses_an_original_image_outside_uploads() { ) )->replace(); $this->assertWPError( $result ); + $this->assertSame( 'optml_attachment_path_outside_uploads', $result->get_error_code() ); $this->assertSame( $before, md5_file( $outside ), 'An original image outside uploads must not be overwritten.' ); wp_delete_post( $id, true ); unlink( $outside ); diff --git a/tests/test-uploads-path.php b/tests/test-uploads-path.php index 2adb3d395..d283d8364 100644 --- a/tests/test-uploads-path.php +++ b/tests/test-uploads-path.php @@ -22,14 +22,22 @@ public function test_file_reached_with_dot_dot_is_refused(): void { } public function test_backslash_in_a_folder_name_is_not_taken_as_a_separator(): void { + if ( '\\' === DIRECTORY_SEPARATOR ) { + $this->markTestSkipped( 'A backslash is a separator on Windows.' ); + } $basedir = wp_get_upload_dir()['basedir']; $sibling = $basedir . '\\private'; + $child = $basedir . '/a\\b'; wp_mkdir_p( $sibling ); + wp_mkdir_p( $child ); - $contains = UploadsPath::contains( $basedir . '/../' . basename( $sibling ) . '/victim.jpg' ); + $sibling_file = UploadsPath::contains( $basedir . '/../' . basename( $sibling ) . '/victim.jpg' ); + $child_file = UploadsPath::contains( $child . '/photo.jpg' ); rmdir( $sibling ); + rmdir( $child ); - $this->assertFalse( $contains ); + $this->assertFalse( $sibling_file ); + $this->assertTrue( $child_file ); } public function test_file_in_a_folder_that_does_not_exist_is_refused(): void { From f23a9e224fe4ed3bc2e0fdbb5d0fe301a2f1124e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 00:10:48 +0200 Subject: [PATCH 05/11] test: share the outside-uploads helpers and cover the replace scaled path and dot names --- tests/media_rename/test-attachment-rename.php | 24 +----- .../media_rename/test-attachment-replace.php | 76 ++++++++++++++----- tests/outside-uploads-files.php | 36 +++++++++ tests/test-media.php | 17 ++--- tests/test-uploads-path.php | 5 ++ 5 files changed, 111 insertions(+), 47 deletions(-) create mode 100644 tests/outside-uploads-files.php diff --git a/tests/media_rename/test-attachment-rename.php b/tests/media_rename/test-attachment-rename.php index 76d9f1bf5..074e6f723 100644 --- a/tests/media_rename/test-attachment-rename.php +++ b/tests/media_rename/test-attachment-rename.php @@ -1,4 +1,6 @@ rename(); diff --git a/tests/media_rename/test-attachment-replace.php b/tests/media_rename/test-attachment-replace.php index 431decba5..b419b8d09 100644 --- a/tests/media_rename/test-attachment-replace.php +++ b/tests/media_rename/test-attachment-replace.php @@ -1,4 +1,6 @@ unscaled protected static $unscaled_scaled_id; // unscaled -> scaled protected static $scaled_scaled_id; // scaled -> scaled @@ -113,13 +117,9 @@ public function test_replace_does_not_delete_size_files_outside_uploads() { global $wp_filesystem; $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/sample-test.jpg' ); - $model = new Optml_Attachment_Model( $id ); - $parent = dirname( wp_get_upload_dir()['basedir'] ); - $outside = $parent . '/optml-outside-replace.txt'; - file_put_contents( $outside, 'keep' ); - $depth = substr_count( trim( substr( $model->get_dir_path(), strlen( $parent ) ), '/' ), '/' ) + 1; - $meta = wp_get_attachment_metadata( $id ); - $meta['sizes']['thumbnail']['file'] = str_repeat( '../', $depth ) . basename( $outside ); + $outside = self::outside_uploads_file( 'optml-outside-replace.txt' ); + $meta = wp_get_attachment_metadata( $id ); + $meta['sizes']['thumbnail']['file'] = self::relative_from( ( new Optml_Attachment_Model( $id ) )->get_dir_path(), $outside ); wp_update_attachment_metadata( $id, $meta ); $tmp_file = self::FILESTASH . 'replace-outside.jpg'; @@ -142,10 +142,9 @@ public function test_replace_refuses_a_main_file_outside_uploads() { global $wp_filesystem; $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/sample-test.jpg' ); - $outside = dirname( wp_get_upload_dir()['basedir'] ) . '/optml-outside-replace-main.jpg'; - copy( OPTML_PATH . 'tests/assets/sample-test.jpg', $outside ); - $before = md5_file( $outside ); - update_post_meta( $id, '_wp_attached_file', '../' . basename( $outside ) ); + $outside = self::outside_uploads_file( 'optml-outside-replace-main.jpg', OPTML_PATH . 'tests/assets/sample-test.jpg' ); + $before = md5_file( $outside ); + update_post_meta( $id, '_wp_attached_file', self::relative_from( wp_get_upload_dir()['basedir'], $outside ) ); $tmp_file = self::FILESTASH . 'replace-outside-main.jpg'; $wp_filesystem->copy( OPTML_PATH . 'tests/assets/small-1.jpg', $tmp_file, true ); @@ -170,13 +169,10 @@ public function test_replace_refuses_an_original_image_outside_uploads() { global $wp_filesystem; $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/sample-test.jpg' ); - $parent = dirname( wp_get_upload_dir()['basedir'] ); - $outside = $parent . '/optml-outside-replace-original.jpg'; - copy( OPTML_PATH . 'tests/assets/sample-test.jpg', $outside ); - $before = md5_file( $outside ); - $depth = substr_count( trim( substr( dirname( get_attached_file( $id ) ), strlen( $parent ) ), '/' ), '/' ) + 1; - $meta = wp_get_attachment_metadata( $id ); - $meta['original_image'] = str_repeat( '../', $depth ) . basename( $outside ); + $outside = self::outside_uploads_file( 'optml-outside-replace-original.jpg', OPTML_PATH . 'tests/assets/sample-test.jpg' ); + $before = md5_file( $outside ); + $meta = wp_get_attachment_metadata( $id ); + $meta['original_image'] = self::relative_from( dirname( get_attached_file( $id ) ), $outside ); wp_update_attachment_metadata( $id, $meta ); $tmp_file = self::FILESTASH . 'replace-outside-original.jpg'; @@ -198,6 +194,50 @@ public function test_replace_refuses_an_original_image_outside_uploads() { file_exists( $tmp_file ) && unlink( $tmp_file ); } + public function test_replace_keeps_a_scaled_file_outside_uploads() { + global $wp_filesystem; + + $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/sample-test.jpg' ); + // The uploads folder name holds the file name, so the old scaled path built from it points to another folder. + $basedir = WP_CONTENT_DIR . '/optml-replace-photo.jpg'; + $outside = WP_CONTENT_DIR . '/optml-replace-photo-scaled.jpg/replace-photo-scaled.jpg'; + wp_mkdir_p( $basedir ); + wp_mkdir_p( dirname( $outside ) ); + copy( OPTML_PATH . 'tests/assets/sample-test.jpg', $basedir . '/replace-photo.jpg' ); + copy( OPTML_PATH . 'tests/assets/sample-test.jpg', $basedir . '/replace-photo-scaled.jpg' ); + file_put_contents( $outside, 'keep' ); + $uploads = static function ( array $dir ) use ( $basedir ): array { + $dir['basedir'] = $basedir; + + return $dir; + }; + add_filter( 'upload_dir', $uploads ); + update_post_meta( $id, '_wp_attached_file', 'replace-photo-scaled.jpg' ); + $meta = wp_get_attachment_metadata( $id ); + $meta['file'] = 'replace-photo-scaled.jpg'; + $meta['original_image'] = 'replace-photo.jpg'; + wp_update_attachment_metadata( $id, $meta ); + + $tmp_file = self::FILESTASH . 'replace-photo.jpg'; + $wp_filesystem->copy( OPTML_PATH . 'tests/assets/small-1.jpg', $tmp_file, true ); + ( new Optml_Attachment_Replace( + $id, + [ + 'name' => 'replace-photo.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => $tmp_file, + ] + ) )->replace(); + remove_filter( 'upload_dir', $uploads ); + + $this->assertFileExists( $outside, 'A scaled file outside uploads must not be deleted.' ); + wp_delete_post( $id, true ); + unlink( $outside ); + rmdir( dirname( $outside ) ); + array_map( 'unlink', glob( $basedir . '/*' ) ); + rmdir( $basedir ); + } + /** * A 0600 upload tmp file must not leave the replaced attachment unreadable to the web server. */ diff --git a/tests/outside-uploads-files.php b/tests/outside-uploads-files.php new file mode 100644 index 000000000..769e31c31 --- /dev/null +++ b/tests/outside-uploads-files.php @@ -0,0 +1,36 @@ + '; use Optml_Dam_Offload_Utils; + use Optml_Test_Outside_Uploads; public static $files = [ 'sample-test', '1PQ7p', @@ -257,9 +260,8 @@ public function test_upload_during_rollback_stays_local(): void { public function test_offload_treats_a_main_file_outside_uploads_as_missing(): void { Optml_Media_Offload::instance()->rollback_and_update_images( [ self::$sample_attachement ] ); - $outside = dirname( wp_get_upload_dir()['basedir'] ) . '/optml-outside-offload.jpg'; - copy( OPTML_PATH . 'tests/assets/sample-test.jpg', $outside ); - update_post_meta( self::$sample_attachement, '_wp_attached_file', '../' . basename( $outside ) ); + $outside = self::outside_uploads_file( 'optml-outside-offload.jpg', OPTML_PATH . 'tests/assets/sample-test.jpg' ); + update_post_meta( self::$sample_attachement, '_wp_attached_file', self::relative_from( wp_get_upload_dir()['basedir'], $outside ) ); Optml_Media_Offload::instance()->upload_and_update_existing_images( [ self::$sample_attachement ] ); @@ -270,12 +272,9 @@ public function test_offload_treats_a_main_file_outside_uploads_as_missing(): vo public function test_offload_keeps_size_files_outside_uploads(): void { Optml_Media_Offload::instance()->rollback_and_update_images( [ self::$sample_attachement ] ); - $parent = dirname( wp_get_upload_dir()['basedir'] ); - $outside = $parent . '/optml-outside-offload-size.jpg'; - file_put_contents( $outside, 'keep' ); - $depth = substr_count( trim( substr( dirname( get_attached_file( self::$sample_attachement ) ), strlen( $parent ) ), '/' ), '/' ) + 1; - $meta = wp_get_attachment_metadata( self::$sample_attachement ); - $meta['sizes']['thumbnail']['file'] = str_repeat( '../', $depth ) . basename( $outside ); + $outside = self::outside_uploads_file( 'optml-outside-offload-size.jpg' ); + $meta = wp_get_attachment_metadata( self::$sample_attachement ); + $meta['sizes']['thumbnail']['file'] = self::relative_from( dirname( get_attached_file( self::$sample_attachement ) ), $outside ); wp_update_attachment_metadata( self::$sample_attachement, $meta ); Optml_Media_Offload::instance()->upload_and_update_existing_images( [ self::$sample_attachement ] ); diff --git a/tests/test-uploads-path.php b/tests/test-uploads-path.php index d283d8364..5fa0ce514 100644 --- a/tests/test-uploads-path.php +++ b/tests/test-uploads-path.php @@ -21,6 +21,11 @@ public function test_file_reached_with_dot_dot_is_refused(): void { $this->assertFalse( UploadsPath::contains( wp_get_upload_dir()['basedir'] . '/../wp-config.php' ) ); } + public function test_path_ending_in_dot_dot_is_refused(): void { + $this->assertFalse( UploadsPath::contains( wp_get_upload_dir()['basedir'] . '/..' ) ); + $this->assertFalse( UploadsPath::contains( wp_get_upload_dir()['basedir'] . '/.' ) ); + } + public function test_backslash_in_a_folder_name_is_not_taken_as_a_separator(): void { if ( '\\' === DIRECTORY_SEPARATOR ) { $this->markTestSkipped( 'A backslash is a separator on Windows.' ); From ab2198d68f569b9a3d6aa79a7c9d4f4a52283c39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 09:24:18 +0200 Subject: [PATCH 06/11] fix: keep links to image sizes the rename leaves in place --- inc/media_rename/attachment_db_renamer.php | 19 +++++- inc/media_rename/attachment_rename.php | 16 ++++- tests/media_rename/test-attachment-rename.php | 63 +++++++++++++++++++ 3 files changed, 96 insertions(+), 2 deletions(-) diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index 5d5d9abaf..d3cd2b4cc 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -26,6 +26,13 @@ class Optml_Attachment_Db_Renamer { */ private $skip_columns = [ 'user_pass' ]; + /** + * Size suffixes, such as `150x150`, whose URLs are left unchanged + * + * @var list + */ + private $kept_size_suffixes = []; + /** * Handle image size variations * @@ -35,9 +42,13 @@ class Optml_Attachment_Db_Renamer { /** * Constructor + * + * @param bool $skip_sizes Whether size and scaled variations are left unchanged. + * @param list $kept_size_suffixes Size suffixes, such as `150x150`, whose URLs are left unchanged. */ - public function __construct( $skip_sizes = false ) { + public function __construct( $skip_sizes = false, array $kept_size_suffixes = [] ) { $this->handle_image_sizes = ! $skip_sizes; + $this->kept_size_suffixes = $kept_size_suffixes; } /** @@ -479,6 +490,9 @@ private function replace_image_urls( $content, $old_url, $new_url ) { function ( $matches ) use ( $old_base, $new_base, $old_domain, $new_domain, $old_dir, $new_dir, $old_ext, $new_ext ) { // Extract the size part (e.g., -300x200) $size_part = substr( $matches[0], strlen( $old_domain . $old_dir . '/' . $old_base ), -strlen( '.' . $old_ext ) ); + if ( in_array( ltrim( $size_part, '-' ), $this->kept_size_suffixes, true ) ) { + return $matches[0]; + } // Build the new URL with the same size return $new_domain . $new_dir . '/' . $new_base . $size_part . '.' . $new_ext; @@ -505,6 +519,9 @@ function ( $matches ) use ( $new_base, $new_domain, $new_dir, $new_ext ) { function ( $matches ) use ( $old_base, $new_base, $old_domain, $new_domain, $old_dir, $new_dir, $old_ext, $new_ext ) { // Extract the size part (e.g., -300x200) $size_part = substr( $matches[0], strlen( str_replace( '/', '\/', $old_domain . $old_dir . '/' . $old_base ) ), -strlen( '.' . $old_ext ) ); + if ( in_array( ltrim( $size_part, '-' ), $this->kept_size_suffixes, true ) ) { + return $matches[0]; + } // Build the new URL with the same size return str_replace( '/', '\/', $new_domain . $new_dir . '/' . $new_base . $size_part . '.' . $new_ext ); diff --git a/inc/media_rename/attachment_rename.php b/inc/media_rename/attachment_rename.php index 92ce217aa..fb0442220 100644 --- a/inc/media_rename/attachment_rename.php +++ b/inc/media_rename/attachment_rename.php @@ -27,6 +27,13 @@ class Optml_Attachment_Rename { */ private $attachment; + /** + * Size suffixes, such as `150x150`, whose files stay under the old name. + * + * @var list + */ + private $kept_size_suffixes = []; + /** * Constructor. * @@ -109,7 +116,7 @@ public function rename() { try { $skip_sizes = ! $this->attachment->is_image(); - $replacer = new Optml_Attachment_Db_Renamer( $skip_sizes ); + $replacer = new Optml_Attachment_Db_Renamer( $skip_sizes, $this->kept_size_suffixes ); $old_url = $this->attachment->get_main_url(); $new_url = $this->get_new_url( $new_unique_filename ); @@ -185,6 +192,8 @@ private function update_attachment_metadata( $new_path ) { // Update image sizes if they exist if ( isset( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) { $already_moved_paths = []; + $skipped_suffixes = []; + $moved_suffixes = []; foreach ( $metadata['sizes'] as $size => $size_data ) { if ( ! isset( $size_data['file'] ) ) { @@ -196,6 +205,7 @@ private function update_attachment_metadata( $new_path ) { $old_size_file_path = sprintf( '%s/%s', $this->attachment->get_dir_path(), $size_data['file'] ); $new_size_file_path = sprintf( '%s/%s', $this->attachment->get_dir_path(), $new_size_file ); if ( ! UploadsPath::contains( $old_size_file_path ) || ! UploadsPath::contains( $new_size_file_path ) ) { + $skipped_suffixes[] = $size_suffix; continue; } @@ -205,8 +215,12 @@ private function update_attachment_metadata( $new_path ) { $already_moved_paths[] = $old_size_file_path; $metadata['sizes'][ $size ]['file'] = $new_size_file; $already_moved_paths = array_unique( $already_moved_paths ); + $moved_suffixes[] = $size_suffix; } } + + // Links to a skipped size keep the old name, because no file is created under the new one. + $this->kept_size_suffixes = array_values( array_diff( $skipped_suffixes, $moved_suffixes ) ); } $metadata_update = wp_update_attachment_metadata( $this->attachment_id, $metadata ); diff --git a/tests/media_rename/test-attachment-rename.php b/tests/media_rename/test-attachment-rename.php index 074e6f723..3cadcec24 100644 --- a/tests/media_rename/test-attachment-rename.php +++ b/tests/media_rename/test-attachment-rename.php @@ -58,6 +58,69 @@ public function test_rename_leaves_size_files_outside_uploads_in_place(): void { unlink( $outside ); } + public function test_rename_keeps_links_to_a_size_left_outside_uploads(): void { + $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/rename-unscaled.jpg' ); + $thumbnail_url = wp_get_attachment_image_url( $id, 'thumbnail' ); + $medium_url = wp_get_attachment_image_url( $id, 'medium' ); + $post_id = $this->post_linking( $thumbnail_url, $medium_url ); + $outside = self::outside_uploads_file( 'optml-outside-linked-size.txt' ); + $meta = wp_get_attachment_metadata( $id ); + $thumbnail = $meta['sizes']['thumbnail']['file']; + $meta['sizes']['thumbnail']['file'] = self::relative_from( ( new Optml_Attachment_Model( $id ) )->get_dir_path(), $outside ); + wp_update_attachment_metadata( $id, $meta ); + + ( new Optml_Attachment_Rename( $id, 'outside-linked-renamed' ) )->rename(); + clean_post_cache( $post_id ); + + $content = get_post( $post_id )->post_content; + $this->assertStringContainsString( $thumbnail_url, $content ); + $this->assertStringContainsString( wp_json_encode( $thumbnail_url ), $content ); + $this->assertStringNotContainsString( $medium_url, $content ); + $this->assertFileExists( ( new Optml_Attachment_Model( $id ) )->get_dir_path() . '/' . $thumbnail ); + wp_delete_post( $id, true ); + unlink( $outside ); + } + + public function test_rename_updates_links_to_a_size_moved_under_another_name(): void { + $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/rename-unscaled.jpg' ); + $thumbnail_url = wp_get_attachment_image_url( $id, 'thumbnail' ); + $post_id = $this->post_linking( $thumbnail_url ); + $outside = self::outside_uploads_file( 'optml-outside-twin-size.txt' ); + $meta = wp_get_attachment_metadata( $id ); + $meta['sizes']['optml_twin'] = $meta['sizes']['thumbnail']; + $meta['sizes']['thumbnail']['file'] = self::relative_from( ( new Optml_Attachment_Model( $id ) )->get_dir_path(), $outside ); + wp_update_attachment_metadata( $id, $meta ); + + ( new Optml_Attachment_Rename( $id, 'outside-twin-renamed' ) )->rename(); + clean_post_cache( $post_id ); + + $this->assertStringNotContainsString( $thumbnail_url, get_post( $post_id )->post_content ); + wp_delete_post( $id, true ); + unlink( $outside ); + } + + /** + * Create a post that links each URL as an image and in JSON block attributes. + * + * The content is written directly, because saving a post strips the escaped slashes of the JSON. + * + * @param string ...$urls Image URLs. + * + * @return int The post ID. + */ + private function post_linking( string ...$urls ): int { + global $wpdb; + + $content = ''; + foreach ( $urls as $url ) { + $content .= ''; + } + $post_id = self::factory()->post->create(); + $wpdb->update( $wpdb->posts, [ 'post_content' => $content ], [ 'ID' => $post_id ] ); + + return $post_id; + } + public function test_rename_refuses_a_main_file_outside_uploads(): void { $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/rename-unscaled.jpg' ); $outside = self::outside_uploads_file( 'optml-outside-main.jpg' ); From b7fe113d08d0b7aee457974fc5ea9f84ae29dfe7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 09:24:39 +0200 Subject: [PATCH 07/11] docs: use a type hint the coding standard accepts --- inc/media_rename/attachment_db_renamer.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index d3cd2b4cc..70874a99b 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -43,8 +43,8 @@ class Optml_Attachment_Db_Renamer { /** * Constructor * - * @param bool $skip_sizes Whether size and scaled variations are left unchanged. - * @param list $kept_size_suffixes Size suffixes, such as `150x150`, whose URLs are left unchanged. + * @param bool $skip_sizes Whether size and scaled variations are left unchanged. + * @param string[] $kept_size_suffixes Size suffixes, such as `150x150`, whose URLs are left unchanged. */ public function __construct( $skip_sizes = false, array $kept_size_suffixes = [] ) { $this->handle_image_sizes = ! $skip_sizes; From 36e4da77cb906de84a88a242b90d6034064cf287 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 09:30:34 +0200 Subject: [PATCH 08/11] perf: look up kept size suffixes by key --- inc/media_rename/attachment_db_renamer.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index 70874a99b..bf0d1ef32 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -27,9 +27,9 @@ class Optml_Attachment_Db_Renamer { private $skip_columns = [ 'user_pass' ]; /** - * Size suffixes, such as `150x150`, whose URLs are left unchanged + * Size suffixes, such as `150x150`, whose URLs are left unchanged, as keys * - * @var list + * @var array */ private $kept_size_suffixes = []; @@ -48,7 +48,7 @@ class Optml_Attachment_Db_Renamer { */ public function __construct( $skip_sizes = false, array $kept_size_suffixes = [] ) { $this->handle_image_sizes = ! $skip_sizes; - $this->kept_size_suffixes = $kept_size_suffixes; + $this->kept_size_suffixes = array_flip( $kept_size_suffixes ); } /** @@ -490,7 +490,7 @@ private function replace_image_urls( $content, $old_url, $new_url ) { function ( $matches ) use ( $old_base, $new_base, $old_domain, $new_domain, $old_dir, $new_dir, $old_ext, $new_ext ) { // Extract the size part (e.g., -300x200) $size_part = substr( $matches[0], strlen( $old_domain . $old_dir . '/' . $old_base ), -strlen( '.' . $old_ext ) ); - if ( in_array( ltrim( $size_part, '-' ), $this->kept_size_suffixes, true ) ) { + if ( isset( $this->kept_size_suffixes[ ltrim( $size_part, '-' ) ] ) ) { return $matches[0]; } @@ -519,7 +519,7 @@ function ( $matches ) use ( $new_base, $new_domain, $new_dir, $new_ext ) { function ( $matches ) use ( $old_base, $new_base, $old_domain, $new_domain, $old_dir, $new_dir, $old_ext, $new_ext ) { // Extract the size part (e.g., -300x200) $size_part = substr( $matches[0], strlen( str_replace( '/', '\/', $old_domain . $old_dir . '/' . $old_base ) ), -strlen( '.' . $old_ext ) ); - if ( in_array( ltrim( $size_part, '-' ), $this->kept_size_suffixes, true ) ) { + if ( isset( $this->kept_size_suffixes[ ltrim( $size_part, '-' ) ] ) ) { return $matches[0]; } From 0207995807d72d98abc0e698c0199f5a2131134f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 11:36:57 +0200 Subject: [PATCH 09/11] fix: rename size links only for size files the rename moved --- inc/media_rename/attachment_db_renamer.php | 18 +++++++++--------- inc/media_rename/attachment_rename.php | 15 +++++---------- tests/media_rename/test-attachment-rename.php | 18 +++++++++++++++++- 3 files changed, 31 insertions(+), 20 deletions(-) diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index bf0d1ef32..ce992e6d5 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -27,11 +27,11 @@ class Optml_Attachment_Db_Renamer { private $skip_columns = [ 'user_pass' ]; /** - * Size suffixes, such as `150x150`, whose URLs are left unchanged, as keys + * Size suffixes, such as `150x150`, whose URLs are renamed, as keys; null renames every size * - * @var array + * @var array|null */ - private $kept_size_suffixes = []; + private $renamed_size_suffixes = null; /** * Handle image size variations @@ -43,12 +43,12 @@ class Optml_Attachment_Db_Renamer { /** * Constructor * - * @param bool $skip_sizes Whether size and scaled variations are left unchanged. - * @param string[] $kept_size_suffixes Size suffixes, such as `150x150`, whose URLs are left unchanged. + * @param bool $skip_sizes Whether size and scaled variations are left unchanged. + * @param string[]|null $renamed_size_suffixes Size suffixes, such as `150x150`, whose URLs are renamed; null renames every size. */ - public function __construct( $skip_sizes = false, array $kept_size_suffixes = [] ) { + public function __construct( $skip_sizes = false, ?array $renamed_size_suffixes = null ) { $this->handle_image_sizes = ! $skip_sizes; - $this->kept_size_suffixes = array_flip( $kept_size_suffixes ); + $this->renamed_size_suffixes = null === $renamed_size_suffixes ? null : array_flip( $renamed_size_suffixes ); } /** @@ -490,7 +490,7 @@ private function replace_image_urls( $content, $old_url, $new_url ) { function ( $matches ) use ( $old_base, $new_base, $old_domain, $new_domain, $old_dir, $new_dir, $old_ext, $new_ext ) { // Extract the size part (e.g., -300x200) $size_part = substr( $matches[0], strlen( $old_domain . $old_dir . '/' . $old_base ), -strlen( '.' . $old_ext ) ); - if ( isset( $this->kept_size_suffixes[ ltrim( $size_part, '-' ) ] ) ) { + if ( null !== $this->renamed_size_suffixes && ! isset( $this->renamed_size_suffixes[ ltrim( $size_part, '-' ) ] ) ) { return $matches[0]; } @@ -519,7 +519,7 @@ function ( $matches ) use ( $new_base, $new_domain, $new_dir, $new_ext ) { function ( $matches ) use ( $old_base, $new_base, $old_domain, $new_domain, $old_dir, $new_dir, $old_ext, $new_ext ) { // Extract the size part (e.g., -300x200) $size_part = substr( $matches[0], strlen( str_replace( '/', '\/', $old_domain . $old_dir . '/' . $old_base ) ), -strlen( '.' . $old_ext ) ); - if ( isset( $this->kept_size_suffixes[ ltrim( $size_part, '-' ) ] ) ) { + if ( null !== $this->renamed_size_suffixes && ! isset( $this->renamed_size_suffixes[ ltrim( $size_part, '-' ) ] ) ) { return $matches[0]; } diff --git a/inc/media_rename/attachment_rename.php b/inc/media_rename/attachment_rename.php index fb0442220..1da3f2abe 100644 --- a/inc/media_rename/attachment_rename.php +++ b/inc/media_rename/attachment_rename.php @@ -28,11 +28,11 @@ class Optml_Attachment_Rename { private $attachment; /** - * Size suffixes, such as `150x150`, whose files stay under the old name. + * Size suffixes, such as `150x150`, of the size files moved to the new name. * * @var list */ - private $kept_size_suffixes = []; + private $moved_size_suffixes = []; /** * Constructor. @@ -116,7 +116,7 @@ public function rename() { try { $skip_sizes = ! $this->attachment->is_image(); - $replacer = new Optml_Attachment_Db_Renamer( $skip_sizes, $this->kept_size_suffixes ); + $replacer = new Optml_Attachment_Db_Renamer( $skip_sizes, $this->moved_size_suffixes ); $old_url = $this->attachment->get_main_url(); $new_url = $this->get_new_url( $new_unique_filename ); @@ -192,8 +192,6 @@ private function update_attachment_metadata( $new_path ) { // Update image sizes if they exist if ( isset( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) { $already_moved_paths = []; - $skipped_suffixes = []; - $moved_suffixes = []; foreach ( $metadata['sizes'] as $size => $size_data ) { if ( ! isset( $size_data['file'] ) ) { @@ -205,7 +203,6 @@ private function update_attachment_metadata( $new_path ) { $old_size_file_path = sprintf( '%s/%s', $this->attachment->get_dir_path(), $size_data['file'] ); $new_size_file_path = sprintf( '%s/%s', $this->attachment->get_dir_path(), $new_size_file ); if ( ! UploadsPath::contains( $old_size_file_path ) || ! UploadsPath::contains( $new_size_file_path ) ) { - $skipped_suffixes[] = $size_suffix; continue; } @@ -215,12 +212,10 @@ private function update_attachment_metadata( $new_path ) { $already_moved_paths[] = $old_size_file_path; $metadata['sizes'][ $size ]['file'] = $new_size_file; $already_moved_paths = array_unique( $already_moved_paths ); - $moved_suffixes[] = $size_suffix; + // Links are renamed only for these sizes, so a skipped size keeps its working links. + $this->moved_size_suffixes[] = $size_suffix; } } - - // Links to a skipped size keep the old name, because no file is created under the new one. - $this->kept_size_suffixes = array_values( array_diff( $skipped_suffixes, $moved_suffixes ) ); } $metadata_update = wp_update_attachment_metadata( $this->attachment_id, $metadata ); diff --git a/tests/media_rename/test-attachment-rename.php b/tests/media_rename/test-attachment-rename.php index 3cadcec24..c4846f31d 100644 --- a/tests/media_rename/test-attachment-rename.php +++ b/tests/media_rename/test-attachment-rename.php @@ -58,7 +58,22 @@ public function test_rename_leaves_size_files_outside_uploads_in_place(): void { unlink( $outside ); } - public function test_rename_keeps_links_to_a_size_left_outside_uploads(): void { + /** + * Tampered metadata can change the size numbers too. + * + * @return array + */ + public function size_width_changes(): array { + return [ + 'same width' => [ 0 ], + 'changed width' => [ 1 ], + ]; + } + + /** + * @dataProvider size_width_changes + */ + public function test_rename_keeps_links_to_a_size_left_outside_uploads( int $width_change ): void { $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/rename-unscaled.jpg' ); $thumbnail_url = wp_get_attachment_image_url( $id, 'thumbnail' ); $medium_url = wp_get_attachment_image_url( $id, 'medium' ); @@ -67,6 +82,7 @@ public function test_rename_keeps_links_to_a_size_left_outside_uploads(): void { $meta = wp_get_attachment_metadata( $id ); $thumbnail = $meta['sizes']['thumbnail']['file']; $meta['sizes']['thumbnail']['file'] = self::relative_from( ( new Optml_Attachment_Model( $id ) )->get_dir_path(), $outside ); + $meta['sizes']['thumbnail']['width'] += $width_change; wp_update_attachment_metadata( $id, $meta ); ( new Optml_Attachment_Rename( $id, 'outside-linked-renamed' ) )->rename(); From 6f70beb0dd76cac94cff625dee69b0d6e2e175bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 11:53:20 +0200 Subject: [PATCH 10/11] test: cover escaped links of moved sizes and an empty moved list --- tests/media_rename/test-attachment-rename.php | 1 + tests/media_rename/test-db-renamer.php | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/tests/media_rename/test-attachment-rename.php b/tests/media_rename/test-attachment-rename.php index c4846f31d..cbbbd287a 100644 --- a/tests/media_rename/test-attachment-rename.php +++ b/tests/media_rename/test-attachment-rename.php @@ -92,6 +92,7 @@ public function test_rename_keeps_links_to_a_size_left_outside_uploads( int $wid $this->assertStringContainsString( $thumbnail_url, $content ); $this->assertStringContainsString( wp_json_encode( $thumbnail_url ), $content ); $this->assertStringNotContainsString( $medium_url, $content ); + $this->assertStringNotContainsString( wp_json_encode( $medium_url ), $content ); $this->assertFileExists( ( new Optml_Attachment_Model( $id ) )->get_dir_path() . '/' . $thumbnail ); wp_delete_post( $id, true ); unlink( $outside ); diff --git a/tests/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index 347769080..13b1e2022 100644 --- a/tests/media_rename/test-db-renamer.php +++ b/tests/media_rename/test-db-renamer.php @@ -284,6 +284,20 @@ public function test_static__ensure_sizes() { } } + public function test_static__renames_only_listed_sizes() { + $old_url = 'http://om-wp.test/wp-content/uploads/2025/03/asdfgh.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2025/03/listed-sizes.jpg'; + + $listed = self::$replace_method->invoke( new Optml_Attachment_Db_Renamer( false, [ '300x200' ] ), self::POST_CONTENT, $old_url, $new_url ); + $none = self::$replace_method->invoke( new Optml_Attachment_Db_Renamer( false, [] ), self::POST_CONTENT, $old_url, $new_url ); + + $this->assertStringContainsString( 'listed-sizes-300x200.jpg', $listed ); + $this->assertStringContainsString( 'asdfgh-150x150.jpg', $listed ); + $this->assertStringNotContainsString( 'listed-sizes-150x150.jpg', $listed ); + $this->assertStringContainsString( 'asdfgh-300x200.jpg', $none ); + $this->assertStringContainsString( 'asdfgh-150x150.jpg', $none ); + } + public function test_db__post_content_video_replacement() { $initial_url = 'http://om-wp.test/wp-content/uploads/2025/03/video-file.mp4'; $new_url = 'http://example.com/wp-content/uploads/2020/01/new-home-made-tutorial.mp4'; From 4f55b0b49a54f21d7990f545b6b7d592ed91edc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 12:32:17 +0200 Subject: [PATCH 11/11] fix: keep links to a size whose file another size moved, and drop the stale PHPStan entry --- inc/media_rename/attachment_rename.php | 5 ++++- phpstan-baseline.neon | 6 ------ tests/media_rename/test-attachment-rename.php | 21 +++++++++++++++++++ 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/inc/media_rename/attachment_rename.php b/inc/media_rename/attachment_rename.php index 1da3f2abe..94d5f2fe5 100644 --- a/inc/media_rename/attachment_rename.php +++ b/inc/media_rename/attachment_rename.php @@ -212,7 +212,10 @@ private function update_attachment_metadata( $new_path ) { $already_moved_paths[] = $old_size_file_path; $metadata['sizes'][ $size ]['file'] = $new_size_file; $already_moved_paths = array_unique( $already_moved_paths ); - // Links are renamed only for these sizes, so a skipped size keeps its working links. + } + // Links are renamed only for size files this rename created, so other links keep working. A path + // moved for an earlier size creates no file with this suffix. + if ( $move ) { $this->moved_size_suffixes[] = $size_suffix; } } diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 92c14f725..a0f7ec18c 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -2400,12 +2400,6 @@ parameters: count: 2 path: inc/media_offload.php - - - message: '#^Method Optml_Attachment_Db_Renamer\:\:__construct\(\) has parameter \$skip_sizes with no type specified\.$#' - identifier: missingType.parameter - count: 1 - path: inc/media_rename/attachment_db_renamer.php - - message: '#^Method Optml_Attachment_Db_Renamer\:\:get_columns\(\) return type has no value type specified in iterable type array\.$#' identifier: missingType.iterableValue diff --git a/tests/media_rename/test-attachment-rename.php b/tests/media_rename/test-attachment-rename.php index cbbbd287a..2f122e116 100644 --- a/tests/media_rename/test-attachment-rename.php +++ b/tests/media_rename/test-attachment-rename.php @@ -116,6 +116,27 @@ public function test_rename_updates_links_to_a_size_moved_under_another_name(): unlink( $outside ); } + public function test_rename_keeps_links_to_a_size_whose_file_another_size_moved(): void { + $id = self::factory()->attachment->create_upload_object( OPTML_PATH . 'tests/assets/rename-unscaled.jpg' ); + $thumbnail_url = wp_get_attachment_image_url( $id, 'thumbnail' ); + $post_id = $this->post_linking( $thumbnail_url ); + $outside = self::outside_uploads_file( 'optml-outside-shared-size.txt' ); + $meta = wp_get_attachment_metadata( $id ); + $thumbnail = $meta['sizes']['thumbnail']; + // A size with the thumbnail dimensions that names the medium file, which the medium size moves first. + $meta['sizes']['optml_twin'] = array_merge( $meta['sizes']['medium'], [ 'width' => $thumbnail['width'], 'height' => $thumbnail['height'] ] ); + $meta['sizes']['thumbnail']['file'] = self::relative_from( ( new Optml_Attachment_Model( $id ) )->get_dir_path(), $outside ); + wp_update_attachment_metadata( $id, $meta ); + + ( new Optml_Attachment_Rename( $id, 'outside-shared-renamed' ) )->rename(); + clean_post_cache( $post_id ); + + $this->assertStringContainsString( $thumbnail_url, get_post( $post_id )->post_content ); + $this->assertFileExists( ( new Optml_Attachment_Model( $id ) )->get_dir_path() . '/' . $thumbnail['file'] ); + wp_delete_post( $id, true ); + unlink( $outside ); + } + /** * Create a post that links each URL as an image and in JSON block attributes. *