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/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; 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/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..d0b191dbb 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,20 +60,20 @@ "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", - "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", @@ -904,11 +904,11 @@ }, { "name": "phpstan/phpstan", - "version": "2.3.3", + "version": "2.3.5", "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpstan/zipball/4b57dc8ca7456b635d1661845f44bc060b02c6b0", - "reference": "4b57dc8ca7456b635d1661845f44bc060b02c6b0", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/645a1bd6bead15fc1b8474137467961d0fa30a79", + "reference": "645a1bd6bead15fc1b8474137467961d0fa30a79", "shasum": "" }, "require": { @@ -964,7 +964,7 @@ "type": "github" } ], - "time": "2026-10-27T14:06:26+00:00" + "time": "2026-11-03T12:14:22+00:00" }, { "name": "phpunit/php-code-coverage", diff --git a/inc/admin.php b/inc/admin.php index 72fb017ff..0641d2599 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 */ @@ -23,7 +24,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'; @@ -565,8 +566,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 +609,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, @@ -620,14 +622,14 @@ public function inline_bootstrap_script() { } }(window, document)); ', - Optml_Lazyload_Replacer::IFRAME_TEMP_COMMENT, + $this->settings->get( 'video_lazyload' ) === 'enabled' ? Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS : '', 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(), @@ -1008,7 +1010,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; } @@ -1064,7 +1066,7 @@ function () { public static function get_optimizer_script( $placeholder = true ) { if ( $placeholder ) { - return ''; + return ''; } return ''; + return ''; } /** * Maybe redirect to dashboard page. @@ -1646,6 +1648,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 +1741,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 +1755,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 +1766,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/lazyload_replacer.php b/inc/lazyload_replacer.php index e9c561d3d..de740ce49 100644 --- a/inc/lazyload_replacer.php +++ b/inc/lazyload_replacer.php @@ -29,8 +29,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. diff --git a/inc/manager.php b/inc/manager.php index ea43e0968..b55c2de33 100644 --- a/inc/manager.php +++ b/inc/manager.php @@ -500,29 +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 marker printed in , or inject the placeholder style there. - * - * Copies of the marker after the head come from page content and are left untouched. - * The head ends at , or at is omitted. - * - * @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; - } - - $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] ); - } - - return preg_replace( '/(.*)<\/head>/ism', ' $1' . Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '', $html ) ?? $html; - } - /** * Filter raw HTML content for urls. * @@ -564,8 +541,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 last is taken as the document end, so earlier copies in page content stay as written. + $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 ) { @@ -576,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 ) { @@ -587,14 +563,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 ); } } @@ -649,17 +626,20 @@ public function add_html_class( $content ) { return $content; } - if ( preg_match( '//ismU', $content, $matches, PREG_OFFSET_CAPTURE ) === 1 ) { + // The first html tag outside HTML comments, such as IE conditional comments, is taken as the root. + if ( preg_match( '/(*SKIP)(*FAIL)|/ismU', $content, $matches, PREG_OFFSET_CAPTURE ) === 1 ) { $add_classes = implode( ' ', $additional_html_classes ); foreach ( $matches as $match ) { 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] ); + // The class check above is case-sensitive, so an uppercase tag, which can hold CLASS, stays as written. + $new_tag = preg_replace( '/^ */ +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; } } @@ -1626,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/media_rename/attachment_db_renamer.php b/inc/media_rename/attachment_db_renamer.php index 171db9cbe..7811cc787 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 renamed, as keys; null renames every size + * + * @var array|null + */ + private $renamed_size_suffixes = null; + /** * Handle image size variations * @@ -33,11 +40,22 @@ 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 + * + * @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 ) { + public function __construct( $skip_sizes = false, ?array $renamed_size_suffixes = null ) { $this->handle_image_sizes = ! $skip_sizes; + $this->renamed_size_suffixes = null === $renamed_size_suffixes ? null : array_flip( $renamed_size_suffixes ); } /** @@ -114,7 +132,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 +150,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 +197,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 '^[aiOCEs]:[0-9]' LIMIT 1" ); // Process with PHP if serialized data is found @@ -256,9 +283,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 +294,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 +353,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 +369,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 ) . '%' ) ); @@ -412,13 +429,18 @@ 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 ) ) { - $unserialized = @unserialize( $value ); + $unserialized = $this->read_serialized( $value ); + if ( null === $unserialized ) { + return $value; + } - // If unserialize successful, process the data - if ( $unserialized !== false ) { - $replaced = $this->replace_in_data( $unserialized, $old_url, $new_url ); - return serialize( $replaced ); + // 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->has_text_after_string( trim( $value ) ) ) { + return $this->replace_image_urls( $value, $old_url, $new_url ); } + + return serialize( $this->replace_in_data( $unserialized, $old_url, $new_url, 0 ) ); } return $this->replace_image_urls( $value, $old_url, $new_url ); @@ -480,6 +502,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 ( null !== $this->renamed_size_suffixes && ! isset( $this->renamed_size_suffixes[ ltrim( $size_part, '-' ) ] ) ) { + return $matches[0]; + } // Build the new URL with the same size return $new_domain . $new_dir . '/' . $new_base . $size_part . '.' . $new_ext; @@ -506,6 +531,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 ( null !== $this->renamed_size_suffixes && ! isset( $this->renamed_size_suffixes[ ltrim( $size_part, '-' ) ] ) ) { + return $matches[0]; + } // Build the new URL with the same size return str_replace( '/', '\/', $new_domain . $new_dir . '/' . $new_base . $size_part . '.' . $new_ext ); @@ -528,33 +556,160 @@ function ( $matches ) use ( $new_base, $new_domain, $new_dir, $new_ext ) { return $content; } + /** + * Check whether unserialized data holds an object other than stdClass, such as an incomplete object or an enum. + * + * @param mixed $data The unserialized data, without references. + * + * @return bool True when the data holds such an object. + */ + 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 ) ) { + return true; + } + } + } + + return false; + } + /** * Recursively replace URLs in data structure * * @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 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. + * @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 = $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 ? serialize( $this->replace_in_data( $inner, $old_url, $new_url, $depth + 1 ) ) : $value; + } + } + + return $this->replace_image_urls( $value, $old_url, $new_url ); + } + + /** + * Read a serialized value when the URL walk can rewrite it safely. + * + * 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 mixed|null The data, or null when the value is left as stored. + */ + 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; + } + + /** + * 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. + * + * 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. + * + * @return bool True when the data serializes to the stored text. + */ + private function reads_back( $data, string $stored ): bool { + $unpadded = preg_replace( '/(^|[;{}])([saOCE]):0+(?=\d)/', '$1$2:', $stored ); + $precision = ini_get( 'serialize_precision' ); + + 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; + } + /** * Check if a string is serialized * @@ -595,6 +750,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/inc/media_rename/attachment_rename.php b/inc/media_rename/attachment_rename.php index 15cba758d..94d5f2fe5 100644 --- a/inc/media_rename/attachment_rename.php +++ b/inc/media_rename/attachment_rename.php @@ -1,5 +1,7 @@ + */ + private $moved_size_suffixes = []; + /** * Constructor. * @@ -65,6 +74,11 @@ public function rename() { global $wp_filesystem; + // Paths come from attachment metadata, so only files inside the uploads directory are moved. + if ( ! UploadsPath::contains( $file_path ) || ! UploadsPath::contains( $new_file_path ) ) { + return new WP_Error( 'optml_attachment_path_outside_uploads', __( 'Error renaming file.', 'optimole-wp' ) ); + } + // Bail if original file doesn't exist. if ( ! $wp_filesystem->exists( $file_path ) ) { return new WP_Error( 'optml_attachment_file_not_found', __( 'Error renaming file.', 'optimole-wp' ) ); @@ -87,7 +101,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 @@ -100,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->moved_size_suffixes ); $old_url = $this->attachment->get_main_url(); $new_url = $this->get_new_url( $new_unique_filename ); @@ -186,6 +202,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 ); @@ -194,6 +213,11 @@ private function update_attachment_metadata( $new_path ) { $metadata['sizes'][ $size ]['file'] = $new_size_file; $already_moved_paths = array_unique( $already_moved_paths ); } + // 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/inc/media_rename/attachment_replace.php b/inc/media_rename/attachment_replace.php index 31424def3..b79500c80 100644 --- a/inc/media_rename/attachment_replace.php +++ b/inc/media_rename/attachment_replace.php @@ -1,5 +1,7 @@ file['name'] ); @@ -186,7 +193,8 @@ private function remove_all_image_sizes() { global $wp_filesystem; foreach ( $all_image_sizes_paths as $path ) { - if ( file_exists( $path ) ) { + // Paths come from attachment metadata, so only files inside the uploads directory are deleted. + if ( file_exists( $path ) && UploadsPath::contains( $path ) ) { $wp_filesystem->delete( $path ); } } @@ -223,7 +231,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/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/inc/v2/BgOptimizer/Lazyload.php b/inc/v2/BgOptimizer/Lazyload.php index 73edb7fd5..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,7 +13,6 @@ * @package OptimoleWP\BgOptimizer */ class Lazyload { - const MARKER = '/* OPTML_VIEWPORT_BG_SELECTORS */'; /** * Shape of a plain selector the frontend getUniqueSelector() reports: ids, tags, classes, ' > ' and :nth-of-type(N). */ @@ -32,6 +32,17 @@ 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 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 { + return '/* OPTML_VIEWPORT_BG_SELECTORS ' . RequestToken::get() . ' */'; + } /** * Get the current personalized CSS for lazy loading. * diff --git a/inc/v2/Media/UploadsPath.php b/inc/v2/Media/UploadsPath.php new file mode 100644 index 000000000..1e4ba22c3 --- /dev/null +++ b/inc/v2/Media/UploadsPath.php @@ -0,0 +1,43 @@ +', - 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/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 f6c069c30..2f122e116 100644 --- a/tests/media_rename/test-attachment-rename.php +++ b/tests/media_rename/test-attachment-rename.php @@ -1,4 +1,6 @@ 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 ); + } + + /** + * 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' ); + $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 ); + $meta['sizes']['thumbnail']['width'] += $width_change; + 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->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 ); + } + + 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 ); + } + + 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. + * + * 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' ); + 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 ); + } + 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..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 @@ -109,6 +113,131 @@ 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' ); + $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'; + $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 ); + } + + 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 = 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 ); + $result = ( new Optml_Attachment_Replace( + $id, + [ + 'name' => 'replace-outside-main.jpg', + 'type' => 'image/jpeg', + 'tmp_name' => $tmp_file, + ] + ) )->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 ); + 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' ); + $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'; + $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( '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 ); + 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/media_rename/test-db-renamer.php b/tests/media_rename/test-db-renamer.php index 014250d9e..c03fad2e2 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 ); @@ -268,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'; @@ -321,6 +351,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'; @@ -410,6 +459,331 @@ public function test_replace_updates_serialized_user_meta(): void { $this->assertSame( [ 'url' => $new_url ], get_user_meta( $user_id, 'optml_test_avatar', true ) ); } + public function test_replace_keeps_stored_objects_of_other_classes_unchanged(): void { + $old_url = 'http://om-wp.test/wp-content/uploads/2026/10/object-photo.jpg'; + $stored = 'O:' . strlen( Optml_Test_Renamer_Stored_Object::class ) . ':"' . Optml_Test_Renamer_Stored_Object::class . '":1:{s:3:"url";s:' . strlen( $old_url ) . ':"' . $old_url . '";}'; + $comment_id = self::factory()->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_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( [ 'image' => $old_url ] ), + ] + ); + $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-mixed-renamed.jpg' ); + clean_comment_cache( $comment_id ); + + $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 { + $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_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, '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' ); + 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 { + $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 . '";', + '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_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'; + $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'] ) ); + } + + 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 { update_post_meta( self::$post_id, 'optml_test_thumbnail', [ 'image' => 'http://om-wp.test/wp-content/uploads/2026/10/sized-photo-300x200.jpg' ] ); @@ -493,3 +867,72 @@ 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 ); + } +} + +/** + * 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; + } +} 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 @@ +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 // ------------------------------------------------------------------------- @@ -502,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. */ @@ -693,4 +748,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 ) ); + } } 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-iframe-placeholder.php b/tests/test-iframe-placeholder.php index aa0a12eb5..e1e9d3a90 100644 --- a/tests/test-iframe-placeholder.php +++ b/tests/test-iframe-placeholder.php @@ -11,6 +11,11 @@ class Test_Iframe_Placeholder extends WP_UnitTestCase { const PLACEHOLDER_SELECTOR = 'iframe[data-opt-src]:not([data-opt-lazy-loaded])'; + /** + * The fixed comment the plugin used to print and replace, which page content can hold. + */ + const STORED_MARKER = '/** optmliframelazyloadplaceholder */'; + /** * Settings values replaced in setUp, restored in tearDown. * @@ -31,7 +36,6 @@ public function setUp(): void { ] ); $settings->update( 'lazyload', 'enabled' ); $settings->update( 'video_lazyload', 'enabled' ); - $this->reset_found_iframe(); $this->init_replacers(); } @@ -40,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(); @@ -58,47 +55,60 @@ private function init_replacers(): void { Optml_Manager::instance()->init(); } - private function comment_link(): string { - return 'hi'; - } - - public function test_marker_in_page_content_is_not_expanded(): void { - $html = '' . self::IFRAME . $this->comment_link() . ''; - - $replaced = Optml_Manager::instance()->replace_content( $html ); + /** + * The markup the plugin prints in the head. + */ + private function plugin_head(): string { + ob_start(); + Optml_Main::instance()->admin->inline_bootstrap_script(); - $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, '' ) ) ); + return (string) ob_get_clean(); } - public function test_marker_in_partial_content_is_not_expanded(): void { - $replaced = Optml_Manager::instance()->replace_content( self::IFRAME . $this->comment_link(), true ); + private function comment_link(): string { + return 'hi'; + } - $this->assertStringContainsString( $this->comment_link(), $replaced ); - $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $replaced ); + public function test_plugin_head_holds_the_placeholder_style(): void { + $this->assertStringContainsString( self::PLACEHOLDER_SELECTOR, $this->plugin_head() ); } - public function test_placeholder_css_cannot_close_an_attribute(): void { - $this->assertDoesNotMatchRegularExpression( '/["\'<>&]/', Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS ); + public function test_plugin_head_has_no_placeholder_style_without_video_lazyload(): void { + ( new Optml_Settings() )->update( 'video_lazyload', 'disabled' ); + + $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $this->plugin_head() ); } - public function test_marker_is_expanded_when_head_end_tag_is_omitted(): void { - $html = '' . self::IFRAME . $this->comment_link() . ''; + public function test_marker_text_in_the_page_is_kept(): void { + $title = 'Search ' . self::STORED_MARKER . ''; + $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 ) ); - $this->assertStringContainsString( self::PLACEHOLDER_SELECTOR, substr( $replaced, 0, strpos( $replaced, 'comment_link() . ''; + public function test_head_end_text_in_the_page_is_kept(): void { + $script = ''; + $html = '' . self::IFRAME . $script . ''; $replaced = Optml_Manager::instance()->replace_content( $html ); + $this->assertStringContainsString( '', $replaced ); + $this->assertStringContainsString( $script, $replaced ); + $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $replaced ); + } + + public function test_marker_in_partial_content_is_not_expanded(): void { + $replaced = Optml_Manager::instance()->replace_content( self::IFRAME . $this->comment_link(), true ); + $this->assertStringContainsString( $this->comment_link(), $replaced ); - $this->assertStringContainsString( Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_STYLE . '', $replaced ); + $this->assertStringNotContainsString( self::PLACEHOLDER_SELECTOR, $replaced ); + } + + public function test_placeholder_css_cannot_close_the_style(): void { + $this->assertDoesNotMatchRegularExpression( '/["\'<>&]/', Optml_Lazyload_Replacer::IFRAME_PLACEHOLDER_CLASS ); } } diff --git a/tests/test-media.php b/tests/test-media.php index 78d6f37a3..737b68417 100644 --- a/tests/test-media.php +++ b/tests/test-media.php @@ -10,6 +10,8 @@ use WpOrg\Requests\Utility\CaseInsensitiveDictionary; +require_once __DIR__ . '/outside-uploads-files.php'; + /** * Class Test_Generic. */ @@ -18,6 +20,7 @@ class Test_Media extends WP_UnitTestCase {

'; use Optml_Dam_Offload_Utils; + use Optml_Test_Outside_Uploads; public static $files = [ 'sample-test', '1PQ7p', @@ -255,6 +258,63 @@ public function test_upload_during_rollback_stays_local(): void { $this->assertFileExists( get_attached_file( $attachment_id ) ); } + public function test_offload_treats_a_main_file_outside_uploads_as_missing(): void { + Optml_Media_Offload::instance()->rollback_and_update_images( [ self::$sample_attachement ] ); + $outside = 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 ] ); + + $this->assertSame( 'true', get_post_meta( self::$sample_attachement, Optml_Media_Offload::META_KEYS['offload_error'], true ) ); + $this->assertFileExists( $outside, 'A main file outside uploads must not be offloaded and deleted.' ); + unlink( $outside ); + } + + public function test_offload_keeps_size_files_outside_uploads(): void { + Optml_Media_Offload::instance()->rollback_and_update_images( [ self::$sample_attachement ] ); + $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 ] ); + + $this->assertTrue( Optml_Media_Offload::is_uploaded_image( wp_get_attachment_metadata( self::$sample_attachement )['file'] ) ); + $this->assertFileExists( $outside, 'A size file outside uploads must not be deleted.' ); + unlink( $outside ); + } + + public function test_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; @@ -332,7 +392,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] ); diff --git a/tests/test-uploads-path.php b/tests/test-uploads-path.php new file mode 100644 index 000000000..5fa0ce514 --- /dev/null +++ b/tests/test-uploads-path.php @@ -0,0 +1,51 @@ +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_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.' ); + } + $basedir = wp_get_upload_dir()['basedir']; + $sibling = $basedir . '\\private'; + $child = $basedir . '/a\\b'; + wp_mkdir_p( $sibling ); + wp_mkdir_p( $child ); + + $sibling_file = UploadsPath::contains( $basedir . '/../' . basename( $sibling ) . '/victim.jpg' ); + $child_file = UploadsPath::contains( $child . '/photo.jpg' ); + rmdir( $sibling ); + rmdir( $child ); + + $this->assertFalse( $sibling_file ); + $this->assertTrue( $child_file ); + } + + 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' ) ); + } +} 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)' ] ) + ); + } } diff --git a/tests/test-viewport-bg-css.php b/tests/test-viewport-bg-css.php new file mode 100644 index 000000000..ea3140999 --- /dev/null +++ b/tests/test-viewport-bg-css.php @@ -0,0 +1,214 @@ + + */ + 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 ); + $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 ) { + $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_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 ); + $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_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 . ''; + $html = $conditional . ''; + + $replaced = Optml_Manager::instance()->replace_content( $html ); + remove_filter( 'optml_additional_html_classes', $add_class ); + + $this->assertStringStartsWith( $conditional . '