From 7e99825be839c2f8603cf3b1277edecf6b4cc5fd Mon Sep 17 00:00:00 2001 From: Girish Panchal <79647963+girishpanchal30@users.noreply.github.com> Date: Thu, 5 Nov 2026 06:31:37 +0530 Subject: [PATCH 01/38] Improved selected compression mode contrast (#1225) * fix: improve selected compression mode contrast * fix: clarify comment for selected-option indicator --- assets/src/dashboard/style.scss | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/assets/src/dashboard/style.scss b/assets/src/dashboard/style.scss index 69ac06e46..2bb8edbd2 100644 --- a/assets/src/dashboard/style.scss +++ b/assets/src/dashboard/style.scss @@ -84,6 +84,11 @@ $mango-yellow: #FBBF24; } .components-toggle-group-control{ border-color: var(--wp-components-color-foreground); + // Selected-option indicator drawn by ToggleGroupControl's ::before. + &::before{ + background: var(--wp-components-color-foreground); + border-color: var(--wp-components-color-foreground); + } } .base-control-label { color: #363636; From ed124d4140067ea9c52803b1261d0dd25c188c08 Mon Sep 17 00:00:00 2001 From: Marius Cristea Date: Thu, 5 Nov 2026 12:15:42 +0200 Subject: [PATCH 02/38] Update codeinwp/optimole-sdk to 1.3.0 (#1230) SDK 1.3.0 fixes the swapped Position::NORTH_EAST / NORTH_WEST values. Image sizes registered with a top-corner crop (['left','top'], ['right','top']) were cropped toward the opposite corner; they now crop toward the corner WordPress asked for. Flip the two test assertions that pinned the old output. Co-authored-by: Claude Opus 5.5 --- composer.json | 2 +- composer.lock | 12 ++++++------ tests/test-dam.php | 2 +- tests/test-media.php | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/composer.json b/composer.json index e0933ec99..c0f420d23 100644 --- a/composer.json +++ b/composer.json @@ -58,7 +58,7 @@ "require": { "php": ">=7.4", "codeinwp/themeisle-sdk": "^3.3.65", - "codeinwp/optimole-sdk": "^1.2", + "codeinwp/optimole-sdk": "^1.3", "enshrined/svg-sanitize": "^1.0.0" } } diff --git a/composer.lock b/composer.lock index 07d43a3b4..bcf45527e 100644 --- a/composer.lock +++ b/composer.lock @@ -4,20 +4,20 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "1c6cb28ea9cfac46761c17ca70f1a8d0", + "content-hash": "fea9ed731d69e59f5089fa14a003e3e3", "packages": [ { "name": "codeinwp/optimole-sdk", - "version": "v1.2.4", + "version": "v1.3.0", "source": { "type": "git", "url": "https://github.com/Codeinwp/optimole-php-sdk.git", - "reference": "2f7a48525014bd681f39ddc85c55521b719d5879" + "reference": "15ce5e000ff005c6a8dfb15142916780eae645a1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Codeinwp/optimole-php-sdk/zipball/2f7a48525014bd681f39ddc85c55521b719d5879", - "reference": "2f7a48525014bd681f39ddc85c55521b719d5879", + "url": "https://api.github.com/repos/Codeinwp/optimole-php-sdk/zipball/15ce5e000ff005c6a8dfb15142916780eae645a1", + "reference": "15ce5e000ff005c6a8dfb15142916780eae645a1", "shasum": "" }, "require": { @@ -60,7 +60,7 @@ "issues": "https://github.com/Codeinwp/codeinwp/optimole-php-sdk/issues", "source": "https://github.com/Codeinwp/optimole-php-sdk" }, - "time": "2025-11-14T18:01:16+00:00" + "time": "2026-11-05T09:54:25+00:00" }, { "name": "codeinwp/themeisle-sdk", diff --git a/tests/test-dam.php b/tests/test-dam.php index 8836a5689..6313bca56 100644 --- a/tests/test-dam.php +++ b/tests/test-dam.php @@ -249,7 +249,7 @@ public function test_alter_attachment_image_src() { $this->assertEquals( 100, $result[2] ); $this->assertFalse( $result[3] ); $result = $this->dam->alter_attachment_image_src( false, $id, 'test_gravity', false ); - $this->assertStringContainsString( 'w:200/h:100/g:noea/rt:fill', $result[0] ); + $this->assertStringContainsString( 'w:200/h:100/g:nowe/rt:fill', $result[0] ); $result = $this->dam->alter_attachment_image_src( false, $id, 'test_portrait', false ); $this->assertStringContainsString( 'w:100/h:200/g:ce/rt:fill', $result[0] ); diff --git a/tests/test-media.php b/tests/test-media.php index 78d6f37a3..ea134de47 100644 --- a/tests/test-media.php +++ b/tests/test-media.php @@ -332,7 +332,7 @@ public function test_image_processed() { $my_size_image = wp_get_attachment_image_src(self::$sample_attachement, 'my_size_crop' ); $this->assertStringContainsString( 'example.i.optimole.com', $my_size_image[0] ); - $this->assertStringContainsString('/w:200/h:200/rt:fill/g:nowe/q:mauto/process:' . self::$sample_attachement .'/id:579c7f7707ce87caa65fdf50c238a117/http://example.org/sample-test.jpg', $my_size_image[0]); + $this->assertStringContainsString('/w:200/h:200/rt:fill/g:noea/q:mauto/process:' . self::$sample_attachement .'/id:579c7f7707ce87caa65fdf50c238a117/http://example.org/sample-test.jpg', $my_size_image[0]); $this->assertStringContainsString( 'example.i.optimole.com', $image_thumbnail_size[0] ); $this->assertStringContainsString( '/w:150/h:150/rt:fill/g:ce/q:mauto/process:' . self::$sample_attachement .'/id:579c7f7707ce87caa65fdf50c238a117/http://example.org/sample-test.jpg', $image_thumbnail_size[0] ); From 55741ef241f810c77be9041adeaff32aaabf64f9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 14:01:25 +0200 Subject: [PATCH 03/38] chore(deps-dev): bump phpstan/phpstan from 2.3.3 to 2.3.4 (#1229) Bumps [phpstan/phpstan](https://github.com/phpstan/phpstan-phar-composer-source) from 2.3.3 to 2.3.4. - [Commits](https://github.com/phpstan/phpstan-phar-composer-source/commits) --- updated-dependencies: - dependency-name: phpstan/phpstan dependency-version: 2.3.4 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- composer.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.lock b/composer.lock index bcf45527e..a2c5f22a0 100644 --- a/composer.lock +++ b/composer.lock @@ -904,11 +904,11 @@ }, { "name": "phpstan/phpstan", - "version": "2.3.3", + "version": "2.3.4", "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/4b57dc8ca7456b635d1661845f44bc060b02c6b0", - "reference": "4b57dc8ca7456b635d1661845f44bc060b02c6b0", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/f20ce6f3c82556cfcfc086b152445a12d1d64fff", + "reference": "f20ce6f3c82556cfcfc086b152445a12d1d64fff", "shasum": "" }, "require": { @@ -964,7 +964,7 @@ "type": "github" } ], - "time": "2026-10-27T14:06:26+00:00" + "time": "2026-10-28T22:38:53+00:00" }, { "name": "phpunit/php-code-coverage", From eb31d9b6346f76101e9683dfe9ca211f5599f3b9 Mon Sep 17 00:00:00 2001 From: Girish Panchal <79647963+girishpanchal30@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:34:27 +0530 Subject: [PATCH 04/38] Supported media rename and video blocks on older WP versions (#1208) * fix: support media rename and video blocks on older WP versions * refactor: remove PHPCS ignores from renamer * fix: ensure notices store compatibility with WP 5.5 * fix: add RadioControl fallback for compression modes --- .../src/dashboard/parts/connected/Toasts.js | 5 +- .../parts/connected/settings/Compression.js | 64 +++++++++----- .../settings/__tests__/Compression.test.js | 83 +++++++++++++++++++ .../src/dashboard/utils/__tests__/api.test.js | 16 +++- assets/src/dashboard/utils/api.js | 6 +- assets/src/widget/index.js | 11 ++- inc/media_rename/attachment_db_renamer.php | 41 +++++---- inc/video_player.php | 22 ++++- jest.config.js | 3 +- tests/media_rename/test-db-renamer.php | 81 ++++++++++++++++++ tests/test-video-player-block.php | 25 ++++++ 11 files changed, 300 insertions(+), 57 deletions(-) create mode 100644 assets/src/dashboard/parts/connected/settings/__tests__/Compression.test.js diff --git a/assets/src/dashboard/parts/connected/Toasts.js b/assets/src/dashboard/parts/connected/Toasts.js index 43864a849..45f6fbc87 100644 --- a/assets/src/dashboard/parts/connected/Toasts.js +++ b/assets/src/dashboard/parts/connected/Toasts.js @@ -1,15 +1,14 @@ import { filter } from 'lodash'; import { SnackbarList } from '@wordpress/components'; import { useSelect, useDispatch } from '@wordpress/data'; -import { store as noticesStore } from '@wordpress/notices'; export default function() { const notices = useSelect( - ( select ) => select( noticesStore ).getNotices(), + ( select ) => select( 'core/notices' ).getNotices(), [] ); - const { removeNotice } = useDispatch( noticesStore ); + const { removeNotice } = useDispatch( 'core/notices' ); const snackbarNotices = filter( notices, { type: 'snackbar' diff --git a/assets/src/dashboard/parts/connected/settings/Compression.js b/assets/src/dashboard/parts/connected/settings/Compression.js index b44dc63c0..5816e6250 100644 --- a/assets/src/dashboard/parts/connected/settings/Compression.js +++ b/assets/src/dashboard/parts/connected/settings/Compression.js @@ -14,6 +14,7 @@ import { BaseControl, Button, Icon, + RadioControl, RangeControl, ToggleControl, @@ -173,32 +174,51 @@ const Compression = ({ } }, [ showSample ]); + const compressionModes = [ + { + className: 'bg-blue-500', + label: optimoleDashboardApp.strings.options_strings.compression_mode_speed_optimized, + value: 'speed_optimized' + }, + { + label: optimoleDashboardApp.strings.options_strings.compression_mode_quality_optimized, + value: 'quality_optimized' + }, + { + label: optimoleDashboardApp.strings.options_strings.compression_mode_custom, + value: 'custom' + } + ]; + + const compressionModeLabel = ( +
+ {optimoleDashboardApp.strings.options_strings.compression_mode} +
+ ); + return ( <> - transformCompressionMode( value ) } - value={ compressionMode } - label={ ( -
- {optimoleDashboardApp.strings.options_strings.compression_mode} -
- ) } - > - transformCompressionMode( value ) } + value={ compressionMode } + label={ compressionModeLabel } + > + { compressionModes.map( mode => ( + + ) ) } +
+ ) : ( + transformCompressionMode( value ) } /> - - - + ) } {'speed_optimized' === compressionMode && (

{optimoleDashboardApp.strings.options_strings.compression_mode_speed_optimized_desc} diff --git a/assets/src/dashboard/parts/connected/settings/__tests__/Compression.test.js b/assets/src/dashboard/parts/connected/settings/__tests__/Compression.test.js new file mode 100644 index 000000000..5fbf23fc6 --- /dev/null +++ b/assets/src/dashboard/parts/connected/settings/__tests__/Compression.test.js @@ -0,0 +1,83 @@ +/** + * The compression mode control on WordPress versions whose @wordpress/components has no + * ToggleGroupControl (below 5.9). + */ +import { act } from 'react-dom/test-utils'; +import { createRoot } from 'react-dom/client'; + +jest.mock( '@wordpress/components', () => ({ + BaseControl: ({ children }) => children, + Button: ({ children }) => children, + Icon: () => null, + RangeControl: () => null, + ToggleControl: () => null, + RadioControl: ({ options, selected, onChange }) => options.map( option => ( + onChange( option.value ) } + /> + ) ) +}) ); +jest.mock( '@wordpress/data', () => ({ + useSelect: () => ({ sampleImages: {}, isLoading: false }) +}) ); +jest.mock( '@wordpress/icons', () => ({ rotateRight: null }) ); +jest.mock( 'react-compare-image', () => () => null ); +jest.mock( '../../../../utils/api', () => ({ sampleRate: jest.fn() }) ); +jest.mock( '../../../components/ProgressBar', () => () => null ); + +global.IS_REACT_ACT_ENVIRONMENT = true; +global.optimoleDashboardApp = { + strings: { + options_strings: new Proxy({}, { get: ( target, name ) => name }) + } +}; + +const Compression = require( '../Compression' ).default; + +describe( 'Compression', () => { + let container; + let root; + + beforeEach( () => { + container = document.createElement( 'div' ); + document.body.appendChild( container ); + root = createRoot( container ); + }); + + afterEach( () => { + act( () => root.unmount() ); + container.remove(); + }); + + test( 'offers the three compression modes without ToggleGroupControl', () => { + const setSettings = jest.fn(); + + act( () => { + root.render( + + ); + }); + + const radios = container.querySelectorAll( 'input[type="radio"]' ); + expect( Array.from( radios, radio => radio.value ) ).toEqual([ 'speed_optimized', 'quality_optimized', 'custom' ]); + expect( container.querySelector( 'input:checked' ).value ).toBe( 'quality_optimized' ); + + act( () => radios[0].click() ); + + expect( setSettings ).toHaveBeenCalledWith( expect.objectContaining({ + compression_mode: 'speed_optimized', + retina_images: 'disabled' + }) ); + }); +}); diff --git a/assets/src/dashboard/utils/__tests__/api.test.js b/assets/src/dashboard/utils/__tests__/api.test.js index 09566d36f..61ab5e308 100644 --- a/assets/src/dashboard/utils/__tests__/api.test.js +++ b/assets/src/dashboard/utils/__tests__/api.test.js @@ -7,14 +7,16 @@ const mockActions = {}; jest.mock( '@wordpress/api-fetch', () => jest.fn() ); jest.mock( '@wordpress/data', () => ({ - dispatch: () => new Proxy({}, { + + // Like the default registry, an unregistered store name resolves to null. + dispatch: store => [ 'optimole', 'core/notices' ].includes( store ) ? new Proxy({}, { get: ( target, name ) => { if ( ! mockActions[ name ]) { mockActions[ name ] = jest.fn(); } return mockActions[ name ]; } - }), + }) : null, select: () => ({ getOptimizedImages: () => [], getQueryArgs: () => ({}), @@ -24,8 +26,8 @@ jest.mock( '@wordpress/data', () => ({ }) ); jest.mock( '@wordpress/url', () => ({ addQueryArgs: url => url }) ); -// Provided by WordPress at runtime, not installed. -jest.mock( '@wordpress/notices', () => ({ store: 'core/notices' }), { virtual: true }); +// Provided by WordPress at runtime, not installed; before 5.7 it has no `store` export. +jest.mock( '@wordpress/notices', () => ({}), { virtual: true }); jest.mock( '../helpers', () => ({ toggleDashboardSidebarSubmenu: jest.fn() }) ); global.optimoleDashboardApp = { @@ -37,6 +39,12 @@ global.jQuery = { ajax: jest.fn() }; const apiFetch = require( '@wordpress/api-fetch' ); const { callSync } = require( '../api' ); +describe( 'api module', () => { + test( 'loads when @wordpress/notices has no store export', () => { + expect( () => jest.isolateModules( () => require( '../api' ) ) ).not.toThrow(); + }); +}); + const flushPromises = () => new Promise( resolve => setTimeout( resolve, 0 ) ); describe( 'callSync', () => { diff --git a/assets/src/dashboard/utils/api.js b/assets/src/dashboard/utils/api.js index 2b93b898e..8588d1903 100644 --- a/assets/src/dashboard/utils/api.js +++ b/assets/src/dashboard/utils/api.js @@ -9,7 +9,9 @@ import { } from '@wordpress/data'; import { addQueryArgs } from '@wordpress/url'; -import { store as noticesStore } from '@wordpress/notices'; + +// Registers the core/notices store; its `store` export only exists from WordPress 5.7. +import '@wordpress/notices'; import { toggleDashboardSidebarSubmenu } from './helpers'; const { @@ -52,7 +54,7 @@ const { getSiteSettings } = select( 'optimole' ); -const { createNotice } = dispatch( noticesStore ); +const { createNotice } = dispatch( 'core/notices' ); export const sendOnboardingImages = ( data = {}) => { diff --git a/assets/src/widget/index.js b/assets/src/widget/index.js index e7ddd84e0..684bca00d 100644 --- a/assets/src/widget/index.js +++ b/assets/src/widget/index.js @@ -1,7 +1,12 @@ -import { createRoot } from '@wordpress/element'; +import { createRoot, render } from '@wordpress/element'; import App from './App'; import './style.scss'; -const root = createRoot( document.getElementById( 'optimole-dashboard-widget-root' ) ); +const container = document.getElementById( 'optimole-dashboard-widget-root' ); -root.render( ); +// createRoot ships with WordPress 6.2 (React 18). +if ( createRoot ) { + createRoot( container ).render( ); +} else { + render( , container ); +} diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index 171db9cbe..5d5d9abaf 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -114,7 +114,7 @@ private function get_columns( $table ) { $text_columns = []; // Get table information - $results = $wpdb->get_results( $wpdb->prepare( 'DESCRIBE %i', $table ) ); + $results = $wpdb->get_results( 'DESCRIBE ' . esc_sql( $this->quote_identifier( $table ) ) ); if ( ! empty( $results ) ) { // phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase @@ -132,6 +132,19 @@ private function get_columns( $table ) { return [ $primary_keys, $text_columns ]; } + /** + * Quote a table or column name for use in SQL. + * + * Replaces the %i placeholder, which wpdb::prepare() only supports from WordPress 6.2. + * + * @param string $identifier Table or column name. + * + * @return string The backtick-quoted identifier. + */ + private function quote_identifier( string $identifier ): string { + return '`' . str_replace( '`', '``', $identifier ) . '`'; + } + /** * Check if column is text type * @@ -166,12 +179,8 @@ private function process_column( $table, $column, $primary_keys, $old_url, $new_ // Check for serialized data $has_serialized = $wpdb->get_var( - $wpdb->prepare( - "SELECT COUNT(%i) FROM %i WHERE %i REGEXP '^[aiO]:[1-9]' LIMIT 1", - $column, - $table, - $column - ) + 'SELECT COUNT(' . esc_sql( $this->quote_identifier( $column ) ) . ') FROM ' . esc_sql( $this->quote_identifier( $table ) ) . + ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . " REGEXP '^[aiO]:[1-9]' LIMIT 1" ); // Process with PHP if serialized data is found @@ -256,9 +265,7 @@ private function sql_handle_column( $table, $column, $primary_keys, $old_url, $n // Get rows with regular URLs $rows = $wpdb->get_results( $wpdb->prepare( - 'SELECT * FROM %i WHERE %i LIKE %s', - $table, - $column, + 'SELECT * FROM ' . esc_sql( $this->quote_identifier( $table ) ) . ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . ' LIKE %s', '%' . $wpdb->esc_like( $base_url ) . '%' ) ); @@ -269,9 +276,7 @@ private function sql_handle_column( $table, $column, $primary_keys, $old_url, $n // Get rows with JSON-escaped URLs $json_rows = $wpdb->get_results( $wpdb->prepare( - 'SELECT * FROM %i WHERE %i LIKE %s', - $table, - $column, + 'SELECT * FROM ' . esc_sql( $this->quote_identifier( $table ) ) . ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . ' LIKE %s', '%' . $wpdb->esc_like( $json_base_url ) . '%' ) ); @@ -330,17 +335,14 @@ private function php_handle_column( $table, $column, $primary_keys, $old_url, $n // Build the query and allow processing with multiple primary keys. $query = 'SELECT '; foreach ( $primary_keys as $key => $value ) { - $query .= $wpdb->prepare( '%i, ', $value ); + $query .= $this->quote_identifier( $value ) . ', '; } - $query .= '%i FROM %i WHERE %i LIKE %s'; + $query .= $this->quote_identifier( $column ) . ' FROM ' . $this->quote_identifier( $table ) . ' WHERE ' . $this->quote_identifier( $column ) . ' LIKE %s'; // Get the rows that need updating - first for regular URLs $rows = $wpdb->get_results( $wpdb->prepare( $query, // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared - $column, - $table, - $column, '%' . $wpdb->esc_like( $base_url ) . '%' ) ); @@ -349,9 +351,6 @@ private function php_handle_column( $table, $column, $primary_keys, $old_url, $n $json_rows = $wpdb->get_results( $wpdb->prepare( $query, // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared - $column, - $table, - $column, '%' . $wpdb->esc_like( $json_base_url ) . '%' ) ); diff --git a/inc/video_player.php b/inc/video_player.php index ee0971163..e12e968ce 100644 --- a/inc/video_player.php +++ b/inc/video_player.php @@ -235,11 +235,31 @@ function ( $key, $value ) { // Alignment and custom classes already come from block supports, so no attribute is forwarded here. return sprintf( '

', - get_block_wrapper_attributes(), + function_exists( 'get_block_wrapper_attributes' ) ? get_block_wrapper_attributes() : $this->get_legacy_wrapper_attributes( $attributes ), implode( ' ', $tag_attributes ), ); } + /** + * Build the wrapper class attribute on WordPress versions without get_block_wrapper_attributes() (below 5.6). + * + * @param array $attributes The block attributes. + * @return string The wrapper class attribute. + */ + private function get_legacy_wrapper_attributes( array $attributes ): string { + $classes = [ 'wp-block-optimole-video-player' ]; + + if ( isset( $attributes['align'] ) && in_array( $attributes['align'], [ 'left', 'center', 'right', 'wide', 'full' ], true ) ) { + $classes[] = 'align' . $attributes['align']; + } + + if ( ! empty( $attributes['className'] ) && is_string( $attributes['className'] ) ) { + $classes[] = $attributes['className']; + } + + return 'class="' . esc_attr( implode( ' ', $classes ) ) . '"'; + } + /** * Get the localization strings. * diff --git a/jest.config.js b/jest.config.js index 151a91f60..adbf760ad 100644 --- a/jest.config.js +++ b/jest.config.js @@ -17,7 +17,8 @@ module.exports = { targets: { node: 'current' } - }] + }], + ['@babel/preset-react', { runtime: 'automatic' }] ] }] }, diff --git a/tests/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index 014250d9e..347769080 100644 --- a/tests/media_rename/test-db-renamer.php +++ b/tests/media_rename/test-db-renamer.php @@ -44,6 +44,13 @@ class Test_Attachment_Db_Renamer extends WP_UnitTestCase { protected static $replacer_skip_sizes; protected static $replace_skip_sizes_method; // ReflectionMethod + /** + * The database object swapped out by a test, restored in tear_down(). + * + * @var wpdb|null + */ + private ?wpdb $original_wpdb = null; + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { self::$post_id = $factory->post->create( [ 'post_title' => 'Test Post', @@ -62,6 +69,15 @@ public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ) { self::$replace_skip_sizes_method->setAccessible( true ); } + public function tear_down(): void { + if ( null !== $this->original_wpdb ) { + $GLOBALS['wpdb'] = $this->original_wpdb; + $this->original_wpdb = null; + } + + parent::tear_down(); + } + public static function tear_down_after_class() { wp_delete_post( self::$attachment_id, true ); wp_delete_post( self::$post_id, true ); @@ -321,6 +337,25 @@ public function test_db__post_content_sizes_replacement() { } } + /** + * Post content is updated when wpdb::prepare() does not support %i (WordPress below 6.2). + */ + public function test_replace_without_identifier_placeholder_support(): void { + global $wpdb; + + $old_url = 'http://example.com/wp-content/uploads/2020/01/legacy-prepare.jpg'; + $new_url = 'http://example.com/wp-content/uploads/2020/01/legacy-prepare-renamed.jpg'; + $post_id = self::factory()->post->create( [ 'post_content' => '' ] ); + + $this->original_wpdb = $wpdb; + $wpdb = Optml_Test_Wpdb_Without_Identifier_Placeholders::from( $wpdb ); + + $count = ( new Optml_Attachment_Db_Renamer() )->replace( $old_url, $new_url ); + + $this->assertGreaterThan( 0, $count ); + $this->assertStringContainsString( $new_url, $wpdb->get_var( $wpdb->prepare( "SELECT post_content FROM {$wpdb->posts} WHERE ID = %d", $post_id ) ) ); + } + public function test_replace_updates_comment_content(): void { $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/comment-photo.jpg'; $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/comment-renamed.jpg'; @@ -493,3 +528,49 @@ public function test_replace_without_sizes_updates_json_escaped_url_in_meta(): v ); } } + +/** + * A wpdb sharing the test connection whose prepare() leaves %i as literal text, as WordPress below 6.2 did. + */ +class Optml_Test_Wpdb_Without_Identifier_Placeholders extends wpdb { + + /** + * Copy an existing wpdb, including its connection. + * + * @param wpdb $source The database object to copy. + * @return self The copy. + */ + public static function from( wpdb $source ): self { + $copy = ( new ReflectionClass( self::class ) )->newInstanceWithoutConstructor(); + $properties = Closure::bind( + function (): array { + return get_object_vars( $this ); + }, + $source, + wpdb::class + )(); + + Closure::bind( + function ( array $properties ): void { + foreach ( $properties as $name => $value ) { + $this->$name = $value; + } + }, + $copy, + wpdb::class + )( $properties ); + + return $copy; + } + + /** + * Prepare a query with %i escaped to a literal, like wpdb::prepare() before WordPress 6.2. + * + * @param string $query Query with placeholders. + * @param mixed ...$args Values for the placeholders. + * @return string|void The prepared query. + */ + public function prepare( $query, ...$args ) { + return parent::prepare( str_replace( '%i', '%%i', $query ), ...$args ); + } +} diff --git a/tests/test-video-player-block.php b/tests/test-video-player-block.php index 9150f63cf..5b5047754 100644 --- a/tests/test-video-player-block.php +++ b/tests/test-video-player-block.php @@ -179,4 +179,29 @@ public function test_spacing_styles_are_sanitized() { $this->assertStringNotContainsString( 'color:red', $rendered ); $this->assertStringNotContainsString( 'color:blue', $rendered ); } + + /** + * Without get_block_wrapper_attributes() (WordPress 5.5) the wrapper keeps its block, alignment and custom classes only. + */ + public function test_legacy_wrapper_attributes(): void { + $method = new ReflectionMethod( Optml_Video_Player::class, 'get_legacy_wrapper_attributes' ); + $method->setAccessible( true ); + + $this->assertSame( + 'class="wp-block-optimole-video-player alignwide my-custom-class"', + $method->invoke( new Optml_Video_Player(), [ + 'align' => 'wide', + 'className' => 'my-custom-class', + 'onmouseover' => 'alert(1)', + ] ) + ); + $this->assertSame( + 'class="wp-block-optimole-video-player"', + $method->invoke( new Optml_Video_Player(), [ 'align' => 'wide" onmouseover="alert(1)' ] ) + ); + $this->assertSame( + 'class="wp-block-optimole-video-player x" onmouseover="alert(1)"', + $method->invoke( new Optml_Video_Player(), [ 'className' => 'x" onmouseover="alert(1)' ] ) + ); + } } From 42a09a2c5d3bad7be467dc4214907243642ef8d1 Mon Sep 17 00:00:00 2001 From: Soare Robert Daniel Date: Fri, 6 Nov 2026 16:28:08 +0200 Subject: [PATCH 05/38] fix(bf): share the SDK Black Friday dismissal and show the banner again each year (#1188) --- inc/admin.php | 45 +++++++++++++++++++++--- inc/rest.php | 6 ++++ tests/test-admin.php | 84 ++++++++++++++++++++++++++++++++------------ 3 files changed, 107 insertions(+), 28 deletions(-) diff --git a/inc/admin.php b/inc/admin.php index 72fb017ff..6775929c0 100755 --- a/inc/admin.php +++ b/inc/admin.php @@ -23,7 +23,7 @@ class Optml_Admin { const IMAGE_DATA_COLLECTED_BATCH = 100; - const BF_PROMO_DISMISS_KEY = 'optml_bf25_notice_dismiss'; + const SDK_BF_DISMISS_META = 'themeisle_sdk_dismissed_notice_black_friday'; const SPC_BANNER_DISMISS_KEY = 'optml_spc_banner_dismiss'; @@ -1646,6 +1646,40 @@ private function get_spc_status() { return 'not-installed'; } + /** + * Check if the current user dismissed the SDK Black Friday notice this year. + * + * The SDK uses one dismissal for the notices of all ThemeIsle products. + * + * @param DateTime $now The current date. + * + * @return bool + */ + public static function is_sdk_bf_notice_dismissed( $now ) { + $dismissed_at = get_user_meta( get_current_user_id(), self::SDK_BF_DISMISS_META, true ); + + return ! empty( $dismissed_at ) && wp_date( 'Y', (int) $dismissed_at ) === $now->format( 'Y' ); + } + + /** + * Dismiss the SDK Black Friday notice for the current user. + * + * Called when the user dismisses the Optimole banner. It also hides the SDK + * notice of the other ThemeIsle products. + * + * @return void + */ + public static function dismiss_sdk_bf_notice() { + /** + * The current date. + * + * @var DateTime $now Current date. + */ + $now = apply_filters( 'themeisle_sdk_current_date', new \DateTime( 'now' ) ); + + update_user_meta( get_current_user_id(), self::SDK_BF_DISMISS_META, $now->getTimestamp() ); + } + /** * Get the black friday notices. * @@ -1705,10 +1739,11 @@ public function get_bf_notices( $user_plan ) { '' . $promo_code . '', '' . __( '25% discount', 'optimole-wp' ) . '' ), - 'cta_link' => esc_url_raw( tsdk_utmify( tsdk_translate_link( self::get_upgrade_base_link() ), 'bfcm25', 'sidebarnotice' ) ), + 'cta_link' => esc_url_raw( tsdk_utmify( tsdk_translate_link( self::get_upgrade_base_link() ), 'bfcm', 'sidebarnotice' ) ), ]; - if ( get_option( self::BF_PROMO_DISMISS_KEY ) === 'yes' ) { + // The banner shares the SDK dismissal, which resets every year. + if ( self::is_sdk_bf_notice_dismissed( $now ) ) { return $notices; } @@ -1718,7 +1753,7 @@ public function get_bf_notices( $user_plan ) { '' . $promo_code . '', '' . __( '25% discount', 'optimole-wp' ) . '' ); - $cta_link = esc_url_raw( tsdk_utmify( self::get_upgrade_base_link(), 'bfcm25', 'notice' ) ); + $cta_link = esc_url_raw( tsdk_utmify( self::get_upgrade_base_link(), 'bfcm', 'notice' ) ); $cta_text = __( 'Claim now', 'optimole-wp' ); $notices['banner'] = [ @@ -1729,7 +1764,7 @@ public function get_bf_notices( $user_plan ) { 'subtitle' => $message, 'cta_text' => $cta_text, 'cta_link' => $cta_link, - 'dismiss_key' => self::BF_PROMO_DISMISS_KEY, + 'dismiss_key' => self::SDK_BF_DISMISS_META, ]; return $notices; diff --git a/inc/rest.php b/inc/rest.php index 9d9239752..50e086529 100644 --- a/inc/rest.php +++ b/inc/rest.php @@ -956,6 +956,12 @@ public function dismiss_notice( WP_REST_Request $request ) { return $this->response( [ 'error' => 'Invalid key' ], 'error' ); } + if ( Optml_Admin::SDK_BF_DISMISS_META === $key ) { + Optml_Admin::dismiss_sdk_bf_notice(); + + return $this->response( [ 'success' => 'Notice dismissed' ] ); + } + $result = update_option( $key, 'yes' ); if ( ! $result ) { diff --git a/tests/test-admin.php b/tests/test-admin.php index 22b5645a2..2843cc609 100644 --- a/tests/test-admin.php +++ b/tests/test-admin.php @@ -65,8 +65,8 @@ public function setUp(): void { $this->sale_end->modify( '+7 days' ); $this->sale_end->setTime( 23, 59, 59 ); - // Clean up options before each test - delete_option( Optml_Admin::BF_PROMO_DISMISS_KEY ); + // Each test starts with an admin that has not dismissed the Black Friday notice. + wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); // Remove any filters that might be set remove_all_filters( 'themeisle_sdk_is_black_friday_sale' ); @@ -77,7 +77,7 @@ public function setUp(): void { * Clean up after each test. */ public function tearDown(): void { - delete_option( Optml_Admin::BF_PROMO_DISMISS_KEY ); + delete_user_meta( get_current_user_id(), Optml_Admin::SDK_BF_DISMISS_META ); remove_all_filters( 'themeisle_sdk_is_black_friday_sale' ); remove_all_filters( 'themeisle_sdk_current_date' ); parent::tearDown(); @@ -188,20 +188,42 @@ public function test_get_bf_notices_banner_dismissal() { $this->mock_date_to( clone $this->black_friday ); // Test banner is hidden when dismissed - update_option( Optml_Admin::BF_PROMO_DISMISS_KEY, 'yes' ); + Optml_Admin::dismiss_sdk_bf_notice(); $result = $this->admin->get_bf_notices( 'free' ); $this->assertIsArray( $result ); $this->assertArrayHasKey( 'sidebar', $result ); $this->assertArrayNotHasKey( 'banner', $result ); // Test banner appears when not dismissed - delete_option( Optml_Admin::BF_PROMO_DISMISS_KEY ); + delete_user_meta( get_current_user_id(), Optml_Admin::SDK_BF_DISMISS_META ); $result = $this->admin->get_bf_notices( 'free' ); $this->assertIsArray( $result ); $this->assertArrayHasKey( 'sidebar', $result ); $this->assertArrayHasKey( 'banner', $result ); } + /** + * Test the dismissal resets every year, the UTM campaign has no year, and the promo code stays BFCM2525. + */ + public function test_get_bf_notices_uses_yearly_dismissal_and_utm() { + $this->setup_black_friday_sale_period(); + + // A dismissal from 2025 does not hide the 2026 banner. + $this->mock_date_to( new DateTime( '2025-11-28 12:00:00' ) ); + Optml_Admin::dismiss_sdk_bf_notice(); + $this->mock_date_to( new DateTime( '2026-11-27 12:00:00' ) ); + $result = $this->admin->get_bf_notices( 'free' ); + delete_user_meta( get_current_user_id(), Optml_Admin::SDK_BF_DISMISS_META ); + + $this->assertArrayHasKey( 'banner', $result ); + $this->assertSame( Optml_Admin::SDK_BF_DISMISS_META, $result['banner']['dismiss_key'] ); + foreach ( [ 'banner', 'sidebar' ] as $notice ) { + parse_str( (string) wp_parse_url( $result[ $notice ]['cta_link'], PHP_URL_QUERY ), $query ); + $this->assertSame( 'bfcm', $query['utm_campaign'] ); + $this->assertStringContainsString( 'BFCM2525', $result[ $notice ]['subtitle'] ); + } + } + /** * Test get_bf_notices contains correct dismiss key in banner. */ @@ -213,7 +235,7 @@ public function test_get_bf_notices_banner_has_correct_dismiss_key() { $this->assertArrayHasKey( 'banner', $result ); $this->assertArrayHasKey( 'dismiss_key', $result['banner'] ); - $this->assertEquals( Optml_Admin::BF_PROMO_DISMISS_KEY, $result['banner']['dismiss_key'] ); + $this->assertEquals( Optml_Admin::SDK_BF_DISMISS_META, $result['banner']['dismiss_key'] ); } /** @@ -296,23 +318,6 @@ public function test_get_bf_notices_date_scenarios() { $this->assertArrayHasKey( 'sidebar', $result ); } - /** - * Test get_bf_notices banner appears with non-'yes' dismissal values. - */ - public function test_get_bf_notices_banner_dismissal_values() { - $this->setup_black_friday_sale_period(); - $this->mock_date_to( clone $this->black_friday ); - - // Banner only hides when dismissal key is exactly 'yes' - $test_values = [ 'no', '0', '', 'dismissed' ]; - - foreach ( $test_values as $value ) { - update_option( Optml_Admin::BF_PROMO_DISMISS_KEY, $value ); - $result = $this->admin->get_bf_notices( 'free' ); - $this->assertArrayHasKey( 'banner', $result, "Banner should appear when dismiss key is '$value'" ); - } - } - // ------------------------------------------------------------------------- // get_permissions_policy() tests // ------------------------------------------------------------------------- @@ -693,4 +698,37 @@ public function mock_offloaded_svg_download( $preempt, array $args, string $url return $preempt; } + + /** + * Test the banner follows the SDK Black Friday dismissal of the current user. + */ + public function test_get_bf_notices_banner_follows_sdk_dismissal() { + $this->setup_black_friday_sale_period(); + $this->mock_date_to( clone $this->black_friday ); + $last_year = ( clone $this->black_friday )->modify( '-1 year' ); + update_user_meta( get_current_user_id(), Optml_Admin::SDK_BF_DISMISS_META, $last_year->getTimestamp() ); + $result = $this->admin->get_bf_notices( 'free' ); + $this->assertArrayHasKey( 'banner', $result ); + + Optml_Admin::dismiss_sdk_bf_notice(); + $this->assertSame( $this->black_friday->getTimestamp(), (int) get_user_meta( get_current_user_id(), Optml_Admin::SDK_BF_DISMISS_META, true ) ); + + $result = $this->admin->get_bf_notices( 'free' ); + $this->assertArrayHasKey( 'sidebar', $result ); + $this->assertArrayNotHasKey( 'banner', $result ); + } + + /** + * Test the REST dismissal of the banner writes the SDK dismissal, not an option. + */ + public function test_rest_dismiss_bf_notice_uses_sdk_dismissal() { + $this->mock_date_to( clone $this->black_friday ); + + $request = new WP_REST_Request( 'POST' ); + $request->set_param( 'key', Optml_Admin::SDK_BF_DISMISS_META ); + ( new Optml_Rest() )->dismiss_notice( $request ); + + $this->assertFalse( get_option( Optml_Admin::SDK_BF_DISMISS_META ) ); + $this->assertTrue( Optml_Admin::is_sdk_bf_notice_dismissed( clone $this->black_friday ) ); + } } From 41e32460133ea125d3740f86019cb3c0d8e7dc45 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 09:37:11 +0000 Subject: [PATCH 06/38] chore(deps): bump codeinwp/themeisle-sdk from 3.3.71 to 3.3.72 Bumps [codeinwp/themeisle-sdk](https://github.com/Codeinwp/themeisle-sdk) from 3.3.71 to 3.3.72. - [Release notes](https://github.com/Codeinwp/themeisle-sdk/releases) - [Commits](https://github.com/Codeinwp/themeisle-sdk/compare/v3.3.71...v3.3.72) --- updated-dependencies: - dependency-name: codeinwp/themeisle-sdk dependency-version: 3.3.72 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- composer.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/composer.lock b/composer.lock index a2c5f22a0..ab51d9ec6 100644 --- a/composer.lock +++ b/composer.lock @@ -64,16 +64,16 @@ }, { "name": "codeinwp/themeisle-sdk", - "version": "3.3.71", + "version": "3.3.72", "source": { "type": "git", "url": "https://github.com/Codeinwp/themeisle-sdk.git", - "reference": "cd7acfc0b01b8d5712736aa3721d689591ced991" + "reference": "66036fa0ef8168f7e5a3f7bf06dc88733e1d46db" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Codeinwp/themeisle-sdk/zipball/cd7acfc0b01b8d5712736aa3721d689591ced991", - "reference": "cd7acfc0b01b8d5712736aa3721d689591ced991", + "url": "https://api.github.com/repos/Codeinwp/themeisle-sdk/zipball/66036fa0ef8168f7e5a3f7bf06dc88733e1d46db", + "reference": "66036fa0ef8168f7e5a3f7bf06dc88733e1d46db", "shasum": "" }, "require-dev": { @@ -99,9 +99,9 @@ ], "support": { "issues": "https://github.com/Codeinwp/themeisle-sdk/issues", - "source": "https://github.com/Codeinwp/themeisle-sdk/tree/v3.3.71" + "source": "https://github.com/Codeinwp/themeisle-sdk/tree/v3.3.72" }, - "time": "2026-11-04T20:22:53+00:00" + "time": "2026-11-06T13:01:52+00:00" }, { "name": "enshrined/svg-sanitize", From 43fb4336da19fd0c45d9f4f2e392cef97873929b Mon Sep 17 00:00:00 2001 From: Marius Cristea Date: Tue, 10 Nov 2026 13:08:44 +0200 Subject: [PATCH 07/38] Encode inline optimizer configuration as JSON (#1233) * fix: encode inline optimizer configuration as JSON * fix: preserve list shape for filtered classes --- inc/admin.php | 17 ++++++++------- tests/test-admin.php | 50 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 8 deletions(-) diff --git a/inc/admin.php b/inc/admin.php index 6775929c0..c519d80e0 100755 --- a/inc/admin.php +++ b/inc/admin.php @@ -565,8 +565,9 @@ public function inline_bootstrap_script() { $lazyload_bg_selectors[] = '.' . $key; } $lazyload_bg_selectors = empty( $lazyload_bg_selectors ) ? '' : sprintf( '%s', implode( ', ', (array) $lazyload_bg_selectors ) ); - $bgclasses = empty( $bgclasses ) ? '' : sprintf( '"%s"', implode( '","', (array) $bgclasses ) ); - $watcher_classes = empty( $watcher_classes ) ? '' : sprintf( '"%s"', implode( '","', (array) $watcher_classes ) ); + $bgclasses = wp_json_encode( array_values( array_map( 'wp_strip_all_tags', (array) $bgclasses ) ) ); + $watcher_classes = wp_json_encode( array_values( array_map( 'wp_strip_all_tags', (array) $watcher_classes ) ) ); + $lazyload_bg_selectors = wp_json_encode( wp_strip_all_tags( $lazyload_bg_selectors ) ); $default_network = ( $this->settings->get( 'network_optimization' ) === 'enabled' ); $limit_dimensions = $this->settings->get( 'limit_dimensions' ) === 'enabled'; $limit_width = $limit_dimensions ? $this->settings->get( 'limit_width' ) : 0; @@ -607,11 +608,11 @@ public function inline_bootstrap_script() { b.appendChild(s); w.optimoleData = { lazyloadOnly: "optimole-lazy-only", - backgroundReplaceClasses: [%s], + backgroundReplaceClasses: %s, nativeLazyload : %s, scalingDisabled: %s, - watchClasses: [%s], - backgroundLazySelectors: "%s", + watchClasses: %s, + backgroundLazySelectors: %s, network_optimizations: %s, ignoreDpr: %s, quality: %d, @@ -623,11 +624,11 @@ public function inline_bootstrap_script() { Optml_Lazyload_Replacer::IFRAME_TEMP_COMMENT, esc_url( $domain ), $min, - wp_strip_all_tags( $bgclasses ), + $bgclasses, $native_lazy_enabled ? 'true' : 'false', $scale_is_disabled ? 'true' : 'false', - wp_strip_all_tags( $watcher_classes ), - addcslashes( wp_strip_all_tags( $lazyload_bg_selectors ), '"' ), + $watcher_classes, + $lazyload_bg_selectors, defined( 'OPTML_NETWORK_ON' ) && constant( 'OPTML_NETWORK_ON' ) ? ( OPTML_NETWORK_ON ? 'true' : 'false' ) : ( $default_network ? 'true' : 'false' ), $retina_ready ? 'true' : 'false', $this->settings->get_numeric_quality(), diff --git a/tests/test-admin.php b/tests/test-admin.php index 2843cc609..c20b2ceef 100644 --- a/tests/test-admin.php +++ b/tests/test-admin.php @@ -507,6 +507,56 @@ public function test_accept_ch_and_policy_are_in_sync() { } } + /** + * Inline bootstrap configuration keeps quoted and escaped values intact. + */ + public function test_inline_bootstrap_script_json_encodes_configuration_values(): void { + $background_class = 'hero\\"banner'; + $watcher_class = 'watch\\"class'; + + $background_class_filter = static function () use ( $background_class ) { + return [ 1 => $background_class ]; + }; + $watcher_class_filter = static function () use ( $watcher_class ) { + return [ 2 => $watcher_class ]; + }; + + add_filter( 'optml_lazyload_bg_classes', $background_class_filter ); + add_filter( 'optml_watcher_lz_classes', $watcher_class_filter ); + + $this->reset_lazyload_bootstrap_configuration(); + try { + $background_selectors = Optml_Lazyload_Replacer::get_background_lazyload_selectors(); + $background_selectors[] = '.' . $background_class; + + ob_start(); + $this->admin->inline_bootstrap_script(); + $output = ob_get_clean(); + + $this->assertStringContainsString( 'backgroundReplaceClasses: ' . wp_json_encode( [ $background_class ] ), $output ); + $this->assertStringContainsString( 'watchClasses: ' . wp_json_encode( [ $watcher_class ] ), $output ); + $this->assertStringContainsString( + 'backgroundLazySelectors: ' . wp_json_encode( implode( ', ', $background_selectors ) ), + $output + ); + } finally { + remove_filter( 'optml_lazyload_bg_classes', $background_class_filter ); + remove_filter( 'optml_watcher_lz_classes', $watcher_class_filter ); + $this->reset_lazyload_bootstrap_configuration(); + } + } + + /** + * Reset cached values used by the inline bootstrap configuration. + */ + private function reset_lazyload_bootstrap_configuration(): void { + foreach ( [ 'lazyload_background_classes', 'lazyload_watcher_classes', 'background_lazyload_selectors' ] as $property_name ) { + $property = new ReflectionProperty( Optml_Lazyload_Replacer::class, $property_name ); + $property->setAccessible( true ); + $property->setValue( null, null ); + } + } + /** * Test get_bf_notices at exact boundary conditions. */ From 0a7451a5073212fd73dffd636e738c4935c26645 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:01:15 +0200 Subject: [PATCH 08/38] chore(deps-dev): bump phpstan/phpstan from 2.3.4 to 2.3.5 (#1234) Bumps [phpstan/phpstan](https://github.com/phpstan/phpstan-phar-composer-source) from 2.3.4 to 2.3.5. - [Commits](https://github.com/phpstan/phpstan-phar-composer-source/commits) --- updated-dependencies: - dependency-name: phpstan/phpstan dependency-version: 2.3.5 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- composer.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.lock b/composer.lock index a2c5f22a0..3fe097f30 100644 --- a/composer.lock +++ b/composer.lock @@ -904,11 +904,11 @@ }, { "name": "phpstan/phpstan", - "version": "2.3.4", + "version": "2.3.5", "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/f20ce6f3c82556cfcfc086b152445a12d1d64fff", - "reference": "f20ce6f3c82556cfcfc086b152445a12d1d64fff", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/645a1bd6bead15fc1b8474137467961d0fa30a79", + "reference": "645a1bd6bead15fc1b8474137467961d0fa30a79", "shasum": "" }, "require": { @@ -964,7 +964,7 @@ "type": "github" } ], - "time": "2026-10-28T22:38:53+00:00" + "time": "2026-11-03T12:14:22+00:00" }, { "name": "phpunit/php-code-coverage", From 0a83994a3f2c35c566a29c28f12f3350730e0461 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Wed, 11 Nov 2026 18:03:23 +0200 Subject: [PATCH 09/38] fix: replace only the background CSS markers printed in the same request The viewport background CSS marker now carries a random token, so the personalized CSS replaces only the pair the plugin printed for this page. --- inc/admin.php | 2 +- inc/manager.php | 7 +- inc/v2/BgOptimizer/Lazyload.php | 27 ++++++- tests/test-viewport-bg-css.php | 136 ++++++++++++++++++++++++++++++++ 4 files changed, 167 insertions(+), 5 deletions(-) create mode 100644 tests/test-viewport-bg-css.php diff --git a/inc/admin.php b/inc/admin.php index c519d80e0..cca5f0989 100755 --- a/inc/admin.php +++ b/inc/admin.php @@ -1009,7 +1009,7 @@ protected function get_background_lazy_css() { } $css = implode( ",\n", $css ) . ' { background-image: none !important; }'; - $css = Lazyload::MARKER . "\n" . strip_tags( $css ) . "\n" . Lazyload::MARKER; + $css = Lazyload::get_marker() . "\n" . strip_tags( $css ) . "\n" . Lazyload::get_marker(); return $css; } diff --git a/inc/manager.php b/inc/manager.php index ea43e0968..71f38dd9d 100644 --- a/inc/manager.php +++ b/inc/manager.php @@ -587,14 +587,15 @@ public function replace_content( $html, $partial = false ) { do_action( 'optml_log', 'viewport_bgselectorsdata: ' . print_r( $personalized_bg_css, true ) ); } - if ( ! empty( $personalized_bg_css ) && ( $start_pos = strpos( $html, Lazyload::MARKER ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found + $marker = Lazyload::get_marker(); + if ( ! empty( $personalized_bg_css ) && ( $start_pos = strpos( $html, $marker ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found // We replace the general bg css with the personalized one. - if ( ( $end_pos = strpos( $html, Lazyload::MARKER, $start_pos + strlen( Lazyload::MARKER ) ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found + if ( ( $end_pos = strpos( $html, $marker, $start_pos + strlen( $marker ) ) ) !== false ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found $html = substr_replace( $html, $personalized_bg_css, $start_pos, - $end_pos + strlen( Lazyload::MARKER ) - $start_pos + $end_pos + strlen( $marker ) - $start_pos ); } } diff --git a/inc/v2/BgOptimizer/Lazyload.php b/inc/v2/BgOptimizer/Lazyload.php index 73edb7fd5..bb50285e1 100644 --- a/inc/v2/BgOptimizer/Lazyload.php +++ b/inc/v2/BgOptimizer/Lazyload.php @@ -12,7 +12,16 @@ * @package OptimoleWP\BgOptimizer */ class Lazyload { - const MARKER = '/* OPTML_VIEWPORT_BG_SELECTORS */'; + /** + * Random bytes in the marker token, printed as twice as many hex characters. + */ + const MARKER_TOKEN_BYTES = 8; + /** + * Marker printed around the general background CSS, created once per PHP process. + * + * @var string|null + */ + private static $marker = null; /** * Shape of a plain selector the frontend getUniqueSelector() reports: ids, tags, classes, ' > ' and :nth-of-type(N). */ @@ -32,6 +41,22 @@ class Lazyload { public static function is_safe_selector( $selector ): bool { return is_string( $selector ) && $selector !== '' && preg_match( self::SAFE_SELECTOR_PATTERN, $selector ) === 1; } + /** + * Get the marker printed before and after the general background CSS. + * + * The personalized CSS replaces everything between two markers. The marker carries a random + * token created once per PHP process, which is one page request under PHP-FPM or Apache, so + * stored page content, such as a visitor comment, cannot contain a matching pair. + * + * @return string The marker, a CSS comment. + */ + public static function get_marker(): string { + if ( null === self::$marker ) { + self::$marker = '/* OPTML_VIEWPORT_BG_SELECTORS ' . bin2hex( random_bytes( self::MARKER_TOKEN_BYTES ) ) . ' */'; + } + + return self::$marker; + } /** * Get the current personalized CSS for lazy loading. * diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php new file mode 100644 index 000000000..6351bf005 --- /dev/null +++ b/tests/test-viewport-bg-css.php @@ -0,0 +1,136 @@ + + */ + private $previous_settings = []; + + public function setUp(): void { + parent::setUp(); + $settings = new Optml_Settings(); + foreach ( [ 'lazyload', 'lazyload_type' ] as $key ) { + $this->previous_settings[ $key ] = $settings->get( $key ); + } + $settings->update( 'service_data', [ + 'cdn_key' => 'test123', + 'cdn_secret' => '12345', + 'whitelist' => [ 'example.com' ], + ] ); + $settings->update( 'lazyload', 'enabled' ); + $settings->update( 'lazyload_type', 'viewport' ); + $this->init_replacers(); + add_filter( 'optml_page_profile_id', [ self::class, 'profile_id' ] ); + + foreach ( [ Profile::DEVICE_TYPE_MOBILE, Profile::DEVICE_TYPE_DESKTOP ] as $device ) { + Optml_Manager::instance()->page_profiler->store( self::PROFILE_ID, $device, [], [ self::WATCHER => [] ] ); + } + } + + public function tearDown(): void { + remove_filter( 'optml_page_profile_id', [ self::class, 'profile_id' ] ); + wp_deregister_style( self::STYLE_HANDLE ); + Profile::reset_current_profile(); + $settings = new Optml_Settings(); + foreach ( $this->previous_settings as $key => $value ) { + $settings->update( $key, $value ); + } + $this->init_replacers(); + parent::tearDown(); + } + + public static function profile_id(): string { + return self::PROFILE_ID; + } + + private function init_replacers(): void { + Optml_Url_Replacer::instance()->init(); + Optml_Tag_Replacer::instance()->init(); + Optml_Lazyload_Replacer::instance()->init(); + Optml_Manager::instance()->init(); + } + + /** + * The inline style the plugin prints in the head, with the general background CSS between its markers. + */ + private function plugin_style(): string { + Optml_Main::instance()->admin->frontend_scripts(); + ob_start(); + wp_styles()->do_item( self::STYLE_HANDLE ); + + return (string) ob_get_clean(); + } + + /** + * Page content, such as a comment, carrying a marker pair inside an attribute. + */ + private function comment(): string { + return 'x'; + } + + private function personalized_rule(): string { + return 'html ' . self::WATCHER . ':not(.optml-bg-lazyloaded) { background-image: none !important; }'; + } + + public function test_marker_carries_a_random_token(): void { + $this->assertMatchesRegularExpression( '/^\/\* OPTML_VIEWPORT_BG_SELECTORS [0-9a-f]{16} \*\/$/', Lazyload::get_marker() ); + $this->assertSame( Lazyload::get_marker(), Lazyload::get_marker(), 'The printed and the replaced marker are the same.' ); + } + + public function test_comment_markers_are_kept_when_the_plugin_prints_none(): void { + // The AMP case: the plugin prints no style, so the comment holds the only marker pair. + $html = 'Post

' . $this->comment() . '

'; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + + $this->assertStringContainsString( $this->comment(), $replaced ); + $this->assertStringNotContainsString( $this->personalized_rule(), $replaced ); + } + + public function test_plugin_markers_are_replaced_and_comment_markers_kept(): void { + $html = '' . $this->plugin_style() . '

' . $this->comment() . '

'; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + + $this->assertStringContainsString( $this->comment(), $replaced ); + $this->assertStringContainsString( $this->personalized_rule(), $replaced ); + $this->assertSame( 2, substr_count( $replaced, 'OPTML_VIEWPORT_BG_SELECTORS' ), 'Only the comment markers are left.' ); + } + + public function test_marker_printed_before_the_plugin_style_is_not_paired_with_it(): void { + // Text another plugin prints in the head, such as a title built from user input. + $title = 'Sale ' . self::STORED_MARKER . ''; + $html = '' . $title . $this->plugin_style() . '

Body.

'; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + + $this->assertStringContainsString( $title, $replaced ); + $this->assertStringContainsString( $this->personalized_rule(), $replaced ); + } +} From afdd9bb171d59a69c2ecf01deb90441b76fee170 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Wed, 11 Nov 2026 19:34:38 +0200 Subject: [PATCH 10/38] fix: give every page placeholder the request token The iframe, preload and optimizer placeholders now carry the same token as the background CSS marker, so copies of their text in page content are not replaced. --- inc/admin.php | 7 +++--- inc/lazyload_replacer.php | 14 ++++++++++-- inc/manager.php | 4 ++-- inc/v2/BgOptimizer/Lazyload.php | 22 ++++-------------- inc/v2/RequestToken.php | 37 +++++++++++++++++++++++++++++++ tests/test-iframe-placeholder.php | 21 +++++++++++++++--- tests/test-viewport-bg-css.php | 28 ++++++++++++++++++----- 7 files changed, 99 insertions(+), 34 deletions(-) create mode 100644 inc/v2/RequestToken.php diff --git a/inc/admin.php b/inc/admin.php index cca5f0989..a1228952e 100755 --- a/inc/admin.php +++ b/inc/admin.php @@ -13,6 +13,7 @@ use enshrined\svgSanitize\Sanitizer; use OptimoleWP\BgOptimizer\Lazyload; use OptimoleWP\PageProfiler\Profile; +use OptimoleWP\RequestToken; /** * Class Optml_Admin */ @@ -621,7 +622,7 @@ public function inline_bootstrap_script() { } }(window, document)); ', - Optml_Lazyload_Replacer::IFRAME_TEMP_COMMENT, + Optml_Lazyload_Replacer::get_iframe_temp_comment(), esc_url( $domain ), $min, $bgclasses, @@ -1065,7 +1066,7 @@ function () { public static function get_optimizer_script( $placeholder = true ) { if ( $placeholder ) { - return ''; + return ''; } return ''; + return ''; } /** * Maybe redirect to dashboard page. diff --git a/inc/lazyload_replacer.php b/inc/lazyload_replacer.php index e9c561d3d..6fcf8ec27 100644 --- a/inc/lazyload_replacer.php +++ b/inc/lazyload_replacer.php @@ -2,6 +2,7 @@ use OptimoleWP\PageProfiler\Profile; use OptimoleWP\Preload\Links; +use OptimoleWP\RequestToken; /** * The class handles the img tag replacements for lazyload. @@ -29,8 +30,6 @@ final class Optml_Lazyload_Replacer extends Optml_App_Replacer { }'; const IFRAME_PLACEHOLDER_STYLE = ''; - const IFRAME_TEMP_COMMENT = '/** optmliframelazyloadplaceholder */'; - const SVG_PLACEHOLDER = 'data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%20#width#%20#height#%22%20width%3D%22#width#%22%20height%3D%22#height#%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Crect%20width%3D%22#width#%22%20height%3D%22#height#%22%20fill%3D%22#fill#%22%2F%3E%3C%2Fsvg%3E'; /** * If frame lazyload is present on page. @@ -38,6 +37,17 @@ final class Optml_Lazyload_Replacer extends Optml_App_Replacer { * @var bool Whether or not at least one iframe has been lazyloaded. */ private static $found_iframe = false; + + /** + * Get the comment printed in the head where the iframe placeholder CSS goes. + * + * It carries the request token, so a copy of its text in the page, such as in a title, is not replaced. + * + * @return string The comment. + */ + public static function get_iframe_temp_comment(): string { + return '/** optmliframelazyloadplaceholder ' . RequestToken::get() . ' */'; + } /** * Cached object instance. * diff --git a/inc/manager.php b/inc/manager.php index 71f38dd9d..6f8931326 100644 --- a/inc/manager.php +++ b/inc/manager.php @@ -516,8 +516,8 @@ private function add_iframe_placeholder_css( string $html ): string { } $head = substr( $html, 0, $head_end[0][1] ); - if ( strpos( $head, Optml_Lazyload_Replacer::IFRAME_TEMP_COMMENT ) !== false ) { - return str_replace( Optml_Lazyload_Replacer::IFRAME_TEMP_COMMENT, Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS, $head ) . substr( $html, $head_end[0][1] ); + if ( strpos( $head, Optml_Lazyload_Replacer::get_iframe_temp_comment() ) !== false ) { + return str_replace( Optml_Lazyload_Replacer::get_iframe_temp_comment(), Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS, $head ) . substr( $html, $head_end[0][1] ); } return preg_replace( '/(.*)<\/head>/ism', ' $1' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '', $html ) ?? $html; diff --git a/inc/v2/BgOptimizer/Lazyload.php b/inc/v2/BgOptimizer/Lazyload.php index bb50285e1..0c57a65e2 100644 --- a/inc/v2/BgOptimizer/Lazyload.php +++ b/inc/v2/BgOptimizer/Lazyload.php @@ -4,6 +4,7 @@ use OptimoleWP\PageProfiler\Profile; use OptimoleWP\Preload\Links; +use OptimoleWP\RequestToken; use Optml_Lazyload_Replacer; /** @@ -12,16 +13,6 @@ * @package OptimoleWP\BgOptimizer */ class Lazyload { - /** - * Random bytes in the marker token, printed as twice as many hex characters. - */ - const MARKER_TOKEN_BYTES = 8; - /** - * Marker printed around the general background CSS, created once per PHP process. - * - * @var string|null - */ - private static $marker = null; /** * Shape of a plain selector the frontend getUniqueSelector() reports: ids, tags, classes, ' > ' and :nth-of-type(N). */ @@ -44,18 +35,13 @@ public static function is_safe_selector( $selector ): bool { /** * Get the marker printed before and after the general background CSS. * - * The personalized CSS replaces everything between two markers. The marker carries a random - * token created once per PHP process, which is one page request under PHP-FPM or Apache, so - * stored page content, such as a visitor comment, cannot contain a matching pair. + * The personalized CSS replaces everything between two markers. The marker carries the request + * token, so page content, such as a comment, cannot contain a matching pair. * * @return string The marker, a CSS comment. */ public static function get_marker(): string { - if ( null === self::$marker ) { - self::$marker = '/* OPTML_VIEWPORT_BG_SELECTORS ' . bin2hex( random_bytes( self::MARKER_TOKEN_BYTES ) ) . ' */'; - } - - return self::$marker; + return '/* OPTML_VIEWPORT_BG_SELECTORS ' . RequestToken::get() . ' */'; } /** * Get the current personalized CSS for lazy loading. diff --git a/inc/v2/RequestToken.php b/inc/v2/RequestToken.php new file mode 100644 index 000000000..1a7f3cb3a --- /dev/null +++ b/inc/v2/RequestToken.php @@ -0,0 +1,37 @@ +hi'; + return 'hi'; } public function test_marker_in_page_content_is_not_expanded(): void { - $html = '' . self::IFRAME . $this->comment_link() . ''; + $html = '' . self::IFRAME . $this->comment_link() . ''; $replaced = Optml_Manager::instance()->replace_content( $html ); @@ -72,6 +77,16 @@ public function test_marker_in_page_content_is_not_expanded(): void { $this->assertStringContainsString( self::PLACEHOLDER_SELECTOR, substr( $replaced, 0, stripos( $replaced, '' ) ) ); } + public function test_marker_in_the_title_is_not_expanded(): void { + $title = 'Search ' . self::STORED_MARKER . ''; + $html = '' . $title . '' . self::IFRAME . ''; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + + $this->assertStringContainsString( $title, $replaced ); + $this->assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); + } + public function test_marker_in_partial_content_is_not_expanded(): void { $replaced = Optml_Manager::instance()->replace_content( self::IFRAME . $this->comment_link(), true ); @@ -84,7 +99,7 @@ public function test_placeholder_css_cannot_close_an_attribute(): void { } public function test_marker_is_expanded_when_head_end_tag_is_omitted(): void { - $html = '' . self::IFRAME . $this->comment_link() . ''; + $html = '' . self::IFRAME . $this->comment_link() . ''; $replaced = Optml_Manager::instance()->replace_content( $html ); diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php index 6351bf005..6b6c22a1a 100644 --- a/tests/test-viewport-bg-css.php +++ b/tests/test-viewport-bg-css.php @@ -10,7 +10,7 @@ use OptimoleWP\PageProfiler\Profile; /** - * The personalized background CSS replaces only the marker pair the plugin printed in this request. + * Page placeholders are replaced only where the plugin printed them in this request. */ class Test_Viewport_Bg_Css extends WP_UnitTestCase { @@ -113,14 +113,30 @@ public function test_comment_markers_are_kept_when_the_plugin_prints_none(): voi $this->assertStringNotContainsString( $this->personalized_rule(), $replaced ); } - public function test_plugin_markers_are_replaced_and_comment_markers_kept(): void { - $html = '' . $this->plugin_style() . '

' . $this->comment() . '

'; + public function test_preload_placeholder_text_in_content_is_kept(): void { + $content = ''; + $html = '' . Optml_Admin::get_preload_links_placeholder() . '' . $content . ''; $replaced = Optml_Manager::instance()->replace_content( $html ); - $this->assertStringContainsString( $this->comment(), $replaced ); - $this->assertStringContainsString( $this->personalized_rule(), $replaced ); - $this->assertSame( 2, substr_count( $replaced, 'OPTML_VIEWPORT_BG_SELECTORS' ), 'Only the comment markers are left.' ); + $this->assertStringContainsString( $content, $replaced ); + $this->assertStringNotContainsString( Optml_Admin::get_preload_links_placeholder(), $replaced ); + } + + public function test_optimizer_placeholder_text_in_content_is_kept(): void { + // A page without a stored profile, so the plugin swaps its placeholder for the optimizer script. + $profile_without_data = static function (): string { + return 'bgcss1946-new'; + }; + add_filter( 'optml_page_profile_id', $profile_without_data, 20 ); + $content = ''; + $html = '' . $content . Optml_Admin::get_optimizer_script( true ) . ''; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + remove_filter( 'optml_page_profile_id', $profile_without_data, 20 ); + + $this->assertStringContainsString( $content, $replaced ); + $this->assertSame( 1, substr_count( $replaced, 'optimoleDataOptimizer' ) ); } public function test_marker_printed_before_the_plugin_style_is_not_paired_with_it(): void { From 9bd87bf31dae998d63f652b9b400dc5cc0da8288 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Wed, 11 Nov 2026 19:40:53 +0200 Subject: [PATCH 11/38] fix: add the root class and the debug comment only to the document itself The root html class goes on the first html tag only, and the profile debug comment after the last closing html tag, so copies in page content stay as written. Tests use the plugin's real head output and check the preload link. --- inc/manager.php | 9 +++++--- tests/test-iframe-placeholder.php | 12 ++++++++++- tests/test-viewport-bg-css.php | 36 ++++++++++++++++++++++++++++++- 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/inc/manager.php b/inc/manager.php index 6f8931326..1daa539af 100644 --- a/inc/manager.php +++ b/inc/manager.php @@ -564,8 +564,10 @@ public function replace_content( $html, $partial = false ) { Profile::set_current_profile_id( $profile_id ); $this->page_profiler->set_current_profile_data(); - if ( $should_show_comment ) { - $html = str_replace( '', '' . $this->page_profiler->get_current_profile_html_comment(), $html ); + // The document ends at the last ; earlier copies are page content. + $html_end = $should_show_comment ? strrpos( $html, '' ) : false; + if ( false !== $html_end ) { + $html = substr_replace( $html, '' . $this->page_profiler->get_current_profile_html_comment(), $html_end, strlen( '' ) ); } } if ( ! $partial ) { @@ -660,7 +662,8 @@ public function add_html_class( $content ) { $new_tag = str_replace( 'html ', 'html class="' . $add_classes . '" ', $match[0] ); } - $content = str_replace( $match[0], $new_tag, $content ); + // Only the tag found first is the root; copies later in the page are content. + $content = substr_replace( $content, $new_tag, $match[1], strlen( $match[0] ) ); } } diff --git a/tests/test-iframe-placeholder.php b/tests/test-iframe-placeholder.php index f1c577d1b..e7a62b173 100644 --- a/tests/test-iframe-placeholder.php +++ b/tests/test-iframe-placeholder.php @@ -63,6 +63,16 @@ private function init_replacers(): void { Optml_Manager::instance()->init(); } + /** + * The markup the plugin prints in the head, with its iframe placeholder comment. + */ + private function plugin_head(): string { + ob_start(); + Optml_Main::instance()->admin->inline_bootstrap_script(); + + return (string) ob_get_clean(); + } + private function comment_link(): string { return 'hi'; } @@ -79,7 +89,7 @@ public function test_marker_in_page_content_is_not_expanded(): void { public function test_marker_in_the_title_is_not_expanded(): void { $title = 'Search ' . self::STORED_MARKER . ''; - $html = '' . $title . '' . self::IFRAME . ''; + $html = '' . $title . $this->plugin_head() . '' . self::IFRAME . ''; $replaced = Optml_Manager::instance()->replace_content( $html ); diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php index 6b6c22a1a..47f19bada 100644 --- a/tests/test-viewport-bg-css.php +++ b/tests/test-viewport-bg-css.php @@ -8,6 +8,7 @@ use OptimoleWP\BgOptimizer\Lazyload; use OptimoleWP\PageProfiler\Profile; +use OptimoleWP\Preload\Links; /** * Page placeholders are replaced only where the plugin printed them in this request. @@ -56,6 +57,9 @@ public function setUp(): void { public function tearDown(): void { remove_filter( 'optml_page_profile_id', [ self::class, 'profile_id' ] ); wp_deregister_style( self::STYLE_HANDLE ); + $links = new ReflectionProperty( Links::class, 'links' ); + $links->setAccessible( true ); + $links->setValue( null, [] ); Profile::reset_current_profile(); $settings = new Optml_Settings(); foreach ( $this->previous_settings as $key => $value ) { @@ -114,13 +118,43 @@ public function test_comment_markers_are_kept_when_the_plugin_prints_none(): voi } public function test_preload_placeholder_text_in_content_is_kept(): void { + Links::add_link( [ 'url' => 'https://example.com/hero.jpg', 'priority' => 'high' ] ); $content = ''; $html = '' . Optml_Admin::get_preload_links_placeholder() . '' . $content . ''; $replaced = Optml_Manager::instance()->replace_content( $html ); $this->assertStringContainsString( $content, $replaced ); - $this->assertStringNotContainsString( Optml_Admin::get_preload_links_placeholder(), $replaced ); + $head = substr( $replaced, 0, strpos( $replaced, '' ) ); + $this->assertMatchesRegularExpression( '/'; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + remove_filter( 'optml_additional_html_classes', $add_class ); + + $this->assertMatchesRegularExpression( '/^/', $replaced ); + $this->assertStringContainsString( $content, $replaced ); + } + + public function test_debug_comment_is_added_only_after_the_document(): void { + $_GET['optml_debug'] = 'true'; + $content = ''; + $html = '' . $content . ''; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + unset( $_GET['optml_debug'] ); + + $this->assertStringContainsString( $content, $replaced ); + $this->assertSame( 1, substr_count( $replaced, 'plugin=optimole-wp' ) ); + $this->assertStringContainsString( '(*SKIP)(*FAIL)|/ismU', $content, $matches, PREG_OFFSET_CAPTURE ) === 1 ) { $add_classes = implode( ' ', $additional_html_classes ); foreach ( $matches as $match ) { @@ -662,7 +663,7 @@ public function add_html_class( $content ) { $new_tag = str_replace( 'html ', 'html class="' . $add_classes . '" ', $match[0] ); } - // Only the tag found first is the root; copies later in the page are content. + // Only that tag changes, so copies later in page content stay as written. $content = substr_replace( $content, $new_tag, $match[1], strlen( $match[0] ) ); } } diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php index 47f19bada..47899e35b 100644 --- a/tests/test-viewport-bg-css.php +++ b/tests/test-viewport-bg-css.php @@ -144,6 +144,20 @@ public function test_html_tag_copy_in_content_gets_no_class(): void { $this->assertStringContainsString( $content, $replaced ); } + public function test_html_tag_in_a_conditional_comment_is_not_taken_as_the_root(): void { + $add_class = static function (): array { + return [ 'optml-test' ]; + }; + add_filter( 'optml_additional_html_classes', $add_class ); + $conditional = ''; + $html = $conditional . ''; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + remove_filter( 'optml_additional_html_classes', $add_class ); + + $this->assertStringStartsWith( $conditional . 'comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => $stored, + ] + ); + Optml_Test_Renamer_Stored_Object::$woken = false; + + self::$replacer->replace( $old_url, 'http://om-wp.test/wp-content/uploads/2026/10/object-renamed.jpg' ); + clean_comment_cache( $comment_id ); + + $this->assertFalse( Optml_Test_Renamer_Stored_Object::$woken, 'The stored object must not be created.' ); + $this->assertSame( $stored, get_comment( $comment_id )->comment_content ); + } + + public function test_replace_keeps_values_with_custom_serialized_objects_unchanged(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/custom-photo.jpg'; + // An array with the URL next to an object in the Serializable format, whose payload only its class can read. + $stored = 'a:2:{s:5:"image";s:' . strlen( $old_url ) . ':"' . $old_url . '";s:6:"widget";C:21:"Optml_Test_Not_Loaded":7:{payload}}'; + $comment_id = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => $stored, + ] + ); + + self::$replacer->replace( $old_url, 'http://om-wp.test/wp-content/uploads/2026/10/custom-renamed.jpg' ); + clean_comment_cache( $comment_id ); + + $this->assertSame( $stored, get_comment( $comment_id )->comment_content ); + } + + public function test_replace_updates_serialized_std_class(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/std-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/std-renamed.jpg'; + update_post_meta( self::$post_id, 'optml_test_object', (object) [ 'image' => $old_url ] ); + + self::$replacer->replace( $old_url, $new_url ); + wp_cache_flush(); + + $this->assertEquals( (object) [ 'image' => $new_url ], get_post_meta( self::$post_id, 'optml_test_object', true ) ); + } + + public function test_replace_finishes_on_a_std_class_that_refers_to_itself(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/cycle-photo.jpg'; + $value = (object) [ "\0*\0self" => $old_url ]; + $value->self = $value; + self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => serialize( $value ), + ] + ); + + $count = self::$replacer->replace( $old_url, 'http://om-wp.test/wp-content/uploads/2026/10/cycle-renamed.jpg' ); + + $this->assertGreaterThan( 0, $count ); + } + + public function test_replace_updates_serialized_text_that_looks_like_an_object(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/text-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/text-renamed.jpg'; + update_post_meta( self::$post_id, 'optml_test_notes', [ 'image' => $old_url, 'note' => 'O:4:"Test":0:{}' ] ); + + self::$replacer->replace( $old_url, $new_url ); + wp_cache_flush(); + + $this->assertSame( [ 'image' => $new_url, 'note' => 'O:4:"Test":0:{}' ], get_post_meta( self::$post_id, 'optml_test_notes', true ) ); + } + public function test_replace_updates_size_variants_in_serialized_meta(): void { update_post_meta( self::$post_id, 'optml_test_thumbnail', [ 'image' => 'http://om-wp.test/wp-content/uploads/2026/10/sized-photo-300x200.jpg' ] ); @@ -574,3 +647,26 @@ public function prepare( $query, ...$args ) { return parent::prepare( str_replace( '%i', '%%i', $query ), ...$args ); } } + +/** + * A class whose code runs when a stored value creates it. + */ +class Optml_Test_Renamer_Stored_Object { + /** + * Whether a stored value created an instance. + * + * @var bool + */ + public static $woken = false; + + /** + * URL the stored value carries. + * + * @var string + */ + public $url = ''; + + public function __wakeup() { + self::$woken = true; + } +} 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 14/38] 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 6b3e021763d2a4c43939f3b50886102c604fb8eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Wed, 11 Nov 2026 20:51:47 +0200 Subject: [PATCH 15/38] fix: leave serialized values the renamer cannot read safely as stored Values with references, values that do not unserialize, and Serializable objects stored on their own are no longer rewritten. --- inc/media_rename/attachment_db_renamer.php | 43 +++++++------ tests/media_rename/test-db-renamer.php | 71 ++++++++++++++++++++-- 2 files changed, 86 insertions(+), 28 deletions(-) diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index 13a30e9db..89f116144 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -180,7 +180,7 @@ private function process_column( $table, $column, $primary_keys, $old_url, $new_ // Check for serialized data $has_serialized = $wpdb->get_var( 'SELECT COUNT(' . esc_sql( $this->quote_identifier( $column ) ) . ') FROM ' . esc_sql( $this->quote_identifier( $table ) ) . - ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . " REGEXP '^[aiO]:[1-9]' LIMIT 1" + ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . " REGEXP '^[aisOCE]:[0-9]' LIMIT 1" ); // Process with PHP if serialized data is found @@ -411,20 +411,24 @@ private function php_handle_column( $table, $column, $primary_keys, $old_url, $n private function replace_urls_in_value( $value, $old_url, $new_url ) { // Check if the value is serialized if ( $this->is_serialized( $value ) ) { + // A value with references (r: or R:) can refer to itself, which the URL walk cannot end. + if ( preg_match( '/[;{][rR]:\d+;/', $value ) ) { + return $value; + } + // Any table can hold the URL, including values visitors write, so stored data must not create // objects whose class runs code. $unserialized = @unserialize( $value, [ 'allowed_classes' => [ 'stdClass' ] ] ); - // If unserialize successful, process the data - if ( $unserialized !== false ) { - // Such values are left as stored: an object read without its class could not be written - // back unchanged, and an enum cannot change. - if ( $this->holds_other_objects( $unserialized ) ) { - return $value; - } - $replaced = $this->replace_in_data( $unserialized, $old_url, $new_url ); - return serialize( $replaced ); + // A serialized value is left as stored when it cannot be read, such as one naming an enum that is + // not loaded, or when it holds an object other than stdClass: an object read without its class + // could not be written back unchanged, and an enum cannot change. A raw text replacement would + // break its declared lengths. + if ( false === $unserialized || $this->holds_other_objects( $unserialized ) ) { + return $value; } + + return serialize( $this->replace_in_data( $unserialized, $old_url, $new_url ) ); } return $this->replace_image_urls( $value, $old_url, $new_url ); @@ -537,24 +541,17 @@ function ( $matches ) use ( $new_base, $new_domain, $new_dir, $new_ext ) { /** * Check whether unserialized data holds an object other than stdClass, such as an incomplete object or an enum. * - * @param mixed $data The unserialized data. - * @param array $seen Ids of the stdClass objects already checked, so self-references end. + * @param mixed $data The unserialized data, without references. * * @return bool True when the data holds such an object. */ - private function holds_other_objects( $data, array &$seen = [] ): bool { - if ( is_object( $data ) ) { - if ( ! $data instanceof stdClass ) { - return true; - } - if ( isset( $seen[ spl_object_id( $data ) ] ) ) { - return false; - } - $seen[ spl_object_id( $data ) ] = true; + private function holds_other_objects( $data ): bool { + if ( is_object( $data ) && ! $data instanceof stdClass ) { + return true; } if ( is_array( $data ) || is_object( $data ) ) { foreach ( $data as $value ) { - if ( $this->holds_other_objects( $value, $seen ) ) { + if ( $this->holds_other_objects( $value ) ) { return true; } } @@ -630,6 +627,8 @@ private function is_serialized( $data ) { // Fall through case 'a': case 'O': + case 'C': + case 'E': case 'i': case 'd': return (bool) preg_match( "/^{$token}:[0-9]+:/", $data ); diff --git a/tests/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index a6c544845..aaac24e16 100644 --- a/tests/media_rename/test-db-renamer.php +++ b/tests/media_rename/test-db-renamer.php @@ -491,20 +491,79 @@ public function test_replace_updates_serialized_std_class(): void { $this->assertEquals( (object) [ 'image' => $new_url ], get_post_meta( self::$post_id, 'optml_test_object', true ) ); } - public function test_replace_finishes_on_a_std_class_that_refers_to_itself(): void { - $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/cycle-photo.jpg'; - $value = (object) [ "\0*\0self" => $old_url ]; + public function test_replace_keeps_a_std_class_that_refers_to_itself_unchanged(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/cycle-photo.jpg'; + $value = (object) [ 'image' => $old_url ]; $value->self = $value; + $stored = serialize( $value ); + $comment_id = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => $stored, + ] + ); + + self::$replacer->replace( $old_url, 'http://om-wp.test/wp-content/uploads/2026/10/cycle-renamed.jpg' ); + clean_comment_cache( $comment_id ); + + $this->assertSame( $stored, get_comment( $comment_id )->comment_content ); + } + + public function test_replace_keeps_a_custom_serialized_object_unchanged(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/custom-top-photo.jpg'; + $payload = '{' . $old_url . '}'; + $stored = 'C:21:"Optml_Test_Not_Loaded":' . ( strlen( $payload ) - 2 ) . ':' . $payload; + $comment_id = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => $stored, + ] + ); + + self::$replacer->replace( $old_url, 'http://om-wp.test/wp-content/uploads/2026/10/custom-top-renamed.jpg' ); + clean_comment_cache( $comment_id ); + + $this->assertSame( $stored, get_comment( $comment_id )->comment_content ); + } + + public function test_replace_keeps_a_custom_serialized_object_next_to_other_serialized_rows_unchanged(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/custom-mixed-photo.jpg'; + $payload = '{' . $old_url . '}'; + $stored = 'C:21:"Optml_Test_Not_Loaded":' . ( strlen( $payload ) - 2 ) . ':' . $payload; + // Another row in the column that starts like an array, so the column is read row by row in PHP. self::factory()->comment->create( [ 'comment_post_ID' => self::$post_id, - 'comment_content' => serialize( $value ), + 'comment_content' => serialize( [ 'image' => $old_url ] ), + ] + ); + $comment_id = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => $stored, ] ); - $count = self::$replacer->replace( $old_url, 'http://om-wp.test/wp-content/uploads/2026/10/cycle-renamed.jpg' ); + self::$replacer->replace( $old_url, 'http://om-wp.test/wp-content/uploads/2026/10/custom-mixed-renamed.jpg' ); + clean_comment_cache( $comment_id ); - $this->assertGreaterThan( 0, $count ); + $this->assertSame( $stored, get_comment( $comment_id )->comment_content ); + } + + public function test_replace_keeps_values_with_an_enum_that_is_not_loaded_unchanged(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/enum-photo.jpg'; + $stored = 'a:2:{s:5:"image";s:' . strlen( $old_url ) . ':"' . $old_url . '";s:4:"kind";E:20:"Optml_Test_No_Enum:A";}'; + $comment_id = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => $stored, + ] + ); + + self::$replacer->replace( $old_url, 'http://om-wp.test/wp-content/uploads/2026/10/enum-renamed.jpg' ); + clean_comment_cache( $comment_id ); + + $this->assertSame( $stored, get_comment( $comment_id )->comment_content ); } public function test_replace_updates_serialized_text_that_looks_like_an_object(): void { From a8c1f00577eac2b7cb15e7f2a53bf5f9cab0f366 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Wed, 11 Nov 2026 20:52:56 +0200 Subject: [PATCH 16/38] fix: add the iframe placeholder style at the real head end and the root class to a bare html tag The iframe placeholder comment is matched by its token wherever it is, and without it the style goes before the first outside comments and scripts. The root class is added right after , or inject the placeholder style there. + * Expand the iframe placeholder comment the plugin printed, or add the placeholder style before the head end. * - * Copies of the marker after the head come from page content and are left untouched. - * The head ends at , or at is omitted. + * The comment carries the request token, so copies of its text in page content are not matched. * * @param string $html Page HTML. * * @return string HTML with the iframe placeholder CSS added. */ private function add_iframe_placeholder_css( string $html ): string { - if ( ! preg_match( '/<\/head>|]/i', $html, $head_end, PREG_OFFSET_CAPTURE ) ) { - return $html; + $comment = Optml_Lazyload_Replacer::get_iframe_temp_comment(); + if ( strpos( $html, $comment ) !== false ) { + return str_replace( $comment, Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS, $html ); } - $head = substr( $html, 0, $head_end[0][1] ); - if ( strpos( $head, Optml_Lazyload_Replacer::get_iframe_temp_comment() ) !== false ) { - return str_replace( Optml_Lazyload_Replacer::get_iframe_temp_comment(), Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS, $head ) . substr( $html, $head_end[0][1] ); + // Comments and scripts can hold "" as text, so the first one outside them is taken as the head end. + if ( ! preg_match( '/(?:|)(*SKIP)(*FAIL)|<\/head>/is', $html, $head_end, PREG_OFFSET_CAPTURE ) ) { + return $html; } - return preg_replace( '/(.*)<\/head>/ism', ' $1' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '', $html ) ?? $html; + return substr_replace( $html, Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE, $head_end[0][1], 0 ); } /** @@ -660,7 +660,7 @@ public function add_html_class( $content ) { if ( strpos( $match[0], 'class' ) !== false ) { $new_tag = str_replace( [ 'class="', "class='" ], [ 'class="' . $add_classes, "class='" . $add_classes ], $match[0] ); } else { - $new_tag = str_replace( 'html ', 'html class="' . $add_classes . '" ', $match[0] ); + $new_tag = preg_replace( '/^assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); } + public function test_head_end_text_in_comments_and_scripts_is_not_taken_as_the_head_end(): void { + $script = ''; + $html = '' . self::IFRAME . $script . ''; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + + $this->assertStringContainsString( '' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '', $replaced ); + $this->assertStringContainsString( $script, $replaced ); + $this->assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); + } + + public function test_plugin_comment_after_head_end_text_is_expanded(): void { + $script = ''; + $html = '' . $this->plugin_head() . '' . self::IFRAME . $script . ''; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + + $this->assertStringContainsString( $script, $replaced ); + $this->assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); + } + public function test_marker_in_partial_content_is_not_expanded(): void { $replaced = Optml_Manager::instance()->replace_content( self::IFRAME . $this->comment_link(), true ); diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php index 47899e35b..ea3140999 100644 --- a/tests/test-viewport-bg-css.php +++ b/tests/test-viewport-bg-css.php @@ -158,6 +158,20 @@ public function test_html_tag_in_a_conditional_comment_is_not_taken_as_the_root( $this->assertStringStartsWith( $conditional . ''; + $html = $conditional . ''; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + remove_filter( 'optml_additional_html_classes', $add_class ); + + $this->assertStringStartsWith( $conditional . '" as text, so the first one outside them is taken as the head end. - if ( ! preg_match( '/(?:|)(*SKIP)(*FAIL)|<\/head>/is', $html, $head_end, PREG_OFFSET_CAPTURE ) ) { + // Only the doctype, the html tag and comments come before the head start tag, while head and body + // content, such as scripts and styles, can hold "" as text. + if ( ! preg_match( '/(*SKIP)(*FAIL)|]*)?>/is', $html, $head_start, PREG_OFFSET_CAPTURE ) ) { return $html; } - return substr_replace( $html, Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE, $head_end[0][1], 0 ); + return substr_replace( $html, Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE, $head_start[0][1] + strlen( $head_start[0][0] ), 0 ); } /** @@ -660,7 +661,8 @@ public function add_html_class( $content ) { if ( strpos( $match[0], 'class' ) !== false ) { $new_tag = str_replace( [ 'class="', "class='" ], [ 'class="' . $add_classes, "class='" . $add_classes ], $match[0] ); } else { - $new_tag = preg_replace( '/^assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); } - public function test_head_end_text_in_comments_and_scripts_is_not_taken_as_the_head_end(): void { - $script = ''; - $html = '' . self::IFRAME . $script . ''; + public function test_placeholder_style_is_added_after_the_head_start_tag(): void { + $head = ''; + $html = '' . $head . '' . self::IFRAME . ''; $replaced = Optml_Manager::instance()->replace_content( $html ); - $this->assertStringContainsString( '' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '', $replaced ); - $this->assertStringContainsString( $script, $replaced ); + $this->assertStringContainsString( '' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . $head . '', $replaced ); + $this->assertStringContainsString( '', $replaced ); $this->assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); } + public function test_partial_content_gets_no_placeholder_style(): void { + $replaced = Optml_Manager::instance()->replace_content( self::IFRAME . '', true ); + + $this->assertStringContainsString( '', $replaced ); + $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $replaced ); + } + public function test_plugin_comment_after_head_end_text_is_expanded(): void { $script = ''; $html = '' . $this->plugin_head() . '' . self::IFRAME . $script . ''; @@ -145,6 +152,6 @@ public function test_body_only_marker_is_not_expanded(): void { $replaced = Optml_Manager::instance()->replace_content( $html ); $this->assertStringContainsString( $this->comment_link(), $replaced ); - $this->assertStringContainsString( Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '', $replaced ); + $this->assertStringContainsString( '' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '', $replaced ); } } diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php index ea3140999..51608bf79 100644 --- a/tests/test-viewport-bg-css.php +++ b/tests/test-viewport-bg-css.php @@ -172,6 +172,19 @@ public function test_bare_html_root_after_a_conditional_comment_gets_the_class() $this->assertStringStartsWith( $conditional . '<html class="optml-test', $replaced ); } + public function test_uppercase_html_root_keeps_its_classes(): void { + $add_class = static function (): array { + return [ 'optml-test' ]; + }; + add_filter( 'optml_additional_html_classes', $add_class ); + $html = '<HTML CLASS="theme-dark"><head></head><body></body></HTML>'; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + remove_filter( 'optml_additional_html_classes', $add_class ); + + $this->assertStringStartsWith( '<HTML CLASS="theme-dark">', $replaced ); + } + public function test_debug_comment_is_added_only_after_the_document(): void { $_GET['optml_debug'] = 'true'; $content = '<textarea></html></textarea>'; From eb2d2625a97125d0d1b5d6810789fbd6158d699e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= <b.vytis@gmail.com> Date: Wed, 11 Nov 2026 23:19:15 +0200 Subject: [PATCH 19/38] fix: leave plain text that starts like a serialized string to the text replacement Only the serialized forms the PHP path must protect, arrays, objects, custom serialized objects and enums, now send a column to it. --- inc/media_rename/attachment_db_renamer.php | 2 +- tests/media_rename/test-db-renamer.php | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index 89f116144..58ab80c96 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -180,7 +180,7 @@ private function process_column( $table, $column, $primary_keys, $old_url, $new_ // Check for serialized data $has_serialized = $wpdb->get_var( 'SELECT COUNT(' . esc_sql( $this->quote_identifier( $column ) ) . ') FROM ' . esc_sql( $this->quote_identifier( $table ) ) . - ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . " REGEXP '^[aisOCE]:[0-9]' LIMIT 1" + ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . " REGEXP '^[aiOCE]:[1-9]' LIMIT 1" ); // Process with PHP if serialized data is found diff --git a/tests/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index aaac24e16..efb5e6f90 100644 --- a/tests/media_rename/test-db-renamer.php +++ b/tests/media_rename/test-db-renamer.php @@ -577,6 +577,22 @@ public function test_replace_updates_serialized_text_that_looks_like_an_object() $this->assertSame( [ 'image' => $new_url, 'note' => 'O:4:"Test":0:{}' ], get_post_meta( self::$post_id, 'optml_test_notes', true ) ); } + public function test_replace_updates_text_that_starts_like_a_serialized_string(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/string-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/string-renamed.jpg'; + $comment_id = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => 's:3:"foo"; see "' . $old_url . '";', + ] + ); + + self::$replacer->replace( $old_url, $new_url ); + clean_comment_cache( $comment_id ); + + $this->assertSame( 's:3:"foo"; see "' . $new_url . '";', get_comment( $comment_id )->comment_content ); + } + public function test_replace_updates_size_variants_in_serialized_meta(): void { update_post_meta( self::$post_id, 'optml_test_thumbnail', [ 'image' => 'http://om-wp.test/wp-content/uploads/2026/10/sized-photo-300x200.jpg' ] ); From dcbbcbd7ef26ff2c0f5240dd5b29756845a60a59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= <b.vytis@gmail.com> Date: Wed, 11 Nov 2026 23:30:10 +0200 Subject: [PATCH 20/38] 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 a22e3597a5a6a14c027a23965c78ec41a839574c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= <b.vytis@gmail.com> Date: Wed, 11 Nov 2026 23:30:35 +0200 Subject: [PATCH 21/38] fix: keep the development fallback for the iframe placeholder style The plugin comment carries the request token and is replaced wherever it is. The fallback for pages without it stays as on development. --- inc/manager.php | 10 ++-------- tests/test-iframe-placeholder.php | 20 +------------------- 2 files changed, 3 insertions(+), 27 deletions(-) diff --git a/inc/manager.php b/inc/manager.php index 9ec71db9e..228ac0c83 100644 --- a/inc/manager.php +++ b/inc/manager.php @@ -501,7 +501,7 @@ public function should_send_temporary_cache_header( $sent_headers = null, $do_no } /** - * Expand the iframe placeholder comment the plugin printed, or add the placeholder style after the head start tag. + * Expand the iframe placeholder comment the plugin printed, or add the placeholder style before the head end. * * The comment carries the request token, so copies of its text in page content are not matched. * @@ -515,13 +515,7 @@ private function add_iframe_placeholder_css( string $html ): string { return str_replace( $comment, Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS, $html ); } - // Only the doctype, the html tag and comments come before the head start tag, while head and body - // content, such as scripts and styles, can hold "</head>" as text. - if ( ! preg_match( '/<!--.*?-->(*SKIP)(*FAIL)|<head(?:\s[^>]*)?>/is', $html, $head_start, PREG_OFFSET_CAPTURE ) ) { - return $html; - } - - return substr_replace( $html, Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE, $head_start[0][1] + strlen( $head_start[0][0] ), 0 ); + return preg_replace( '/<head>(.*)<\/head>/ism', '<head> $1' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '</head>', $html ) ?? $html; } /** diff --git a/tests/test-iframe-placeholder.php b/tests/test-iframe-placeholder.php index c2e9a6402..8b4b2ddd1 100644 --- a/tests/test-iframe-placeholder.php +++ b/tests/test-iframe-placeholder.php @@ -97,24 +97,6 @@ public function test_marker_in_the_title_is_not_expanded(): void { $this->assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); } - public function test_placeholder_style_is_added_after_the_head_start_tag(): void { - $head = '<!-- <head> --><style>.label::after { content: "</head>"; }</style><script>var end = "</head>";</script >'; - $html = '<html><head lang="en">' . $head . '</head><body>' . self::IFRAME . '<textarea></head></textarea></body></html>'; - - $replaced = Optml_Manager::instance()->replace_content( $html ); - - $this->assertStringContainsString( '<head lang="en">' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . $head . '</head>', $replaced ); - $this->assertStringContainsString( '<textarea></head></textarea>', $replaced ); - $this->assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); - } - - public function test_partial_content_gets_no_placeholder_style(): void { - $replaced = Optml_Manager::instance()->replace_content( self::IFRAME . '<textarea></head></textarea>', true ); - - $this->assertStringContainsString( '<textarea></head></textarea>', $replaced ); - $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $replaced ); - } - public function test_plugin_comment_after_head_end_text_is_expanded(): void { $script = '<script>var end = "</head>";</script>'; $html = '<html><head><!-- </head> -->' . $this->plugin_head() . '</head><body>' . self::IFRAME . $script . '</body></html>'; @@ -152,6 +134,6 @@ public function test_body_only_marker_is_not_expanded(): void { $replaced = Optml_Manager::instance()->replace_content( $html ); $this->assertStringContainsString( $this->comment_link(), $replaced ); - $this->assertStringContainsString( '<head>' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '<title>', $replaced ); + $this->assertStringContainsString( Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '</head>', $replaced ); } } From d6849fa8963bdb269c88f607c372638f20c731ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= <b.vytis@gmail.com> Date: Wed, 11 Nov 2026 23:41:27 +0200 Subject: [PATCH 22/38] 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 86bfe2d79e23c1b0caaf500f77200c713d9c6fec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= <b.vytis@gmail.com> Date: Thu, 12 Nov 2026 00:10:48 +0200 Subject: [PATCH 23/38] fix: add the iframe placeholder style only where the plugin printed its comment Without the comment the plugin printed no head script, so the iframes do not lazyload. The fallback that added the style before the last </head> is removed. --- inc/manager.php | 12 ++++-------- tests/test-iframe-placeholder.php | 8 ++++---- tests/test-viewport-bg-css.php | 13 ------------- 3 files changed, 8 insertions(+), 25 deletions(-) diff --git a/inc/manager.php b/inc/manager.php index 228ac0c83..8b0c10bb1 100644 --- a/inc/manager.php +++ b/inc/manager.php @@ -501,21 +501,17 @@ public function should_send_temporary_cache_header( $sent_headers = null, $do_no } /** - * Expand the iframe placeholder comment the plugin printed, or add the placeholder style before the head end. + * Expand the iframe placeholder comment the plugin printed. * - * The comment carries the request token, so copies of its text in page content are not matched. + * The comment carries the request token, so copies of its text in page content are not matched. Without the + * comment, the plugin printed no head script either, so the iframes do not lazyload and need no placeholder. * * @param string $html Page HTML. * * @return string HTML with the iframe placeholder CSS added. */ private function add_iframe_placeholder_css( string $html ): string { - $comment = Optml_Lazyload_Replacer::get_iframe_temp_comment(); - if ( strpos( $html, $comment ) !== false ) { - return str_replace( $comment, Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS, $html ); - } - - return preg_replace( '/<head>(.*)<\/head>/ism', '<head> $1' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '</head>', $html ) ?? $html; + return str_replace( Optml_Lazyload_Replacer::get_iframe_temp_comment(), Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS, $html ); } /** diff --git a/tests/test-iframe-placeholder.php b/tests/test-iframe-placeholder.php index 8b4b2ddd1..65eb41a08 100644 --- a/tests/test-iframe-placeholder.php +++ b/tests/test-iframe-placeholder.php @@ -128,12 +128,12 @@ public function test_marker_is_expanded_when_head_end_tag_is_omitted(): void { $this->assertStringContainsString( self::PLACEHOLDER_SELECTOR, substr( $replaced, 0, strpos( $replaced, '<body' ) ) ); } - public function test_body_only_marker_is_not_expanded(): void { - $html = '<html><head><title>t' . self::IFRAME . $this->comment_link() . ''; + public function test_page_without_the_plugin_comment_is_left_unchanged(): void { + $html = 't' . self::IFRAME . $this->comment_link() . ''; $replaced = Optml_Manager::instance()->replace_content( $html ); - $this->assertStringContainsString( $this->comment_link(), $replaced ); - $this->assertStringContainsString( Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '', $replaced ); + $this->assertStringContainsString( $this->comment_link() . '', $replaced ); + $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $replaced ); } } diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php index 51608bf79..ea3140999 100644 --- a/tests/test-viewport-bg-css.php +++ b/tests/test-viewport-bg-css.php @@ -172,19 +172,6 @@ public function test_bare_html_root_after_a_conditional_comment_gets_the_class() $this->assertStringStartsWith( $conditional . ''; - - $replaced = Optml_Manager::instance()->replace_content( $html ); - remove_filter( 'optml_additional_html_classes', $add_class ); - - $this->assertStringStartsWith( '', $replaced ); - } - public function test_debug_comment_is_added_only_after_the_document(): void { $_GET['optml_debug'] = 'true'; $content = ''; 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 24/38] 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 ab3253b604ab84f2c6296ccf52f4f87b6f847934 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 00:20:48 +0200 Subject: [PATCH 25/38] fix: print the iframe placeholder style in the plugin head The style goes into the inline style the plugin prints when video lazyload is on, so no comment is replaced in the page output and no style is added outside the plugin head. --- inc/admin.php | 2 +- inc/lazyload_replacer.php | 11 -------- inc/manager.php | 17 ----------- tests/test-iframe-placeholder.php | 47 ++++++++++--------------------- 4 files changed, 16 insertions(+), 61 deletions(-) diff --git a/inc/admin.php b/inc/admin.php index a1228952e..0641d2599 100755 --- a/inc/admin.php +++ b/inc/admin.php @@ -622,7 +622,7 @@ public function inline_bootstrap_script() { } }(window, document)); ', - Optml_Lazyload_Replacer::get_iframe_temp_comment(), + $this->settings->get( 'video_lazyload' ) === 'enabled' ? Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS : '', esc_url( $domain ), $min, $bgclasses, diff --git a/inc/lazyload_replacer.php b/inc/lazyload_replacer.php index 6fcf8ec27..d9282bddb 100644 --- a/inc/lazyload_replacer.php +++ b/inc/lazyload_replacer.php @@ -2,7 +2,6 @@ use OptimoleWP\PageProfiler\Profile; use OptimoleWP\Preload\Links; -use OptimoleWP\RequestToken; /** * The class handles the img tag replacements for lazyload. @@ -38,16 +37,6 @@ final class Optml_Lazyload_Replacer extends Optml_App_Replacer { */ private static $found_iframe = false; - /** - * Get the comment printed in the head where the iframe placeholder CSS goes. - * - * It carries the request token, so a copy of its text in the page, such as in a title, is not replaced. - * - * @return string The comment. - */ - public static function get_iframe_temp_comment(): string { - return '/** optmliframelazyloadplaceholder ' . RequestToken::get() . ' */'; - } /** * Cached object instance. * diff --git a/inc/manager.php b/inc/manager.php index 8b0c10bb1..b55c2de33 100644 --- a/inc/manager.php +++ b/inc/manager.php @@ -500,20 +500,6 @@ public function should_send_temporary_cache_header( $sent_headers = null, $do_no return apply_filters( 'optml_send_temporary_cache_header', $send ) === true; } - /** - * Expand the iframe placeholder comment the plugin printed. - * - * The comment carries the request token, so copies of its text in page content are not matched. Without the - * comment, the plugin printed no head script either, so the iframes do not lazyload and need no placeholder. - * - * @param string $html Page HTML. - * - * @return string HTML with the iframe placeholder CSS added. - */ - private function add_iframe_placeholder_css( string $html ): string { - return str_replace( Optml_Lazyload_Replacer::get_iframe_temp_comment(), Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS, $html ); - } - /** * Filter raw HTML content for urls. * @@ -569,9 +555,6 @@ public function replace_content( $html, $partial = false ) { if ( $this->settings->get( 'video_lazyload' ) === 'enabled' ) { $html = apply_filters( 'optml_video_replace', $html ); - if ( Optml_Lazyload_Replacer::found_iframe() === true ) { - $html = $this->add_iframe_placeholder_css( $html ); - } } if ( $this->settings->is_lazyload_type_viewport() && ! $partial ) { diff --git a/tests/test-iframe-placeholder.php b/tests/test-iframe-placeholder.php index 65eb41a08..9f24bf6d3 100644 --- a/tests/test-iframe-placeholder.php +++ b/tests/test-iframe-placeholder.php @@ -12,7 +12,7 @@ class Test_Iframe_Placeholder extends WP_UnitTestCase { const PLACEHOLDER_SELECTOR = 'iframe[data-opt-src]:not([data-opt-lazy-loaded])'; /** - * The marker text page content can know: it was fixed before markers carried a token. + * The fixed comment the plugin used to print and replace, which page content can hold. */ const STORED_MARKER = '/** optmliframelazyloadplaceholder */'; @@ -64,7 +64,7 @@ private function init_replacers(): void { } /** - * The markup the plugin prints in the head, with its iframe placeholder comment. + * The markup the plugin prints in the head. */ private function plugin_head(): string { ob_start(); @@ -77,34 +77,36 @@ private function comment_link(): string { return 'hi'; } - public function test_marker_in_page_content_is_not_expanded(): void { - $html = '' . self::IFRAME . $this->comment_link() . ''; + public function test_plugin_head_holds_the_placeholder_style(): void { + $this->assertStringContainsString( self::PLACEHOLDER_SELECTOR, $this->plugin_head() ); + } - $replaced = Optml_Manager::instance()->replace_content( $html ); + public function test_plugin_head_has_no_placeholder_style_without_video_lazyload(): void { + ( new Optml_Settings() )->update( 'video_lazyload', 'disabled' ); - $this->assertStringContainsString( $this->comment_link(), $replaced ); - $this->assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); - $this->assertStringContainsString( self::PLACEHOLDER_SELECTOR, substr( $replaced, 0, stripos( $replaced, '' ) ) ); + $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $this->plugin_head() ); } - public function test_marker_in_the_title_is_not_expanded(): void { + public function test_marker_text_in_the_page_is_kept(): void { $title = 'Search ' . self::STORED_MARKER . ''; - $html = '' . $title . $this->plugin_head() . '' . self::IFRAME . ''; + $html = '' . $title . $this->plugin_head() . '' . self::IFRAME . $this->comment_link() . ''; $replaced = Optml_Manager::instance()->replace_content( $html ); $this->assertStringContainsString( $title, $replaced ); + $this->assertStringContainsString( $this->comment_link(), $replaced ); $this->assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); } - public function test_plugin_comment_after_head_end_text_is_expanded(): void { + public function test_head_end_text_in_the_page_is_kept(): void { $script = ''; - $html = '' . $this->plugin_head() . '' . self::IFRAME . $script . ''; + $html = '' . self::IFRAME . $script . ''; $replaced = Optml_Manager::instance()->replace_content( $html ); + $this->assertStringContainsString( '', $replaced ); $this->assertStringContainsString( $script, $replaced ); - $this->assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); + $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $replaced ); } public function test_marker_in_partial_content_is_not_expanded(): void { @@ -117,23 +119,4 @@ public function test_marker_in_partial_content_is_not_expanded(): void { public function test_placeholder_css_cannot_close_an_attribute(): void { $this->assertDoesNotMatchRegularExpression( '/["\'<>&]/', Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS ); } - - public function test_marker_is_expanded_when_head_end_tag_is_omitted(): void { - $html = '' . self::IFRAME . $this->comment_link() . ''; - - $replaced = Optml_Manager::instance()->replace_content( $html ); - - $this->assertStringContainsString( $this->comment_link(), $replaced ); - $this->assertSame( 1, substr_count( $replaced, self::PLACEHOLDER_SELECTOR ) ); - $this->assertStringContainsString( self::PLACEHOLDER_SELECTOR, substr( $replaced, 0, strpos( $replaced, 'comment_link() . ''; - - $replaced = Optml_Manager::instance()->replace_content( $html ); - - $this->assertStringContainsString( $this->comment_link() . '', $replaced ); - $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $replaced ); - } } From 8a5a836ad3e904d0ae612052c655b750b22e36c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 00:20:48 +0200 Subject: [PATCH 26/38] test: drop the plain-text probe test, which passes on the base --- tests/media_rename/test-db-renamer.php | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/tests/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index efb5e6f90..aaac24e16 100644 --- a/tests/media_rename/test-db-renamer.php +++ b/tests/media_rename/test-db-renamer.php @@ -577,22 +577,6 @@ public function test_replace_updates_serialized_text_that_looks_like_an_object() $this->assertSame( [ 'image' => $new_url, 'note' => 'O:4:"Test":0:{}' ], get_post_meta( self::$post_id, 'optml_test_notes', true ) ); } - public function test_replace_updates_text_that_starts_like_a_serialized_string(): void { - $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/string-photo.jpg'; - $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/string-renamed.jpg'; - $comment_id = self::factory()->comment->create( - [ - 'comment_post_ID' => self::$post_id, - 'comment_content' => 's:3:"foo"; see "' . $old_url . '";', - ] - ); - - self::$replacer->replace( $old_url, $new_url ); - clean_comment_cache( $comment_id ); - - $this->assertSame( 's:3:"foo"; see "' . $new_url . '";', get_comment( $comment_id )->comment_content ); - } - public function test_replace_updates_size_variants_in_serialized_meta(): void { update_post_meta( self::$post_id, 'optml_test_thumbnail', [ 'image' => 'http://om-wp.test/wp-content/uploads/2026/10/sized-photo-300x200.jpg' ] ); From e3c6b700a4bb35341dc1ffce0295a4ee1e4ab39a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 03:18:53 +0200 Subject: [PATCH 27/38] test: drop the iframe flag reset the placeholder tests no longer need --- inc/lazyload_replacer.php | 1 - tests/test-iframe-placeholder.php | 10 +--------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/inc/lazyload_replacer.php b/inc/lazyload_replacer.php index d9282bddb..de740ce49 100644 --- a/inc/lazyload_replacer.php +++ b/inc/lazyload_replacer.php @@ -36,7 +36,6 @@ final class Optml_Lazyload_Replacer extends Optml_App_Replacer { * @var bool Whether or not at least one iframe has been lazyloaded. */ private static $found_iframe = false; - /** * Cached object instance. * diff --git a/tests/test-iframe-placeholder.php b/tests/test-iframe-placeholder.php index 9f24bf6d3..e1e9d3a90 100644 --- a/tests/test-iframe-placeholder.php +++ b/tests/test-iframe-placeholder.php @@ -36,7 +36,6 @@ public function setUp(): void { ] ); $settings->update( 'lazyload', 'enabled' ); $settings->update( 'video_lazyload', 'enabled' ); - $this->reset_found_iframe(); $this->init_replacers(); } @@ -45,17 +44,10 @@ public function tearDown(): void { foreach ( $this->previous_settings as $key => $value ) { $settings->update( $key, $value ); } - $this->reset_found_iframe(); $this->init_replacers(); parent::tearDown(); } - private function reset_found_iframe(): void { - $found_iframe = new ReflectionProperty( Optml_Lazyload_Replacer::class, 'found_iframe' ); - $found_iframe->setAccessible( true ); - $found_iframe->setValue( null, false ); - } - private function init_replacers(): void { Optml_Url_Replacer::instance()->init(); Optml_Tag_Replacer::instance()->init(); @@ -116,7 +108,7 @@ public function test_marker_in_partial_content_is_not_expanded(): void { $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $replaced ); } - public function test_placeholder_css_cannot_close_an_attribute(): void { + public function test_placeholder_css_cannot_close_the_style(): void { $this->assertDoesNotMatchRegularExpression( '/["\'<>&]/', Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS ); } } From 6861701e964c213b89452ee8d80786e0ca45c10a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 09:17:46 +0200 Subject: [PATCH 28/38] fix: rewrite serialized values stored in strings of serialized data --- inc/media_rename/attachment_db_renamer.php | 47 +++++++++++++++++++--- tests/media_rename/test-db-renamer.php | 40 ++++++++++++++++++ 2 files changed, 81 insertions(+), 6 deletions(-) diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index 58ab80c96..1b874f6ba 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -33,6 +33,13 @@ class Optml_Attachment_Db_Renamer { */ private $handle_image_sizes = false; + /** + * How many serialized values nested in strings are rewritten as data. + * + * Each level reads a copy of the string, so the cap bounds memory. + */ + private const MAX_NESTED_DEPTH = 3; + /** * Constructor */ @@ -405,10 +412,11 @@ private function php_handle_column( $table, $column, $primary_keys, $old_url, $n * @param string $value The value to process. * @param string $old_url Old URL. * @param string $new_url New URL. + * @param int $depth How many serialized strings hold this value. * * @return string The processed value */ - private function replace_urls_in_value( $value, $old_url, $new_url ) { + private function replace_urls_in_value( $value, $old_url, $new_url, int $depth = 0 ) { // Check if the value is serialized if ( $this->is_serialized( $value ) ) { // A value with references (r: or R:) can refer to itself, which the URL walk cannot end. @@ -428,7 +436,7 @@ private function replace_urls_in_value( $value, $old_url, $new_url ) { return $value; } - return serialize( $this->replace_in_data( $unserialized, $old_url, $new_url ) ); + return serialize( $this->replace_in_data( $unserialized, $old_url, $new_url, $depth ) ); } return $this->replace_image_urls( $value, $old_url, $new_url ); @@ -566,27 +574,54 @@ private function holds_other_objects( $data ): bool { * @param mixed $data The data to process. * @param string $old_url Old URL. * @param string $new_url New URL. + * @param int $depth How many serialized strings hold this data. * * @return mixed The processed data */ - private function replace_in_data( $data, $old_url, $new_url ) { + private function replace_in_data( $data, $old_url, $new_url, int $depth ) { if ( is_array( $data ) ) { // Process arrays recursively foreach ( $data as $key => $value ) { - $data[ $key ] = $this->replace_in_data( $value, $old_url, $new_url ); + $data[ $key ] = $this->replace_in_data( $value, $old_url, $new_url, $depth ); } } elseif ( is_object( $data ) ) { // Process objects recursively foreach ( $data as $key => $value ) { - $data->$key = $this->replace_in_data( $value, $old_url, $new_url ); + $data->$key = $this->replace_in_data( $value, $old_url, $new_url, $depth ); } } elseif ( is_string( $data ) ) { - $data = $this->replace_image_urls( $data, $old_url, $new_url ); + $data = $this->replace_in_string( $data, $old_url, $new_url, $depth ); } return $data; } + /** + * Replace URLs in a string read from serialized data. + * + * Plugins can store a serialized value in a string of another one. That value is rewritten as data, so its + * declared lengths stay right, but only when it reads back to exactly the same text. Other text that only + * starts like serialized data gets the plain replacement. + * + * @param string $value The string. + * @param string $old_url Old URL. + * @param string $new_url New URL. + * @param int $depth How many serialized strings hold the data this string is in. + * + * @return string The processed string. + */ + private function replace_in_string( string $value, string $old_url, string $new_url, int $depth ): string { + if ( $this->is_serialized( $value ) ) { + $inner = @unserialize( $value, [ 'allowed_classes' => [ 'stdClass' ] ] ); + if ( false !== $inner && serialize( $inner ) === $value ) { + // Past the cap the value is kept as stored, because a text replacement would break its lengths. + return $depth < self::MAX_NESTED_DEPTH ? $this->replace_urls_in_value( $value, $old_url, $new_url, $depth + 1 ) : $value; + } + } + + return $this->replace_image_urls( $value, $old_url, $new_url ); + } + /** * Check if a string is serialized * diff --git a/tests/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index aaac24e16..55e3b61fc 100644 --- a/tests/media_rename/test-db-renamer.php +++ b/tests/media_rename/test-db-renamer.php @@ -577,6 +577,46 @@ public function test_replace_updates_serialized_text_that_looks_like_an_object() $this->assertSame( [ 'image' => $new_url, 'note' => 'O:4:"Test":0:{}' ], get_post_meta( self::$post_id, 'optml_test_notes', true ) ); } + public function test_replace_updates_a_serialized_string_inside_a_serialized_option(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-renamed-photo.jpg'; + update_option( 'optml_test_nested', [ 'data' => serialize( [ 'url' => $old_url ] ) ] ); + + self::$replacer->replace( $old_url, $new_url ); + wp_cache_flush(); + + $this->assertSame( [ 'url' => $new_url ], unserialize( get_option( 'optml_test_nested' )['data'] ) ); + } + + public function test_replace_keeps_serialized_strings_past_the_nesting_cap_as_stored(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/deep-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/deep-renamed-photo.jpg'; + $deepest = serialize( [ 'url' => $old_url ] ); + $value = $deepest; + for ( $level = 0; $level < 3; $level++ ) { + $value = serialize( [ 'data' => $value ] ); + } + update_option( 'optml_test_deep', [ 'data' => $value, 'url' => $old_url ] ); + + self::$replacer->replace( $old_url, $new_url ); + wp_cache_flush(); + + $stored = get_option( 'optml_test_deep' ); + $this->assertSame( $new_url, $stored['url'] ); + $this->assertSame( serialize( [ 'data' => serialize( [ 'data' => $deepest ] ) ] ), unserialize( $stored['data'] )['data'] ); + } + + public function test_replace_updates_nested_text_that_starts_like_a_serialized_string(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/note-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/note-renamed-photo.jpg'; + update_option( 'optml_test_note', [ 'note' => 's:3:"foo"; see "' . $old_url . '";' ] ); + + self::$replacer->replace( $old_url, $new_url ); + wp_cache_flush(); + + $this->assertSame( [ 'note' => 's:3:"foo"; see "' . $new_url . '";' ], get_option( 'optml_test_note' ) ); + } + public function test_replace_updates_size_variants_in_serialized_meta(): void { update_post_meta( self::$post_id, 'optml_test_thumbnail', [ 'image' => 'http://om-wp.test/wp-content/uploads/2026/10/sized-photo-300x200.jpg' ] ); 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 29/38] 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 30/38] 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 42abe22c8343af5e77c5e3f1bd2d1dec75149a68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 09:30:32 +0200 Subject: [PATCH 31/38] test: pin the nesting cap and the class restriction of nested values --- tests/media_rename/test-db-renamer.php | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/tests/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index 55e3b61fc..db65c27fa 100644 --- a/tests/media_rename/test-db-renamer.php +++ b/tests/media_rename/test-db-renamer.php @@ -594,16 +594,33 @@ public function test_replace_keeps_serialized_strings_past_the_nesting_cap_as_st $deepest = serialize( [ 'url' => $old_url ] ); $value = $deepest; for ( $level = 0; $level < 3; $level++ ) { - $value = serialize( [ 'data' => $value ] ); + $value = serialize( [ 'data' => $value, 'url' => $old_url ] ); } update_option( 'optml_test_deep', [ 'data' => $value, 'url' => $old_url ] ); self::$replacer->replace( $old_url, $new_url ); wp_cache_flush(); + // Three nested levels are rewritten, and the fourth stays as stored. $stored = get_option( 'optml_test_deep' ); - $this->assertSame( $new_url, $stored['url'] ); - $this->assertSame( serialize( [ 'data' => serialize( [ 'data' => $deepest ] ) ] ), unserialize( $stored['data'] )['data'] ); + for ( $level = 0; $level < 3; $level++ ) { + $stored = unserialize( $stored['data'] ); + $this->assertSame( $new_url, $stored['url'] ); + } + $this->assertSame( $deepest, $stored['data'] ); + } + + public function test_replace_does_not_create_objects_nested_in_strings(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-object-photo.jpg'; + $object = 'O:' . strlen( Optml_Test_Renamer_Stored_Object::class ) . ':"' . Optml_Test_Renamer_Stored_Object::class . '":1:{s:3:"url";s:' . strlen( $old_url ) . ':"' . $old_url . '";}'; + update_option( 'optml_test_nested_object', [ 'data' => $object, 'url' => $old_url ] ); + Optml_Test_Renamer_Stored_Object::$woken = false; + + self::$replacer->replace( $old_url, 'http://om-wp.test/wp-content/uploads/2026/10/nested-object-renamed.jpg' ); + wp_cache_flush(); + + $this->assertFalse( Optml_Test_Renamer_Stored_Object::$woken, 'The nested object must not be created.' ); + $this->assertSame( $object, get_option( 'optml_test_nested_object' )['data'] ); } public function test_replace_updates_nested_text_that_starts_like_a_serialized_string(): void { 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 32/38] 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 d71c6e8d39503c81a570605793dbdc9a1664cb04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 11:35:36 +0200 Subject: [PATCH 33/38] fix: keep nested values that cannot be read safely, and handle serialized strings in any column --- inc/media_rename/attachment_db_renamer.php | 42 ++++++++++-- tests/media_rename/test-db-renamer.php | 74 +++++++++++++++++++++- 2 files changed, 110 insertions(+), 6 deletions(-) diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index 1b874f6ba..815f04411 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -187,7 +187,7 @@ private function process_column( $table, $column, $primary_keys, $old_url, $new_ // Check for serialized data $has_serialized = $wpdb->get_var( 'SELECT COUNT(' . esc_sql( $this->quote_identifier( $column ) ) . ') FROM ' . esc_sql( $this->quote_identifier( $table ) ) . - ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . " REGEXP '^[aiOCE]:[1-9]' LIMIT 1" + ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . " REGEXP '^[aiOCEs]:[1-9]' LIMIT 1" ); // Process with PHP if serialized data is found @@ -436,6 +436,12 @@ private function replace_urls_in_value( $value, $old_url, $new_url, int $depth = return $value; } + // Plain text can start like a serialized string, such as `s:3:"foo"; see …`, and keeps its text after + // the first value. + if ( is_string( $unserialized ) && ! $this->reads_back( $unserialized, trim( $value ) ) ) { + return $this->replace_image_urls( $value, $old_url, $new_url ); + } + return serialize( $this->replace_in_data( $unserialized, $old_url, $new_url, $depth ) ); } @@ -600,8 +606,9 @@ private function replace_in_data( $data, $old_url, $new_url, int $depth ) { * Replace URLs in a string read from serialized data. * * Plugins can store a serialized value in a string of another one. That value is rewritten as data, so its - * declared lengths stay right, but only when it reads back to exactly the same text. Other text that only - * starts like serialized data gets the plain replacement. + * declared lengths stay right, but only when it reads back to the same text. A serialized value that cannot + * be read safely stays as stored, as at the top level. Other text that only starts like serialized data gets + * the plain replacement. * * @param string $value The string. * @param string $old_url Old URL. @@ -613,7 +620,10 @@ private function replace_in_data( $data, $old_url, $new_url, int $depth ) { private function replace_in_string( string $value, string $old_url, string $new_url, int $depth ): string { if ( $this->is_serialized( $value ) ) { $inner = @unserialize( $value, [ 'allowed_classes' => [ 'stdClass' ] ] ); - if ( false !== $inner && serialize( $inner ) === $value ) { + if ( false === $inner || $this->holds_other_objects( $inner ) ) { + return $value; + } + if ( $this->reads_back( $inner, $value ) ) { // Past the cap the value is kept as stored, because a text replacement would break its lengths. return $depth < self::MAX_NESTED_DEPTH ? $this->replace_urls_in_value( $value, $old_url, $new_url, $depth + 1 ) : $value; } @@ -622,6 +632,30 @@ private function replace_in_string( string $value, string $old_url, string $new_ return $this->replace_image_urls( $value, $old_url, $new_url ); } + /** + * Check whether unserialized data serializes back to the stored text. + * + * PHP 7.0 and earlier wrote floats with 17 digits, such as `d:0.10000000000000001;`, so that precision is + * tried as well. + * + * @param mixed $data The unserialized data. + * @param string $stored The stored text. + * + * @return bool True when the data serializes to the stored text. + */ + private function reads_back( $data, string $stored ): bool { + if ( serialize( $data ) === $stored ) { + return true; + } + + $precision = ini_get( 'serialize_precision' ); + ini_set( 'serialize_precision', '17' ); + $same = serialize( $data ) === $stored; + ini_set( 'serialize_precision', $precision ); + + return $same; + } + /** * Check if a string is serialized * diff --git a/tests/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index db65c27fa..ba7c4eec4 100644 --- a/tests/media_rename/test-db-renamer.php +++ b/tests/media_rename/test-db-renamer.php @@ -626,12 +626,82 @@ public function test_replace_does_not_create_objects_nested_in_strings(): void { public function test_replace_updates_nested_text_that_starts_like_a_serialized_string(): void { $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/note-photo.jpg'; $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/note-renamed-photo.jpg'; - update_option( 'optml_test_note', [ 'note' => 's:3:"foo"; see "' . $old_url . '";' ] ); + update_option( + 'optml_test_note', + [ + 'note' => 's:3:"foo"; see "' . $old_url . '";', + 'data' => serialize( [ 'url' => $old_url ] ), + ] + ); + + self::$replacer->replace( $old_url, $new_url ); + wp_cache_flush(); + + $stored = get_option( 'optml_test_note' ); + $this->assertSame( 's:3:"foo"; see "' . $new_url . '";', $stored['note'] ); + $this->assertSame( [ 'url' => $new_url ], unserialize( $stored['data'] ) ); + } + + public function test_replace_keeps_nested_values_it_cannot_read_safely_as_stored(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-unsafe-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-unsafe-renamed.jpg'; + $url = 's:3:"url";s:' . strlen( $old_url ) . ':"' . $old_url . '";'; + $custom = 'a:2:{' . $url . 's:6:"widget";C:21:"Optml_Test_Not_Loaded":7:{payload}}'; + $enum = 'a:2:{' . $url . 's:4:"kind";E:20:"Optml_Test_No_Enum:A";}'; + update_option( + 'optml_test_nested_unsafe', + [ + 'custom' => $custom, + 'enum' => $enum, + 'url' => $old_url, + ] + ); + + self::$replacer->replace( $old_url, $new_url ); + wp_cache_flush(); + + $this->assertSame( + [ + 'custom' => $custom, + 'enum' => $enum, + 'url' => $new_url, + ], + get_option( 'optml_test_nested_unsafe' ) + ); + } + + public function test_replace_updates_nested_values_with_old_float_precision(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/float-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/float-renamed-photo.jpg'; + update_option( 'optml_test_float', [ 'data' => 'a:2:{s:3:"url";s:' . strlen( $old_url ) . ':"' . $old_url . '";s:5:"ratio";d:0.10000000000000001;}' ] ); self::$replacer->replace( $old_url, $new_url ); wp_cache_flush(); - $this->assertSame( [ 'note' => 's:3:"foo"; see "' . $new_url . '";' ], get_option( 'optml_test_note' ) ); + $this->assertSame( [ 'url' => $new_url, 'ratio' => 0.1 ], unserialize( get_option( 'optml_test_float' )['data'] ) ); + } + + public function test_replace_updates_columns_whose_only_serialized_values_are_strings(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/string-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/string-renamed-photo.jpg'; + $string = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => serialize( 'see ' . $old_url ), + ] + ); + $text = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => 's:3:"foo"; see "' . $old_url . '";', + ] + ); + + self::$replacer->replace( $old_url, $new_url ); + clean_comment_cache( [ $string, $text ] ); + + $this->assertSame( 'see ' . $new_url, unserialize( get_comment( $string )->comment_content ) ); + $this->assertSame( 's:3:"foo"; see "' . $new_url . '";', get_comment( $text )->comment_content ); } public function test_replace_updates_size_variants_in_serialized_meta(): void { 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 34/38] 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 73544e2bee3bf0e737ac50bf1cb8222d58daa491 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 11:53:17 +0200 Subject: [PATCH 35/38] fix: check nested values for references, and keep padded string lengths valid --- inc/media_rename/attachment_db_renamer.php | 36 ++++++++++++++++++++-- tests/media_rename/test-db-renamer.php | 30 +++++++++++++++++- 2 files changed, 62 insertions(+), 4 deletions(-) diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index 815f04411..667500c61 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -419,8 +419,7 @@ private function php_handle_column( $table, $column, $primary_keys, $old_url, $n private function replace_urls_in_value( $value, $old_url, $new_url, int $depth = 0 ) { // Check if the value is serialized if ( $this->is_serialized( $value ) ) { - // A value with references (r: or R:) can refer to itself, which the URL walk cannot end. - if ( preg_match( '/[;{][rR]:\d+;/', $value ) ) { + if ( $this->has_references( $value ) ) { return $value; } @@ -438,7 +437,7 @@ private function replace_urls_in_value( $value, $old_url, $new_url, int $depth = // Plain text can start like a serialized string, such as `s:3:"foo"; see …`, and keeps its text after // the first value. - if ( is_string( $unserialized ) && ! $this->reads_back( $unserialized, trim( $value ) ) ) { + if ( is_string( $unserialized ) && $this->has_text_after_string( trim( $value ) ) ) { return $this->replace_image_urls( $value, $old_url, $new_url ); } @@ -619,6 +618,9 @@ private function replace_in_data( $data, $old_url, $new_url, int $depth ) { */ private function replace_in_string( string $value, string $old_url, string $new_url, int $depth ): string { if ( $this->is_serialized( $value ) ) { + if ( $this->has_references( $value ) ) { + return $value; + } $inner = @unserialize( $value, [ 'allowed_classes' => [ 'stdClass' ] ] ); if ( false === $inner || $this->holds_other_objects( $inner ) ) { return $value; @@ -632,6 +634,34 @@ private function replace_in_string( string $value, string $old_url, string $new_ return $this->replace_image_urls( $value, $old_url, $new_url ); } + /** + * Check whether a serialized value has references (r: or R:). + * + * A reference can point back at its own value, which the URL walk and the object check cannot end. + * + * @param string $value The serialized value. + * + * @return bool True when the value has references. + */ + private function has_references( string $value ): bool { + return (bool) preg_match( '/[;{][rR]:\d+;/', $value ); + } + + /** + * Check whether text follows the first value of a serialized string, which unserialize() ignores. + * + * Lengths can have leading zeros, such as `s:027:"…";`, which serialize() does not write. + * + * @param string $value A serialized string that unserializes. + * + * @return bool True when text follows the string. + */ + private function has_text_after_string( string $value ): bool { + preg_match( '/^s:(\d+):"/', $value, $matches ); + + return strlen( $value ) > strlen( $matches[0] ) + (int) $matches[1] + 2; + } + /** * Check whether unserialized data serializes back to the stored text. * diff --git a/tests/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index ba7c4eec4..c9b15128e 100644 --- a/tests/media_rename/test-db-renamer.php +++ b/tests/media_rename/test-db-renamer.php @@ -670,14 +670,35 @@ public function test_replace_keeps_nested_values_it_cannot_read_safely_as_stored ); } + public function test_replace_keeps_nested_values_with_references_as_stored(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-reference-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-reference-renamed.jpg'; + $inner = 'O:8:"stdClass":2:{s:3:"url";s:' . strlen( $old_url ) . ':"' . $old_url . '";s:4:"self";r:1;}'; + // The escaped string format hides the reference from the check on the outer value. + $escaped = str_replace( ';', '\\3b', $inner ); + $comment_id = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => 'a:2:{s:3:"url";s:' . strlen( $old_url ) . ':"' . $old_url . '";s:4:"data";S:' . strlen( $inner ) . ':"' . $escaped . '";}', + ] + ); + + self::$replacer->replace( $old_url, $new_url ); + clean_comment_cache( $comment_id ); + + $this->assertSame( [ 'url' => $new_url, 'data' => $inner ], unserialize( get_comment( $comment_id )->comment_content ) ); + } + public function test_replace_updates_nested_values_with_old_float_precision(): void { $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/float-photo.jpg'; $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/float-renamed-photo.jpg'; update_option( 'optml_test_float', [ 'data' => 'a:2:{s:3:"url";s:' . strlen( $old_url ) . ':"' . $old_url . '";s:5:"ratio";d:0.10000000000000001;}' ] ); + $precision = ini_get( 'serialize_precision' ); self::$replacer->replace( $old_url, $new_url ); wp_cache_flush(); + $this->assertSame( $precision, ini_get( 'serialize_precision' ) ); $this->assertSame( [ 'url' => $new_url, 'ratio' => 0.1 ], unserialize( get_option( 'optml_test_float' )['data'] ) ); } @@ -696,11 +717,18 @@ public function test_replace_updates_columns_whose_only_serialized_values_are_st 'comment_content' => 's:3:"foo"; see "' . $old_url . '";', ] ); + $padded = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => 's:0' . strlen( $old_url ) . ':"' . $old_url . '";', + ] + ); self::$replacer->replace( $old_url, $new_url ); - clean_comment_cache( [ $string, $text ] ); + clean_comment_cache( [ $string, $text, $padded ] ); $this->assertSame( 'see ' . $new_url, unserialize( get_comment( $string )->comment_content ) ); + $this->assertSame( $new_url, unserialize( get_comment( $padded )->comment_content ) ); $this->assertSame( 's:3:"foo"; see "' . $new_url . '";', get_comment( $text )->comment_content ); } 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 36/38] 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 fa309fb7ec5101b154bcddcc0a2976386ee10932 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vytis=20Bulkevi=C4=8Dius?= Date: Thu, 12 Nov 2026 12:32:15 +0200 Subject: [PATCH 37/38] fix: read padded lengths and both float precisions, and share the read guard --- inc/media_rename/attachment_db_renamer.php | 83 ++++++++++++---------- tests/media_rename/test-db-renamer.php | 54 +++++++++++--- 2 files changed, 91 insertions(+), 46 deletions(-) diff --git a/inc/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index 667500c61..9e69d3351 100644 --- a/inc/media_rename/attachment_db_renamer.php +++ b/inc/media_rename/attachment_db_renamer.php @@ -187,7 +187,7 @@ private function process_column( $table, $column, $primary_keys, $old_url, $new_ // Check for serialized data $has_serialized = $wpdb->get_var( 'SELECT COUNT(' . esc_sql( $this->quote_identifier( $column ) ) . ') FROM ' . esc_sql( $this->quote_identifier( $table ) ) . - ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . " REGEXP '^[aiOCEs]:[1-9]' LIMIT 1" + ' WHERE ' . esc_sql( $this->quote_identifier( $column ) ) . " REGEXP '^[aiOCEs]:[0-9]' LIMIT 1" ); // Process with PHP if serialized data is found @@ -412,26 +412,14 @@ private function php_handle_column( $table, $column, $primary_keys, $old_url, $n * @param string $value The value to process. * @param string $old_url Old URL. * @param string $new_url New URL. - * @param int $depth How many serialized strings hold this value. * * @return string The processed value */ - private function replace_urls_in_value( $value, $old_url, $new_url, int $depth = 0 ) { + private function replace_urls_in_value( $value, $old_url, $new_url ) { // Check if the value is serialized if ( $this->is_serialized( $value ) ) { - if ( $this->has_references( $value ) ) { - return $value; - } - - // Any table can hold the URL, including values visitors write, so stored data must not create - // objects whose class runs code. - $unserialized = @unserialize( $value, [ 'allowed_classes' => [ 'stdClass' ] ] ); - - // A serialized value is left as stored when it cannot be read, such as one naming an enum that is - // not loaded, or when it holds an object other than stdClass: an object read without its class - // could not be written back unchanged, and an enum cannot change. A raw text replacement would - // break its declared lengths. - if ( false === $unserialized || $this->holds_other_objects( $unserialized ) ) { + $unserialized = $this->read_serialized( $value ); + if ( null === $unserialized ) { return $value; } @@ -441,7 +429,7 @@ private function replace_urls_in_value( $value, $old_url, $new_url, int $depth = return $this->replace_image_urls( $value, $old_url, $new_url ); } - return serialize( $this->replace_in_data( $unserialized, $old_url, $new_url, $depth ) ); + return serialize( $this->replace_in_data( $unserialized, $old_url, $new_url, 0 ) ); } return $this->replace_image_urls( $value, $old_url, $new_url ); @@ -618,16 +606,13 @@ private function replace_in_data( $data, $old_url, $new_url, int $depth ) { */ private function replace_in_string( string $value, string $old_url, string $new_url, int $depth ): string { if ( $this->is_serialized( $value ) ) { - if ( $this->has_references( $value ) ) { - return $value; - } - $inner = @unserialize( $value, [ 'allowed_classes' => [ 'stdClass' ] ] ); - if ( false === $inner || $this->holds_other_objects( $inner ) ) { + $inner = $this->read_serialized( $value ); + if ( null === $inner ) { return $value; } if ( $this->reads_back( $inner, $value ) ) { // Past the cap the value is kept as stored, because a text replacement would break its lengths. - return $depth < self::MAX_NESTED_DEPTH ? $this->replace_urls_in_value( $value, $old_url, $new_url, $depth + 1 ) : $value; + return $depth < self::MAX_NESTED_DEPTH ? serialize( $this->replace_in_data( $inner, $old_url, $new_url, $depth + 1 ) ) : $value; } } @@ -635,16 +620,32 @@ private function replace_in_string( string $value, string $old_url, string $new_ } /** - * Check whether a serialized value has references (r: or R:). + * Read a serialized value when the URL walk can rewrite it safely. * - * A reference can point back at its own value, which the URL walk and the object check cannot end. + * The value is left as stored when this returns null: + * - It has references (r: or R:), which can point back at their own value, so the walk cannot end. + * - It cannot be read, such as one naming an enum that is not loaded. + * - It holds an object other than stdClass. Such an object read without its class could not be written back + * unchanged, and an enum cannot change. + * A raw text replacement would break its declared lengths. * * @param string $value The serialized value. * - * @return bool True when the value has references. + * @return mixed|null The data, or null when the value is left as stored. */ - private function has_references( string $value ): bool { - return (bool) preg_match( '/[;{][rR]:\d+;/', $value ); + private function read_serialized( string $value ) { + if ( preg_match( '/[;{][rR]:\d+;/', $value ) ) { + return null; + } + + // Any table can hold the URL, including values visitors write, so stored data must not create objects + // whose class runs code. + $data = @unserialize( $value, [ 'allowed_classes' => [ 'stdClass' ] ] ); + if ( false === $data || $this->holds_other_objects( $data ) ) { + return null; + } + + return $data; } /** @@ -665,8 +666,9 @@ private function has_text_after_string( string $value ): bool { /** * Check whether unserialized data serializes back to the stored text. * - * PHP 7.0 and earlier wrote floats with 17 digits, such as `d:0.10000000000000001;`, so that precision is - * tried as well. + * Floats were written with 17 digits, such as `d:0.10000000000000001;`, by PHP 7.0 and earlier or with that + * setting, and in the shortest form since, so both precisions are tried. Lengths can have leading zeros, + * such as `s:062:"…";`, which serialize() does not write. * * @param mixed $data The unserialized data. * @param string $stored The stored text. @@ -674,16 +676,21 @@ private function has_text_after_string( string $value ): bool { * @return bool True when the data serializes to the stored text. */ private function reads_back( $data, string $stored ): bool { - if ( serialize( $data ) === $stored ) { - return true; - } - + $unpadded = preg_replace( '/(^|[;{}])([saOCE]):0+(?=\d)/', '$1$2:', $stored ); $precision = ini_get( 'serialize_precision' ); - ini_set( 'serialize_precision', '17' ); - $same = serialize( $data ) === $stored; - ini_set( 'serialize_precision', $precision ); - return $same; + try { + foreach ( [ $precision, '17', '-1' ] as $try ) { + ini_set( 'serialize_precision', $try ); + if ( in_array( serialize( $data ), [ $stored, $unpadded ], true ) ) { + return true; + } + } + } finally { + ini_set( 'serialize_precision', $precision ); + } + + return false; } /** diff --git a/tests/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index c9b15128e..c3233b568 100644 --- a/tests/media_rename/test-db-renamer.php +++ b/tests/media_rename/test-db-renamer.php @@ -670,6 +670,51 @@ public function test_replace_keeps_nested_values_it_cannot_read_safely_as_stored ); } + public function test_replace_updates_columns_whose_only_serialized_values_have_padded_lengths(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/padded-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/padded-renamed-photo.jpg'; + $comment_id = self::factory()->comment->create( + [ + 'comment_post_ID' => self::$post_id, + 'comment_content' => 's:0' . strlen( $old_url ) . ':"' . $old_url . '";', + ] + ); + + self::$replacer->replace( $old_url, $new_url ); + clean_comment_cache( $comment_id ); + + $this->assertSame( $new_url, unserialize( get_comment( $comment_id )->comment_content ) ); + } + + public function test_replace_updates_nested_values_with_padded_lengths(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-padded-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-padded-renamed.jpg'; + update_option( 'optml_test_nested_padded', [ 'data' => 'a:1:{s:3:"url";s:0' . strlen( $old_url ) . ':"' . $old_url . '";}' ] ); + + self::$replacer->replace( $old_url, $new_url ); + wp_cache_flush(); + + $this->assertSame( [ 'url' => $new_url ], unserialize( get_option( 'optml_test_nested_padded' )['data'] ) ); + } + + public function test_replace_updates_nested_floats_when_the_site_uses_precision_17(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/precision-photo.jpg'; + $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/precision-renamed-photo.jpg'; + $precision = ini_get( 'serialize_precision' ); + update_option( 'optml_test_precision', [ 'data' => 'a:2:{s:3:"url";s:' . strlen( $old_url ) . ':"' . $old_url . '";s:5:"ratio";d:0.1;}' ] ); + + ini_set( 'serialize_precision', '17' ); + try { + self::$replacer->replace( $old_url, $new_url ); + $this->assertSame( '17', ini_get( 'serialize_precision' ) ); + } finally { + ini_set( 'serialize_precision', $precision ); + } + wp_cache_flush(); + + $this->assertSame( [ 'url' => $new_url, 'ratio' => 0.1 ], unserialize( get_option( 'optml_test_precision' )['data'] ) ); + } + public function test_replace_keeps_nested_values_with_references_as_stored(): void { $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-reference-photo.jpg'; $new_url = 'http://om-wp.test/wp-content/uploads/2026/10/nested-reference-renamed.jpg'; @@ -717,18 +762,11 @@ public function test_replace_updates_columns_whose_only_serialized_values_are_st 'comment_content' => 's:3:"foo"; see "' . $old_url . '";', ] ); - $padded = self::factory()->comment->create( - [ - 'comment_post_ID' => self::$post_id, - 'comment_content' => 's:0' . strlen( $old_url ) . ':"' . $old_url . '";', - ] - ); self::$replacer->replace( $old_url, $new_url ); - clean_comment_cache( [ $string, $text, $padded ] ); + clean_comment_cache( [ $string, $text ] ); $this->assertSame( 'see ' . $new_url, unserialize( get_comment( $string )->comment_content ) ); - $this->assertSame( $new_url, unserialize( get_comment( $padded )->comment_content ) ); $this->assertSame( 's:3:"foo"; see "' . $new_url . '";', get_comment( $text )->comment_content ); } 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 38/38] 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. *