Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/litespeed-cache/cli/online.cls.php
+++ b/litespeed-cache/cli/online.cls.php
@@ -202,7 +202,8 @@
WP_CLI::success( 'Sync successfully' );
$list = array();
- foreach ( Cloud::$services as $v ) {
+ // Usage v4 only reports optimization units and CDN.
+ foreach ( ! empty( $json['usage.optm'] ) ? [ 'optm', 'cdn' ] : Cloud::$services as $v ) {
$list[] = array(
'key' => $v,
'used' => ! empty( $json['usage.' . $v]['used'] ) ? $json['usage.' . $v]['used'] : 0,
--- a/litespeed-cache/lib/css_js_min/minify/js.cls.php
+++ b/litespeed-cache/lib/css_js_min/minify/js.cls.php
@@ -249,7 +249,7 @@
);
$delimiters = array_fill( 0, count( $propertiesAndMethods ), '/' );
$propertiesAndMethods = array_map( 'preg_quote', $propertiesAndMethods, $delimiters );
- $after = '(?=s*([.,;:)}&|+]|//|$|.(' . implode( '|', $propertiesAndMethods ) . ')))';
+ $after = '(?=s*([.,;:)}]&|+]|//|$|.(' . implode( '|', $propertiesAndMethods ) . ')))';
$this->registerPattern( '/' . $before . 'K' . $pattern . $after . '/', $callback );
// regular expressions following a `)` are rather annoying to detect...
--- a/litespeed-cache/lib/html-min.cls.php
+++ b/litespeed-cache/lib/html-min.cls.php
@@ -136,6 +136,9 @@
}
$this->_html = $html;
+ // Every real tag is tokenized by now, so a `<` followed by whitespace is literal text; encode it so removing whitespace cannot join it to the next word as a tag.
+ $this->_html = preg_replace( '/<(?=s)/', '<', $this->_html );
+
// trim each line.
// @todo take into account attribute values that span multiple lines.
$this->_html = preg_replace( '/^\s+|\s+$/m', '', $this->_html );
@@ -264,7 +267,7 @@
} else {
$js = trim( $js );
}
- if ( false !== stripos( $js, '</script' ) ) {
+ if ( LiteSpeedUtility::script_body_unsafe( $m[3], $js ) ) {
return $this->_reservePlace( $m[0] );
}
--- a/litespeed-cache/litespeed-cache.php
+++ b/litespeed-cache/litespeed-cache.php
@@ -3,7 +3,7 @@
* Plugin Name: LiteSpeed Cache
* Plugin URI: https://www.litespeedtech.com/products/cache-plugins/wordpress-acceleration
* Description: High-performance page caching and site optimization from LiteSpeed
- * Version: 7.9.3
+ * Version: 7.9.4
* Author: LiteSpeed Technologies
* Author URI: https://www.litespeedtech.com
* License: GPLv3
@@ -35,7 +35,7 @@
return;
}
-! defined( 'LSCWP_V' ) && define( 'LSCWP_V', '7.9.3' );
+! defined( 'LSCWP_V' ) && define( 'LSCWP_V', '7.9.4' );
! defined( 'LSCWP_CONTENT_DIR' ) && define( 'LSCWP_CONTENT_DIR', WP_CONTENT_DIR );
! defined( 'LSCWP_DIR' ) && define( 'LSCWP_DIR', __DIR__ . '/' ); // Full absolute path '/var/www/html/***/wp-content/plugins/litespeed-cache/' or MU
--- a/litespeed-cache/src/activation.cls.php
+++ b/litespeed-cache/src/activation.cls.php
@@ -108,6 +108,9 @@
*/
public static function uninstall_litespeed_cache() {
Task::destroy();
+ // Cloud requests persist bookkeeping files and options; remove them with the rest of the installation data.
+ // Limit this best-effort notification to a five-second HTTP timeout so cleanup can proceed promptly.
+ Cloud::version_check( 'uninstall', 5 );
if ( is_multisite() ) {
// Save main site id
@@ -156,8 +159,6 @@
}
self::del_conf_data_file();
-
- Cloud::version_check( 'uninstall' );
}
/**
--- a/litespeed-cache/src/admin-display.cls.php
+++ b/litespeed-cache/src/admin-display.cls.php
@@ -175,7 +175,7 @@
* List of settings with filters and return type.
*
* @since 7.4
- * @deprecated 7.7 Use general conf fitlers.
+ * @deprecated 7.7 Use general conf filters.
*
* @var array<string,array<string,mixed>>
*/
@@ -334,6 +334,13 @@
if ( $screen && in_array( $screen->id, [ 'toplevel_page_litespeed' ], true ) ) {
$classes .= ' litespeed-cache_page_litespeed';
}
+ // Stamp the dark/light override from the admin JS cookie so the first paint uses the right mode.
+ if ( ! empty( $_COOKIE['litespeed-dark-preference'] ) ) {
+ $pref = sanitize_key( wp_unslash( $_COOKIE['litespeed-dark-preference'] ) );
+ if ( 'dark' === $pref || 'light' === $pref ) {
+ $classes .= ' litespeed-' . $pref . 'mode';
+ }
+ }
return $classes;
} );
} );
@@ -868,22 +875,6 @@
}
/**
- * Hooked to the in_widget_form action.
- * Appends LiteSpeed Cache settings to the widget edit settings screen.
- * This will append the esi on/off selector and ttl text.
- *
- * @since 1.1.0
- *
- * @param WP_Widget $widget The widget instance (passed by reference).
- * @param mixed $return_val Return param (unused).
- * @param array $instance The widget instance's settings.
- * @return void
- */
- public function show_widget_edit( $widget, $return_val, $instance ) {
- require LSCWP_DIR . 'tpl/esi_widget_edit.php';
- }
-
- /**
* Outputs a notice when the plugin is installed via WHM.
*
* @since 1.0.12
--- a/litespeed-cache/src/admin.cls.php
+++ b/litespeed-cache/src/admin.cls.php
@@ -83,11 +83,6 @@
$this->cls( 'Media' )->after_admin_init();
do_action( 'litespeed_after_admin_init' );
-
- if ( $this->cls( 'Router' )->esi_enabled() ) {
- add_action( 'in_widget_form', [ $this->cls( 'Admin_Display' ), 'show_widget_edit' ], 100, 3 );
- add_filter( 'widget_update_callback', __NAMESPACE__ . 'Admin_Settings::validate_widget_save', 10, 4 );
- }
}
/**
--- a/litespeed-cache/src/base.cls.php
+++ b/litespeed-cache/src/base.cls.php
@@ -31,7 +31,7 @@
const _VER = '_version'; // Not set-able
const HASH = 'hash'; // Not set-able
const O_AUTO_UPGRADE = 'auto_upgrade';
- const O_API_KEY = 'api_key'; // Deprecated since v6.4. TODO: Will drop after v8 (still need to keep for v7 upgrade conf usage as v6.5.4 has a major user base)
+ const O_API_KEY = 'api_key'; // Deprecated since v6.4; retained until after v8 to protect stored legacy values, no longer used for cloud authentication.
const O_SERVER_IP = 'server_ip';
const O_GUEST = 'guest';
const O_GUEST_OPTM = 'guest_optm';
@@ -156,7 +156,6 @@
const O_OPTM_CCSS_SEP_POSTTYPE = 'optm-ccss_sep_posttype';
const O_OPTM_CCSS_SEP_URI = 'optm-ccss_sep_uri';
const O_OPTM_CCSS_SELECTOR_WHITELIST = 'optm-ccss_whitelist';
- const O_OPTM_CSS_ASYNC_INLINE = 'optm-css_async_inline';
const O_OPTM_CSS_FONT_DISPLAY = 'optm-css_font_display';
const O_OPTM_JS_DEFER = 'optm-js_defer';
const O_OPTM_LOCALIZE = 'optm-localize';
@@ -465,7 +464,6 @@
self::O_OPTM_CCSS_SEP_POSTTYPE => [],
self::O_OPTM_CCSS_SEP_URI => [],
self::O_OPTM_CCSS_SELECTOR_WHITELIST => [],
- self::O_OPTM_CSS_ASYNC_INLINE => false,
self::O_OPTM_CSS_FONT_DISPLAY => false,
self::O_OPTM_JS_DEFER => false,
self::O_OPTM_EMOJI_RM => false,
--- a/litespeed-cache/src/cdn.cls.php
+++ b/litespeed-cache/src/cdn.cls.php
@@ -255,7 +255,7 @@
}
// Check if need preg_replace
- $this->_cfg_url_ori = Utility::wildcard2regex( $this->_cfg_url_ori );
+ $this->_cfg_url_ori = $this->_ori_patterns( $this->_cfg_url_ori );
$this->_cfg_cdn_exclude = $this->conf( Base::O_CDN_EXC );
@@ -281,6 +281,33 @@
}
/**
+ * Turn wildcard Original URLs into regex fragments that cannot leave the URL they match.
+ *
+ * @since 7.9.4
+ * @access private
+ *
+ * @param array $urls Original URLs from settings.
+ * @return array Plain entries unchanged; entries with `*` as regex fragments for a `#` delimiter.
+ */
+ private function _ori_patterns( $urls ) {
+ $patterns = [];
+ foreach ( (array) $urls as $url ) {
+ if ( false === strpos( $url, '*' ) ) {
+ $patterns[] = $url;
+ continue;
+ }
+ // A wildcard in the host stays inside the host; elsewhere it still never matches whitespace, quotes, angle brackets, backslash or backtick.
+ $host_start = strpos( $url, '//' );
+ $host_end = strpos( $url, '/', false === $host_start ? 0 : $host_start + 2 );
+ $host = false === $host_end ? $url : substr( $url, 0, $host_end );
+ $path = false === $host_end ? '' : substr( $url, $host_end );
+ $patterns[] = str_replace( '*', '[^/s"'<>\\`]*', preg_quote( $host, '#' ) ) . str_replace( '*', '[^s"'<>\\`]*', preg_quote( $path, '#' ) );
+ }
+
+ return $patterns;
+ }
+
+ /**
* Associate all filetypes with CDN URL.
*
* @since 2.0
@@ -403,6 +430,10 @@
}
foreach ($matches[$v[0] ? 3 : 2] as $k2 => $url) {
+ // The pattern also matches text and can span tags; only a capture without delimiter bytes is a URL that can be rewritten in place.
+ if ( preg_match( '/[sx00-x1fx7f'"<>\\`]/', $url ) ) {
+ continue;
+ }
// self::debug2( 'check ' . $url );
$postfix = '.' . pathinfo((string) wp_parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
if (!array_key_exists($postfix, $this->_cfg_cdn_mapping)) {
@@ -476,7 +507,7 @@
$is_img = 'img' === strtolower( $token['tag'] );
$src = false;
// Consume every attribute, including non-style quoted values, before advancing; like browsers, whitespace, `/` runs or a just-closed quote separate attributes (`<img/src=x>`, `alt="x"src=y`).
- $attrs = preg_replace_callback( '~G([s/]+|(?<=["']))([^s=/>]+)(s*=s*)("[^"]*"|'[^']*'|[^s>]+)|G(?:[s/]+|(?<=["']))[^s=/>]++(?!s*=)~', function ( $attr ) use ( $is_img, &$src ) {
+ $attrs = preg_replace_callback( Utility::HTML_ATTR_WALK, function ( $attr ) use ( $is_img, &$src ) {
if ( empty( $attr[2] ) ) {
return $attr[0];
}
@@ -485,7 +516,8 @@
return $attr[0];
}
$value = $attr[4];
- $quote = '"' === $value[0] || "'" === $value[0] ? $value[0] : '';
+ // An opening quote without its closing quote is part of an unquoted value.
+ $quote = strlen( $value ) > 1 && ( '"' === $value[0] || "'" === $value[0] ) && substr( $value, -1 ) === $value[0] ? $value[0] : '';
$inner = $quote ? substr( $value, 1, -1 ) : $value;
if ( 'style' === $name ) {
return $attr[1] . $attr[2] . $attr[3] . $quote . $this->_rewrite_css_urls( $inner ) . $quote;
@@ -741,9 +773,10 @@
// Now lets replace CDN url
foreach ( $this->_cfg_url_ori as $v ) {
if ( false !== strpos( $v, '*' ) ) {
- $url = preg_replace_callback( '#' . $scheme . $v . '#iU', static function () use ( $final_url ) {
+ $replaced = preg_replace_callback( '#A' . preg_quote( $scheme, '#' ) . $v . '#iU', static function () use ( $final_url ) {
return $final_url;
- }, $url );
+ }, $url, 1 );
+ $url = null === $replaced ? $url : $replaced;
} else {
$url = str_replace( $scheme . $v, $final_url, $url );
}
@@ -770,7 +803,7 @@
foreach ( $this->_cfg_url_ori as $v ) {
$needle = $scheme . $v;
if ( false !== strpos( $v, '*' ) ) {
- if ( preg_match( '#' . $needle . '#iU', $url ) ) {
+ if ( preg_match( '#A' . preg_quote( $scheme, '#' ) . $v . '#iU', $url ) ) {
return true;
}
} elseif ( 0 === strpos( $url, $needle ) ) {
--- a/litespeed-cache/src/cloud-auth-callback.trait.php
+++ b/litespeed-cache/src/cloud-auth-callback.trait.php
@@ -393,7 +393,7 @@
return $this->_callback_error( self::CALLBACK_ERR_ACTION, 'Callback action does not match its route.' );
}
- $request_key = spl_object_hash( $request ) . ':' . hash( 'sha256', $action );
+ $request_key = spl_object_id( $request ) . ':' . hash( 'sha256', $action );
$fingerprint = hash( 'sha256', $body ) . hash( 'sha256', $content_type ) . hash( 'sha256', $content_encoding ) . hash( 'sha256', $signature_b64 );
if (
isset( $this->_validated_callback_requests[ $request_key ] ) &&
--- a/litespeed-cache/src/cloud-misc.trait.php
+++ b/litespeed-cache/src/cloud-misc.trait.php
@@ -122,10 +122,11 @@
* @since 2.9
* @access public
*
- * @param string|false $src Source.
+ * @param string|false $src Source.
+ * @param int|false $time_out HTTP timeout in seconds, or false for the default.
* @return mixed
*/
- public static function version_check( $src = false ) {
+ public static function version_check( $src = false, $time_out = false ) {
$req_data = [
'v' => defined( 'LSCWP_CUR_V' ) ? LSCWP_CUR_V : '',
'src' => $src,
@@ -139,7 +140,7 @@
$litespeed_err = constant( 'LITESPEED_ERR' );
$req_data['err'] = base64_encode( ! is_string( $litespeed_err ) ? wp_json_encode( $litespeed_err ) : $litespeed_err ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
}
- $data = self::post( self::API_VER, $req_data );
+ $data = self::post( self::API_VER, $req_data, $time_out );
return $data;
}
@@ -232,13 +233,11 @@
public function allowance( $service, &$err = false ) {
$allowance = $this->_cached_allowance( $service, $err );
$last_request = (int) ( $this->_summary[ 'last_request.' . self::SVC_D_USAGE ] ?? 0 );
- $interval = DAY_IN_SECONDS;
if ( ! $allowance ) {
- // Recheck exhausted credit on demand; a failed usage request also starts the hourly interval.
- $interval = HOUR_IN_SECONDS;
+ // Exhausted credit keeps the daily interval; a failed usage request also counts as the last one.
$last_request = max( $last_request, (int) ( $this->_summary[ 'curr_request.' . self::SVC_D_USAGE ] ?? 0 ) );
}
- if ( ! $last_request || time() - $last_request >= $interval ) {
+ if ( ! $last_request || time() - $last_request >= DAY_IN_SECONDS ) {
$this->sync_usage();
$allowance = $this->_cached_allowance( $service, $err );
}
@@ -254,6 +253,28 @@
* @return int
*/
private function _cached_allowance( $service, &$err ) {
+ // Usage v4: every optimization service draws from the shared `optm` units.
+ if ( ! empty( $this->_summary['usage.optm'] ) ) {
+ $usage = $this->_summary['usage.optm'];
+ $left = 0;
+ // `remaining` decides when reported; without it: plan units first, then PAYG balance, then overage. -1 means unlimited.
+ $caps = isset( $usage['remaining'] ) ? [ 'remaining' => '' ] : [ 'quota' => 'used', 'pag_bal' => '', 'overage_cap' => 'overage_used' ];
+ foreach ( $caps as $cap => $spent ) {
+ $left = isset( $usage[ $cap ] ) ? (int) $usage[ $cap ] : 0;
+ if ( -1 === $left ) {
+ $left = PHP_INT_MAX;
+ } elseif ( $spent && isset( $usage[ $spent ] ) ) {
+ $left -= (int) $usage[ $spent ];
+ }
+ if ( $left > 0 ) {
+ // Image optimization sends one group per request; units are not converted into an image count.
+ return self::SVC_IMG_OPTM === $service ? self::IMG_OPTM_DEFAULT_GROUP : $left;
+ }
+ }
+ $err = 'out_of_quota';
+ return 0;
+ }
+
if ( in_array( $service, [ self::SVC_CCSS, self::SVC_UCSS, self::SVC_VPI ], true ) ) {
// @since 4.2
$service = self::SVC_PAGE_OPTM;
@@ -319,6 +340,13 @@
foreach ( self::$services as $v ) {
$this->_summary[ 'usage.' . $v ] = ! empty( $usage[ $v ] ) ? $usage[ $v ] : false;
}
+ // Usage v4 reports only `cdn` and `optm`; a stored `usage.optm` marks that format, and an older response clears it.
+ $this->_summary['usage.optm'] = ! empty( $usage['optm'] ) && is_array( $usage['optm'] ) ? $usage['optm'] : false;
+ $this->_summary['usage.plan'] = ! empty( $usage['plan'] ) && is_string( $usage['plan'] ) ? $usage['plan'] : false;
+ // End of the current billing cycle as a Unix timestamp; empty when there is no reset.
+ $this->_summary['usage.cycle_end'] = ! empty( $usage['cycle_end'] ) && is_numeric( $usage['cycle_end'] ) ? (int) $usage['cycle_end'] : false;
+ // The plan description is text.
+ $this->_summary['usage.plan_desc'] = ! empty( $usage['plan_desc'] ) && is_string( $usage['plan_desc'] ) ? $usage['plan_desc'] : false;
self::save_summary();
--- a/litespeed-cache/src/cloud-request.trait.php
+++ b/litespeed-cache/src/cloud-request.trait.php
@@ -518,6 +518,25 @@
if ( isset( $json['_carry_on'][ $v ] ) ) {
switch ( $v ) {
case 'usage':
+ // Usage v4 carries the same `optm` / `cdn` items as the `d/usage` response.
+ if ( is_array( $json['_carry_on'][ $v ] ) && ! empty( $json['_carry_on'][ $v ]['optm'] ) && is_array( $json['_carry_on'][ $v ]['optm'] ) ) {
+ // The cycle end is a timestamp, or null when there is no reset.
+ if ( array_key_exists( 'cycle_end', $json['_carry_on'][ $v ] ) && ( null === $json['_carry_on'][ $v ]['cycle_end'] || is_numeric( $json['_carry_on'][ $v ]['cycle_end'] ) ) ) {
+ $this->_summary['usage.cycle_end'] = (int) $json['_carry_on'][ $v ]['cycle_end'];
+ }
+ foreach ( [ 'optm', 'cdn', 'plan', 'plan_desc' ] as $k2 ) {
+ $v2 = isset( $json['_carry_on'][ $v ][ $k2 ] ) ? $json['_carry_on'][ $v ][ $k2 ] : null;
+ // Only the items carried are refreshed (an empty one clears it); usage items must be arrays, plan fields strings.
+ if ( 0 === strpos( $k2, 'plan' ) ? is_string( $v2 ) : is_array( $v2 ) ) {
+ // A service response may carry only its own `sub_svc` entry: merge by key so the others stay.
+ if ( 'optm' === $k2 && ! empty( $this->_summary['usage.optm']['sub_svc'] ) && is_array( $this->_summary['usage.optm']['sub_svc'] ) ) {
+ $v2['sub_svc'] = array_merge( $this->_summary['usage.optm']['sub_svc'], ! empty( $v2['sub_svc'] ) && is_array( $v2['sub_svc'] ) ? $v2['sub_svc'] : [] );
+ }
+ $this->_summary[ 'usage.' . $k2 ] = $v2;
+ }
+ }
+ break;
+ }
$usage_svc_tag = in_array( $service, [ self::SVC_CCSS, self::SVC_UCSS, self::SVC_VPI ], true ) ? self::SVC_PAGE_OPTM : $service;
$this->_summary[ 'usage.' . $usage_svc_tag ] = $json['_carry_on'][ $v ];
break;
--- a/litespeed-cache/src/cloud.cls.php
+++ b/litespeed-cache/src/cloud.cls.php
@@ -50,7 +50,6 @@
const SVC_D_LINK = 'd/link';
const SVC_D_API = 'd/api';
const SVC_D_DASH = 'd/dash';
- const SVC_D_V3UPGRADE = 'd/v3upgrade';
const SVC_U_LINK = 'u/wp3/link';
const SVC_U_ENABLE_CDN = 'u/wp3/enablecdn';
const SVC_D_STATUS_CDN_CLI = 'd/status/cdn_cli';
@@ -145,7 +144,6 @@
self::SVC_D_SYNC_CONF,
self::SVC_D_USAGE,
self::SVC_D_API,
- self::SVC_D_V3UPGRADE,
self::SVC_D_DASH,
self::SVC_D_STATUS_CDN_CLI,
// self::API_NEWS,
@@ -168,7 +166,7 @@
*
* @var string[]
*/
- private static $_pub_svc_set = [ self::API_NEWS, self::API_REPORT, self::API_VER, self::API_BETA_TEST, self::API_REST_ECHO, self::SVC_D_V3UPGRADE, self::SVC_D_DASH ];
+ private static $_pub_svc_set = [ self::API_NEWS, self::API_REPORT, self::API_VER, self::API_BETA_TEST, self::API_REST_ECHO, self::SVC_D_DASH ];
/**
* Services that should go through the queue.
--- a/litespeed-cache/src/conf.cls.php
+++ b/litespeed-cache/src/conf.cls.php
@@ -573,8 +573,8 @@
return;
}
- // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
- Debug2::debug( '[Conf] ** ' . $k . ' forced from ' . var_export( $this->conf( $k ), true ) . ' to ' . var_export( $v, true ) );
+ // Option values can contain credentials; log only the overridden key.
+ Debug2::debug( '[Conf] ** ' . $k . ' forced' );
$this->set_conf( $k, $v );
}
--- a/litespeed-cache/src/core.cls.php
+++ b/litespeed-cache/src/core.cls.php
@@ -75,6 +75,10 @@
! defined( 'LSCWP_TS_0' ) && define( 'LSCWP_TS_0', microtime( true ) );
$this->cls( 'Conf' )->init();
+ if ( defined( 'LITESPEED_ON' ) ) {
+ $this->_drop_query_strings();
+ }
+
/**
* Load API hooks
*
@@ -216,8 +220,11 @@
do_action( 'litespeed_initing' );
ob_start( [ $this, 'send_headers_force' ] );
- add_filter( 'litespeed_buffer_after', [ $this, 'drop_query_strings' ], 99 );
add_action( 'shutdown', [ $this, 'send_headers' ], 0 );
+ // CLI: send_headers() runs once and may fire early on an output flush, so purges queued later in the command (e.g. by upgrader hooks) need their own last-moment kick.
+ if ( defined( 'LITESPEED_CLI' ) ) {
+ add_action( 'shutdown', [ __CLASS__, 'kick_cli_purge_queues' ], PHP_INT_MAX );
+ }
add_action( 'wp_footer', [ $this, 'footer_hook' ] );
/**
@@ -583,24 +590,22 @@
}
/**
- * Remove ignored query arguments from quoted current-page URLs in cacheable output.
- * Request input and other URLs are preserved.
+ * Remove Drop Query String arguments from the request before WordPress reads it.
+ *
+ * The server drops them from the cache key, so the page must not be generated from them either, whatever form a component reflects the URL in.
*
- * @since 7.9.2
- * @param string $buffer Final response body.
- * @return string
- */
- public function drop_query_strings( $buffer ) {
- if ( ! defined( 'LITESPEED_ON' ) || ! Control::is_cacheable() || empty( $_SERVER['REQUEST_URI'] ) ||
- // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase -- Existing public hook.
- ( defined( 'DONOTCACHEPAGE' ) && apply_filters( 'litespeed_const_DONOTCACHEPAGE', DONOTCACHEPAGE ) ) ) {
- return $buffer;
- }
- // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Raw URL comparison; only removes arguments.
- $request_uri = wp_unslash( $_SERVER['REQUEST_URI'] );
- $uri = explode( '?', $request_uri, 2 );
+ * @since 7.9.4
+ * @return void
+ */
+ private function _drop_query_strings() {
+ $method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : '';
+ if ( is_admin() || ! in_array( $method, [ 'GET', 'HEAD' ], true ) || empty( $_SERVER['REQUEST_URI'] ) ) {
+ return;
+ }
+ // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Raw URL kept as is; only arguments are removed.
+ $uri = explode( '?', $_SERVER['REQUEST_URI'], 2 );
if ( ! isset( $uri[1] ) || '' === $uri[1] ) {
- return $buffer;
+ return;
}
// Use the same option values as the cache-key rules.
$options = $this->get_options();
@@ -618,7 +623,7 @@
$patterns[] = preg_quote( $prefix ? substr( $rule, 0, -1 ) : $rule, '/' ) . ( $prefix ? '' : '(?:=|&|z)' );
}
if ( ! $patterns ) {
- return $buffer;
+ return;
}
$pattern = '/A(?:' . implode( '|', $patterns ) . ')/';
$parts = preg_split( '/(?<=&)/', $uri[1], -1, PREG_SPLIT_NO_EMPTY );
@@ -626,23 +631,19 @@
foreach ( $parts as $part ) {
if ( ! preg_match( $pattern, $part ) ) {
$kept[] = $part;
+ continue;
}
+ // PHP keys `utm[x]=1` as `utm` and `utm.x` as `utm_x`, so unset the name the way PHP parsed it.
+ $name = strtr( explode( '[', urldecode( explode( '=', rtrim( $part, '&' ), 2 )[0] ), 2 )[0], ' .', '__' );
+ unset( $_GET[ $name ], $_REQUEST[ $name ] );
}
$query = implode( '', $kept );
if ( $query === $uri[1] ) {
- return $buffer;
- }
- $query = '&' === substr( $query, -1 ) ? substr( $query, 0, -1 ) : $query;
- $map = [];
- foreach ( [ get_self_link(), $request_uri ] as $source ) {
- $target = explode( '?', $source, 2 )[0] . ( '' !== $query ? '?' . $query : '' );
- foreach ( [ [ $source, $target ], [ esc_url( $source ), esc_url( $target ) ], [ esc_attr( $source ), esc_attr( $target ) ] ] as $urls ) {
- foreach ( [ '"', "'" ] as $quote ) {
- $map[ $quote . $urls[0] . $quote ] = $quote . $urls[1] . $quote;
- }
- }
+ return;
}
- return strtr( $buffer, $map );
+ $query = rtrim( $query, '&' );
+ $_SERVER['QUERY_STRING'] = $query;
+ $_SERVER['REQUEST_URI'] = $uri[0] . ( '' !== $query ? '?' . $query : '' );
}
/**
@@ -783,10 +784,26 @@
if ( $is_forced ) {
Debug2::debug( '--forced--' );
}
+ }
- // If CLI and contains Purge Header, issue an HTTP request to Purge
- if ( defined( 'LITESPEED_CLI' ) ) {
+ /**
+ * At CLI shutdown, kick the current blog's queue and, on multisite, the queue of every other blog this process stored a purge for.
+ *
+ * Each blog's queue is only consumed by a request to that blog, so a purge stored after switch_to_blog() needs its own kick.
+ */
+ public static function kick_cli_purge_queues() {
+ self::kick_purge_queue();
+ if ( ! is_multisite() ) {
+ return;
+ }
+ $current = get_current_blog_id();
+ foreach ( Purge::cli_queued_blogs() as $blog_id ) {
+ if ( $blog_id === $current ) {
+ continue;
+ }
+ switch_to_blog( $blog_id );
self::kick_purge_queue();
+ restore_current_blog();
}
}
--- a/litespeed-cache/src/crawler.cls.php
+++ b/litespeed-cache/src/crawler.cls.php
@@ -801,15 +801,15 @@
curl_setopt( $ch, CURLOPT_URL, $url );
$result = curl_exec( $ch );
$errno = curl_errno( $ch );
+ $http_code = $errno ? 0 : (int) curl_getinfo( $ch, CURLINFO_RESPONSE_CODE );
$test_result = false;
if ( 0 === $errno && $result === $home ) {
self::debug( '✅ Tested local 443 port successfully' );
define( 'LITESPEED_CRAWLER_LOCAL_PORT', 443 );
$this->_summary['test_port'] = 443;
$test_result = true;
- } elseif ( CURLE_COULDNT_CONNECT === $errno ) {
- // Fall back only on connection failure; this does not prove ports 80 and 443 share a cache.
- self::debug( '❌ Test local 443 port could not connect, try port 80' );
+ } elseif ( CURLE_COULDNT_CONNECT === $errno || in_array( $http_code, [ 404, 421 ], true ) ) {
+ self::debug( '❌ Test local 443 port ' . ( $errno ? 'could not connect' : 'returned HTTP ' . $http_code ) . ', try port 80' );
// Try port 80.
$resolved = $parsed_url['host'] . ':80:' . $this->_server_ip;
@@ -837,6 +837,9 @@
} else {
self::debug( '❌ Test local 443 port failed, no fallback, response is wrong: ' . $result );
}
+ if ( ! $test_result ) {
+ self::debug( 'Define LITESPEED_CRAWLER_LOCAL_PORT in wp-config.php to set the crawler port explicitly.' );
+ }
self::save_summary();
unset( $ch );
// phpcs:enable
--- a/litespeed-cache/src/data.cls.php
+++ b/litespeed-cache/src/data.cls.php
@@ -26,11 +26,11 @@
*/
private $_db_updater = [
'5.3-a5' => [ 'litespeed_update_5_3' ],
- '7.0-b26' => [ 'litespeed_update_7' ],
'7.0.1-b1' => [ 'litespeed_update_7_0_1' ],
'7.7-b28' => [ 'litespeed_update_7_7' ],
'7.9-b5' => [ 'litespeed_update_7_9' ],
'7.9.2-b60' => [ 'litespeed_update_7_9_2' ],
+ '7.9.4-b15' => [ 'litespeed_update_7_9_4' ],
];
/**
--- a/litespeed-cache/src/data.upgrade.func.php
+++ b/litespeed-cache/src/data.upgrade.func.php
@@ -11,7 +11,6 @@
defined( 'WPINC' ) || exit();
use LiteSpeedDebug2;
-use LiteSpeedCloud;
use LiteSpeedConf;
use LiteSpeedHtaccess;
@@ -80,43 +79,6 @@
}
/**
- * Migrate from domain key to pk/sk for QC
- *
- * @since 7.0
- */
-function litespeed_update_7() {
- Debug2::debug('[Data] v7 upgrade started');
-
- $__cloud = Cloud::cls();
-
- $domain_key = $__cloud->conf('api_key');
- if (!$domain_key) {
- Debug2::debug('[Data] No domain key, bypassed migration');
- return;
- }
-
- $new_prepared = $__cloud->init_qc_prepare();
- if (!$new_prepared && $__cloud->activated()) {
- Debug2::debug('[Data] QC previously activated in v7, bypassed migration');
- return;
- }
- $data = array(
- 'domain_key' => $domain_key,
- );
- $resp = $__cloud->post(Cloud::SVC_D_V3UPGRADE, $data);
- if ( ! empty( $resp['qc_activated'] ) ) {
- if ( 'deleted' !== $resp['qc_activated'] ) {
- $cloud_summary_updates = array( 'qc_activated' => $resp['qc_activated'] );
- if (!empty($resp['main_domain'])) {
- $cloud_summary_updates['main_domain'] = $resp['main_domain'];
- }
- Cloud::save_summary($cloud_summary_updates);
- Debug2::debug('[Data] Updated QC activated status to ' . $resp['qc_activated']);
- }
- }
-}
-
-/**
* Drop deprecated guest_ips and guest_uas from DB options.
* Migrate url table to make all links trailing slash for UCSS/CCSS.
*
@@ -216,3 +178,14 @@
// v7.9.2 no longer writes outside the WordPress/frontend roots; point the administrator to any block left there.
Htaccess::cls()->notice_orphan_rules();
}
+
+/**
+ * Drop the removed Inline CSS Async Lib option. [2026-11-11]
+ *
+ * @since 7.9.4
+ * @return void
+ */
+function litespeed_update_7_9_4() {
+ Conf::delete_option( 'optm-css_async_inline' );
+ Conf::delete_site_option( 'optm-css_async_inline' );
+}
--- a/litespeed-cache/src/esi.cls.php
+++ b/litespeed-cache/src/esi.cls.php
@@ -46,6 +46,12 @@
* @since 4.0 Change to be after Vary init in hook 'after_setup_theme'
*/
public function init() {
+ // Widget ESI settings are registered before the AJAX bypass below: the classic widgets screen and the Customizer save through admin-ajax, the block editor through REST.
+ if ( $this->cls( 'Router' )->esi_enabled() ) {
+ add_action( 'in_widget_form', [ $this, 'widget_form' ], 100, 3 );
+ add_filter( 'widget_update_callback', __NAMESPACE__ . 'Admin_Settings::validate_widget_save', 10, 4 );
+ }
+
/**
* Bypass ESI related funcs if disabled ESI to fix potential DIVI compatibility issue
*
@@ -83,6 +89,23 @@
}
/**
+ * Output the LiteSpeed ESI settings inside a widget form.
+ *
+ * Hooked to the in_widget_form action.
+ *
+ * @since 7.9.4
+ * @access public
+ *
+ * @param WP_Widget $widget The widget instance (passed by reference).
+ * @param mixed $return_val Return param (unused).
+ * @param array $instance The widget instance's settings.
+ * @return void
+ */
+ public function widget_form( $widget, $return_val, $instance ) {
+ require LSCWP_DIR . 'tpl/esi_widget_edit.php';
+ }
+
+ /**
* Init ESI related hooks
*
* Load delayed by hook to give the ability to bypass by LITESPEED_DISABLE_ALL const
@@ -566,7 +589,8 @@
// Convert to string to avoid html chars filter when using
// Will reverse the buffer when output in self::finalize()
if ($preserved) {
- $hash = md5($output);
+ // Bind the marker to the identity the nonce itself is bound to, so one learned in another session never matches here.
+ $hash = md5( $this->_preserve_identity( isset( $params['action'] ) ? $params['action'] : -1 ) . $output );
$this->_esi_preserve_list[$hash] = $output;
self::debug("Preserved to $hash");
@@ -577,6 +601,29 @@
}
/**
+ * Secret, session-bound prefix for preserved ESI markers.
+ *
+ * @since 7.9.4
+ * @access private
+ *
+ * @param mixed $action Nonce action, or -1.
+ * @return string
+ */
+ private function _preserve_identity( $action ) {
+ // Pluggable functions are missing when a nonce is created while plugins are still loading; such a marker is only keyed by the site.
+ if ( ! function_exists( 'wp_get_current_user' ) || ! function_exists( 'wp_hash' ) ) {
+ return md5( (string) $this->conf( Base::HASH ) );
+ }
+ $uid = get_current_user_id();
+ if ( ! $uid ) {
+ /** This filter is documented in wp-includes/pluggable.php */
+ $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
+ }
+
+ return wp_hash( $uid . '|' . wp_get_session_token(), 'nonce' );
+ }
+
+ /**
* Generate the ESI request MAC.
*
* @since 2.9.6
@@ -1214,6 +1261,15 @@
$keys = array_keys($this->_esi_preserve_list);
+ // Headers are not expanded: a marker sent as X-WP-Nonce is neither a nonce nor safe to disclose.
+ if ( ! headers_sent() ) {
+ foreach ( headers_list() as $header ) {
+ if ( 0 === stripos( $header, 'X-WP-Nonce:' ) && isset( $this->_esi_preserve_list[ trim( substr( $header, 11 ) ) ] ) ) {
+ header_remove( 'X-WP-Nonce' );
+ }
+ }
+ }
+
self::debug('[ESI] replacing preserved blocks', $keys);
$buffer = str_replace($keys, $this->_esi_preserve_list, $buffer);
--- a/litespeed-cache/src/file.cls.php
+++ b/litespeed-cache/src/file.cls.php
@@ -214,7 +214,12 @@
if ( ! is_dir( $dir ) || is_link( $dir ) ) {
return false;
}
- $files = array_diff(scandir($dir), array( '.', '..' ));
+ $files = scandir($dir);
+ // The directory can become unreadable or disappear after is_dir().
+ if (false === $files) {
+ return false;
+ }
+ $files = array_diff($files, [ '.', '..' ]);
foreach ($files as $file) {
is_dir("$dir/$file") && ! is_link("$dir/$file") ? self::rrmdir("$dir/$file") : unlink("$dir/$file");
--- a/litespeed-cache/src/gui.cls.php
+++ b/litespeed-cache/src/gui.cls.php
@@ -170,10 +170,13 @@
* @param bool $finished_tick Show a tick when 100%.
* @param bool $without_percentage Hide the % label.
* @param string|bool $append_cls Extra CSS class.
+ * @param string|bool $label Text shown in the center instead of the percentage.
* @return string SVG markup.
*/
- public static function pie( $percent, $width = 50, $finished_tick = false, $without_percentage = false, $append_cls = false ) {
- $label = $without_percentage ? $percent : ( $percent . '%' );
+ public static function pie( $percent, $width = 50, $finished_tick = false, $without_percentage = false, $append_cls = false, $label = false ) {
+ if ( false === $label ) {
+ $label = $without_percentage ? $percent : ( $percent . '%' );
+ }
$percentage = '<text x="50%" y="50%">' . esc_html( $label ) . '</text>';
if ( 100 === $percent && $finished_tick ) {
@@ -1180,9 +1183,39 @@
private function _enqueue_guest_js( $buffer ) {
$js_con = File::read( LSCWP_DIR . self::LIB_GUEST_JS );
// Build path for guest endpoint using wp_parse_url for compatibility.
- $guest_update_path = wp_parse_url( LSWCP_PLUGIN_URL . self::PHP_GUEST, PHP_URL_PATH );
- $js_con = str_replace( 'litespeed_url', esc_url( $guest_update_path ), $js_con );
- $buffer = Utility::insert_before_last_tag( $buffer, '</body>', '<script data-no-optimize="1">' . $js_con . '</script>' );
+ $default = wp_parse_url( LSWCP_PLUGIN_URL . self::PHP_GUEST, PHP_URL_PATH );
+
+ /**
+ * Filters the endpoint the Guest Mode script posts to; the lightweight guest.vary.php path by default.
+ *
+ * @since 7.9.4
+ * @param string $default Endpoint URL or path.
+ */
+ $url = apply_filters( 'litespeed_guest_vary_url', $default );
+ if ( ! is_string( $url ) || '' === $url ) {
+ $url = $default;
+ }
+ // When the endpoint was replaced, the script retries once with the default one if it fails.
+ $fallback = $url === $default ? '' : $default;
+
+ // Inject as JSON string literals: esc_url() would turn `&` into `&`.
+ $url_js = wp_json_encode( $url, Str::JSON_HTML_FLAGS );
+ $fallback_js = wp_json_encode( $fallback, Str::JSON_HTML_FLAGS );
+ if ( false === $url_js || false === $fallback_js ) {
+ // An endpoint that cannot be encoded must never leave the script without a value.
+ $url_js = wp_json_encode( $default, Str::JSON_HTML_FLAGS );
+ $fallback_js = '""';
+ }
+ $js_con = strtr(
+ $js_con,
+ [
+ "'litespeed_url'" => $url_js,
+ '"litespeed_url"' => $url_js,
+ "'litespeed_fallback_url'" => $fallback_js,
+ '"litespeed_fallback_url"' => $fallback_js,
+ ]
+ );
+ $buffer = Utility::insert_before_last_tag( $buffer, '</body>', '<script data-no-optimize="1">' . $js_con . '</script>' );
return $buffer;
}
}
--- a/litespeed-cache/src/htaccess.cls.php
+++ b/litespeed-cache/src/htaccess.cls.php
@@ -294,6 +294,7 @@
* Find LiteSpeed blocks that v7.9.1 wrote into an ancestor .htaccess outside the WordPress and frontend roots.
*
* Read-only: repeats the v7.9.1 upward search (first existing .htaccess outside the roots, stopping at DOCUMENT_ROOT or `/`); a .htaccess inside the roots does not end it. Never writes outside the proven roots.
+ * An ancestor .htaccess beside both wp-load.php and wp-includes belongs to another WordPress installation and ends the search without a notice.
*
* @since 7.9.2
* @return array<int,string> Paths of ancestor .htaccess files still holding a LiteSpeed block.
@@ -306,6 +307,10 @@
// An owned .htaccess created later (e.g. by v7.9.2) does not end the search: v7.9.1 may have written to an ancestor before it existed. The first ancestor file outside the roots (the v7.9.1 target) does.
while ( $path ) {
if ( file_exists( $path . '/.htaccess' ) && ! File::within( $path, ABSPATH ) && ! File::within( $path, $frontend ) ) {
+ // A separate ancestor installation can own these markers; never ask this site's administrator to remove them.
+ if ( is_file( $path . '/wp-load.php' ) && is_dir( $path . '/wp-includes' ) ) {
+ break;
+ }
$content = File::read( $path . '/.htaccess' );
// Accept LF and CRLF line endings.
if ( is_string( $content ) && preg_match( '/^[ t]*# BEGIN (?:' . self::MARKER . '|' . self::MARKER_NONLS . ')[ t]*r?$/m', $content ) ) {
@@ -1117,12 +1122,26 @@
$failed = [];
$kinds = $this->frontend_htaccess !== $this->backend_htaccess ? [ 'frontend', 'backend' ] : [ 'frontend' ];
foreach ( $kinds as $kind ) {
- foreach ( [ self::MARKER, self::MARKER_NONLS ] as $marker ) {
- try {
- $this->_insert_wrapper( false, $kind, $marker );
- } catch ( Exception $error ) {
- $failed[] = $error->getMessage();
+ // Remove our blocks with their markers, leaving the rest of the file as is.
+ $path = $this->htaccess_path( $kind );
+ $content = File::read( $path );
+ // An unreadable file must never be saved back as empty.
+ if ( ! is_string( $content ) ) {
+ $failed[] = 'Could not read the rewrite rules.';
+ continue;
+ }
+ // A later start belongs to its own block, not to an earlier orphan start.
+ $cleaned = preg_replace( '/^[ t]*# BEGIN (' . self::MARKER . '|' . self::MARKER_NONLS . ')[ t]*r?n(?:(?![ t]*# BEGIN 1[ t]*r?$)[^n]*n)*?[ t]*# END 1[ t]*(?:r?n|z)/m', '', $content );
+ if ( $cleaned === $content ) {
+ continue;
+ }
+ try {
+ $this->_htaccess_backup( $kind );
+ if ( ! is_string( $cleaned ) || ! File::save( $path, $cleaned ) ) {
+ throw new Exception( 'Could not update the rewrite rules.' );
}
+ } catch ( Exception $error ) {
+ $failed[] = $error->getMessage();
}
}
if ( $failed ) {
--- a/litespeed-cache/src/img-optm-pull.trait.php
+++ b/litespeed-cache/src/img-optm-pull.trait.php
@@ -146,7 +146,13 @@
* @return bool True if need to pull.
*/
public static function need_pull() {
- $tag = (int) self::get_option( self::DB_NEED_PULL );
+ $tag = self::get_option( self::DB_NEED_PULL, null );
+ if ( null === $tag ) {
+ // Task::init() asks on every request and a missing option is not autoloaded, so store the default once; 0 means nothing to pull.
+ self::update_option( self::DB_NEED_PULL, 0 );
+ return false;
+ }
+ $tag = (int) $tag;
if ( ! $tag || self::STATUS_NOTIFIED !== $tag ) {
return false;
}
--- a/litespeed-cache/src/img-optm-send.trait.php
+++ b/litespeed-cache/src/img-optm-send.trait.php
@@ -117,8 +117,9 @@
*
* @since 1.6
* @access public
+ * @param int $post_id Optional attachment ID to optimize only that image; 0 scans from the batch cursor.
*/
- public function new_req() {
+ public function new_req( $post_id = 0 ) {
global $wpdb;
if ( ! $this->_format && ! $this->conf( self::O_IMG_OPTM_ORI ) ) {
@@ -201,7 +202,7 @@
// May need to get more images
$list = [];
- $more = $allowance - $total_new;
+ $more = $post_id ? 1 : $allowance - $total_new;
if ( $more > 0 ) {
$previous_post_id = $this->_summary['next_post_id'];
$q = "SELECT b.post_id, b.meta_value
@@ -210,13 +211,13 @@
WHERE b.meta_key = '_wp_attachment_metadata'
AND a.post_type = 'attachment'
AND a.post_status = 'inherit'
- AND a.ID>%d
+ AND a.ID" . ( $post_id ? '=' : '>' ) . "%d
AND a.post_mime_type IN ('image/jpeg', 'image/png', 'image/gif')
ORDER BY a.ID
LIMIT %d
";
// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared
- $q = $wpdb->prepare( $q, [ $this->_summary['next_post_id'], $more ] );
+ $q = $wpdb->prepare( $q, [ $post_id ? $post_id : $this->_summary['next_post_id'], $more ] );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared
$list = $wpdb->get_results( $q );
foreach ( $list as $v ) {
@@ -224,7 +225,9 @@
continue;
}
- $this->_summary['next_post_id'] = $v->post_id;
+ if ( ! $post_id ) {
+ $this->_summary['next_post_id'] = $v->post_id;
+ }
$meta_value = $this->_parse_wp_meta_value( $v );
if ( ! $meta_value ) {
@@ -270,7 +273,7 @@
}
// Push to Cloud server
- $accepted_imgs = $this->_send_request( $allowance );
+ $accepted_imgs = $this->_send_request( $allowance, $post_id );
$this->_finished_running();
if ( ! $accepted_imgs ) {
@@ -551,17 +554,21 @@
* @since 1.6.7
* @access private
* @param int $allowance The allowance limit.
+ * @param int $post_id Optional attachment ID to send only its rows.
* @return array|void Array with pushed and accepted counts.
*/
- private function _send_request( $allowance ) {
+ private function _send_request( $allowance, $post_id = 0 ) {
global $wpdb;
- $q = "SELECT id, src, post_id FROM `$this->_table_img_optming` WHERE optm_status=%d LIMIT %d";
+ $q = "SELECT id, src, post_id FROM `$this->_table_img_optming` WHERE optm_status=%d" . ( $post_id ? ' AND post_id=%d' : '' ) . ' LIMIT %d';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared
- $q = $wpdb->prepare( $q, [ self::STATUS_RAW, $allowance ] );
+ $q = $wpdb->prepare( $q, $post_id ? [ self::STATUS_RAW, $post_id, $allowance ] : [ self::STATUS_RAW, $allowance ] );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared
$_img_in_queue = $wpdb->get_results( $q );
if ( ! $_img_in_queue ) {
+ if ( $post_id ) {
+ Admin_Display::error( __( 'No valid image found in the current request.', 'litespeed-cache' ) );
+ }
return;
}
--- a/litespeed-cache/src/img-optm.cls.php
+++ b/litespeed-cache/src/img-optm.cls.php
@@ -29,6 +29,7 @@
const CLOUD_ACTION_CLEAN = 'clean';
const TYPE_NEW_REQ = 'new_req';
+ const TYPE_NEW_REQ_ROW = 'new_req_row';
const TYPE_RESCAN = 'rescan';
const TYPE_DESTROY = 'destroy';
const TYPE_RESET_COUNTER = 'reset_counter';
@@ -223,6 +224,17 @@
$this->new_req();
break;
+ case self::TYPE_NEW_REQ_ROW:
+ // phpcs:ignore WordPress.Security.NonceVerification.Recommended
+ $id = isset( $_GET['id'] ) && is_string( $_GET['id'] ) ? sanitize_text_field( wp_unslash( $_GET['id'] ) ) : '';
+ $id = ctype_digit( $id ) ? absint( $id ) : 0;
+ if ( $id ) {
+ $this->new_req( $id );
+ } else {
+ Admin_Display::error( __( 'No valid image found in the current request.', 'litespeed-cache' ) );
+ }
+ break;
+
case self::TYPE_RESCAN:
$this->_rescan();
break;
--- a/litespeed-cache/src/lang.cls.php
+++ b/litespeed-cache/src/lang.cls.php
@@ -172,7 +172,6 @@
self::O_OPTM_HTML_SKIP_COMMENTS => __( 'HTML Keep Comments', 'litespeed-cache' ),
self::O_OPTM_CSS_ASYNC => __( 'Load CSS Asynchronously', 'litespeed-cache' ),
self::O_OPTM_CCSS_PER_URL => __( 'CCSS Per URL', 'litespeed-cache' ),
- self::O_OPTM_CSS_ASYNC_INLINE => __( 'Inline CSS Async Lib', 'litespeed-cache' ),
self::O_OPTM_CSS_FONT_DISPLAY => __( 'Font Display Optimization', 'litespeed-cache' ),
self::O_OPTM_JS_DEFER => __( 'Load JS Deferred', 'litespeed-cache' ),
self::O_OPTM_LOCALIZE => __( 'Localize Resources', 'litespeed-cache' ),
--- a/litespeed-cache/src/media.cls.php
+++ b/litespeed-cache/src/media.cls.php
@@ -150,44 +150,57 @@
public function rescale_ori( $metadata, $attachment_id ) {
// Test if create and image was resized.
if ( $metadata && isset( $metadata['original_image'], $metadata['file'] ) && false !== strpos( $metadata['file'], '-scaled' ) ) {
- // Get rescaled file name.
- $path_exploded = explode( '/', strrev( $metadata['file'] ), 2 );
- $rescaled_file_name = strrev( $path_exploded[0] );
+ // Use the attachment's own folder (e.g. "2021/04/"), not the current upload month.
+ $subdir = $this->_meta_folder( $metadata['file'] );
// Create paths for images: resized and original.
- $base_path = $this->_wp_upload_dir['basedir'] . $this->_wp_upload_dir['subdir'] . '/';
- $rescaled_path = $base_path . $rescaled_file_name;
+ $base_path = trailingslashit( $this->_wp_upload_dir['basedir'] ) . $subdir;
+ $rescaled_path = $base_path . wp_basename( $metadata['file'] );
$new_path = $base_path . $metadata['original_image'];
- // Change array file key.
- $metadata['file'] = $this->_wp_upload_dir['subdir'] . '/' . $metadata['original_image'];
- if ( 0 === strpos( $metadata['file'], '/' ) ) {
- $metadata['file'] = substr( $metadata['file'], 1 );
+ if ( ! file_exists( $new_path ) ) {
+ return $metadata;
}
- // Delete array "original_image" key.
- unset( $metadata['original_image'] );
-
- if ( file_exists( $rescaled_path ) && file_exists( $new_path ) ) {
+ if ( file_exists( $rescaled_path ) ) {
// Move rescaled to original using WP_Filesystem.
global $wp_filesystem;
if ( ! $wp_filesystem ) {
require_once ABSPATH . '/wp-admin/includes/file.php';
WP_Filesystem();
}
- if ( $wp_filesystem ) {
- $wp_filesystem->move( $rescaled_path, $new_path, true );
+ if ( ! $wp_filesystem || ! $wp_filesystem->move( $rescaled_path, $new_path, true ) ) {
+ return $metadata;
}
-
- // Update meta "_wp_attached_file".
- update_post_meta( $attachment_id, '_wp_attached_file', $metadata['file'] );
}
+ // Otherwise an earlier metadata save of this upload already moved it.
+
+ // Point metadata to the original only once the rescaled file is in its place.
+ $metadata['file'] = $subdir . $metadata['original_image'];
+ unset( $metadata['original_image'] );
+
+ // Update meta "_wp_attached_file".
+ update_post_meta( $attachment_id, '_wp_attached_file', $metadata['file'] );
}
return $metadata;
}
/**
+ * Get the folder prefix of an attachment from its metadata file path.
+ *
+ * @since 7.9.4
+ *
+ * @param string $file Metadata file value relative to the uploads folder, e.g. "2024/05/photo.jpg" or "photo.jpg".
+ * @return string Folder with a trailing slash, or an empty string when the file sits in the uploads root.
+ */
+ private function _meta_folder( $file ) {
+ $folder = dirname( $file );
+
+ return '.' === $folder ? '' : $folder . '/';
+ }
+
+ /**
* Route media actions.
*
* @since 7.7
@@ -255,16 +268,15 @@
$attachment_id = $v->ID;
- // Extract subdirectory from metadata file path (e.g. "2024/05/photo-scaled.jpg" → "2024/05").
- $subdir = pathinfo( $meta_value['file'], PATHINFO_DIRNAME );
+ // Folder prefix from the metadata file path (e.g. "2024/05/photo-scaled.jpg" gives "2024/05/", "photo-scaled.jpg" gives "").
+ $subdir = $this->_meta_folder( $meta_value['file'] );
// Build relative paths for rename().
- $scaled_filename = basename( $meta_value['file'] );
- $scaled_path = $subdir . '/' . $scaled_filename;
- $original_path = $subdir . '/' . $meta_value['original_image'];
+ $scaled_path = $subdir . wp_basename( $meta_value['file'] );
+ $original_path = $subdir . $meta_value['original_image'];
// Verify scaled file exists before proceeding
- // TODO: need to ues isfile func to allow hook from offload plugins
+ // TODO: need to use isfile func to allow hook from offload plugins
$basedir = $this->_wp_upload_dir['basedir'] . '/';
if ( ! file_exists( $basedir . $scaled_path ) ) {
self::debug( 'Skipped: scaled file missing [pid] ' . $attachment_id );
@@ -277,7 +289,7 @@
}
// Update metadata: point file to original, remove original_image key.
- $meta_value['file'] = $subdir . '/' . $meta_value['original_image'];
+ $meta_value['file'] = $original_path;
unset( $meta_value['original_image'] );
wp_update_attachment_metadata( $attachment_id, $meta_value );
@@ -702,6 +714,12 @@
esc_html__( 'Restore from backup', 'litespeed-cache' )
);
echo '</div>';
+ } elseif ( in_array( get_post_mime_type( $post_id ), [ 'image/jpeg', 'image/png', 'image/gif' ], true ) ) {
+ printf(
+ '<div class="row-actions"><span><a href="%1$s">%2$s</a></span></div>',
+ esc_url( Utility::build_url( Router::ACTION_IMG_OPTM, Img_Optm::TYPE_NEW_REQ_ROW, false, null, [ 'id' => $post_id ] ) ),
+ esc_html__( 'Optimize', 'litespeed-cache' )
+ );
}
}
@@ -926,7 +944,7 @@
foreach ( $html_list as $k => $v ) {
$snippet = $cfg_trim_noscript || false !== stripos( $v, '</noscript' ) ? '' : '<noscript>' . $v . '</noscript>';
$source_attr = $cfg_js_delay ? 'data-litespeed-src' : 'data-src';
- $v = preg_replace_callback( '/A(<iframeb' . Utility::HTML_ATTR_PREFIX . ')s+srcs*=/i', static function ( $matches ) use ( $source_attr ) {
+ $v = preg_replace_callback( '/A(<iframeb' . Utility::HTML_ATTR_PREFIX . ')[' . Utility::HTML_WS . ']+src[' . Utility::HTML_WS . ']*=/i', static function ( $matches ) use ( $source_attr ) {
return $matches[1] . ' ' . $source_attr . '=';
}, $v, 1, $renamed );
// Only a real src rename may receive the about:blank src; otherwise keep the iframe untouched.
@@ -984,37 +1002,30 @@
return;
}
- $replacements = [];
- $content = Utility::html_mask( $this->content, [ 'img' ] );
- if ( null === $content ) {
- return;
- }
- // Keep source offsets and skip non-rendered markup, even when it contains the same image tag.
- preg_match_all( '#<imgs+(?P<attrs>' . Utility::HTML_ATTR_PATTERN . ')>#is', $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
- foreach ($matches as $source_match) {
- if ( ! isset( $source_match['attrs'] ) || -1 === $source_match['attrs'][1] || ! preg_match( '//u', $source_match['attrs'][0] ) ) {
- continue;
+ // Walk real img tokens only; identical text in comments, scripts or another tag's attribute value is never a token.
+ $result = Utility::html_tokens( $this->content, function ( $token ) use ( $vpi_files ) {
+ if ( empty( $token['tag'] ) || empty( $token['end'] ) || ! empty( $token['opaque'] ) || 'img' !== strtolower( $token['tag'] ) || ! preg_match( '//u', $token['attrs'] ) ) {
+ return $token[0];
}
- $match = [ $source_match[0][0], $source_match['attrs'][0] ];
- $attrs = Utility::parse_attr($match[1]);
+ $attrs = Utility::parse_attr( $token['attrs'] );
if ( empty( $attrs['src'] ) ) {
- continue;
+ return $token[0];
}
if ( false !== strpos( $attrs['src'], 'base64' ) || 0 === strpos( $attrs['src'], 'data:' ) ) {
self::debug2( 'lazyload bypassed base64 img' );
- continue;
+ return $token[0];
}
if ( false !== strpos( $attrs['src'], '{' ) ) {
self::debug2( 'image src has {} ' . $attrs['src'] );
- continue;
+ return $token[0];
}
// If the src contains VPI filename, then preload it.
if ( ! Utility::str_hit_array( $attrs['src'], $vpi_files ) ) {
- continue;
+ return $token[0];
}
self::debug2( 'VPI preload found and matched: ' . $attrs['src'] );
@@ -1028,29 +1039,16 @@
$this->_vpi_preload_list[] = $preload;
}
- // Add attributes fetchpriority="high" and decode="sync"
- // after WP 6.3.0 use: wp_img_tag_add_loading_optimization_attrs().
- $new_html = [];
- $attrs[ 'fetchpriority' ] = 'high';
- $attrs[ 'decoding' ] = 'sync';
- // create html with new attributes.
- foreach ( $attrs as $k => $attr ) {
- // Escape the value and drop anything whose name is not a plain attribute name.
- if ( ! preg_match( '/^[a-zA-Z_:][-w:.]*$/', (string) $k ) ) {
- self::debug2( 'VPI preload dropped an attribute with an unusable name' );
- continue;
- }
- $new_html[] = $k . '="' . esc_attr( $attr ) . '"';
- }
-
- if ( $new_html ) {
- $replacements[] = [ $source_match[0][1], strlen( $match[0] ), '<img ' . implode( ' ', $new_html ) . '>' ];
+ // Add fetchpriority="high" and decoding="sync" in front of the original attribute bytes; the tag is never rebuilt from parsed values.
+ $kept = Utility::remove_attr( Utility::remove_attr( $token['attrs'], 'fetchpriority' ), 'decoding' );
+ if ( '' !== $kept && false === strpos( "tnfr /", $kept[0] ) ) {
+ return $token[0];
}
- }
- // Replace from the end so earlier source offsets remain valid.
- foreach ( array_reverse( $replacements ) as $replacement ) {
- $this->content = substr_replace( $this->content, $replacement[2], $replacement[0], $replacement[1] );
+ return '<' . $token['tag'] . ' fetchpriority="high" decoding="sync"' . $kept . '>';
+ } );
+ if ( null !== $result ) {
+ $this->content = $result;
}
}
@@ -1121,7 +1119,7 @@
&& apply_filters( 'litespeed_media_add_missing_sizes', true );
$replacements = [];
- preg_match_all( '#<imgs+(' . Utility::HTML_ATTR_PATTERN . ')>#is', $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
+ preg_match_all( '#<img[' . Utility::HTML_WS . ']+(' . Utility::HTML_ATTR_PATTERN . ')>#is', $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
foreach ( $matches as $source_match ) {
$match = [ $source_match[0][0], $source_match[1][0] ];
// Exclusion masks may hide tokens, but must never expose previously inert text.
@@ -1205,16 +1203,19 @@
}
// Remove existing width/height, then append new values
- $inner = Utility::html_self_closing( $match[1] ) ? substr( $match[1], 0, -1 ) : $match[1];
- $inner = Utility::remove_attr( $inner, 'width' );
- $inner = Utility::remove_attr( $inner, 'height' );
- $inner = rtrim( $inner, " tnrf" );
- $new_html = '<img ' . $inner . ' width="' . (int) $ori_width . '" height="' . (int) $ori_height . '" />';
- self::debug( 'Add missing sizes ' . $ori_width . 'x' . $ori_height . ' to ' . $attrs['src'] );
- $replacements[ $match[0] ] = $new_html;
- $match[0] = $new_html;
- $attrs['width'] = $ori_width;
- $attrs['height'] = $ori_height;
+ $inner = Utility::html_self_closing( $match[1] ) ? substr( $match[1], 0, -1 ) : $match[1];
+ $inner = Utility::remove_attr( $inner, 'width' );
+ $inner = Utility::remove_attr( $inner, 'height' );
+ $inner = rtrim( $inner, " tnrf" );
+ // A trailing `name=` would take the appended attributes as its value, so such a tag keeps its own markup.
+ if ( '=' !== substr( $inner, -1 ) ) {
+ $new_html = '<img ' . $inner . ' width="' . (int) $ori_width . '" height="' . (int) $ori_height . '" />';
+ self::debug( 'Add missing sizes ' . $ori_width . 'x' . $ori_height . ' to ' . $attrs['src'] );
+ $replacements[ $match[0] ] = $new_html;
+ $match[0] = $new_html;
+ $attrs['width'] = $ori_width;
+ $attrs['height'] = $ori_height;
+ }
}
}
}
@@ -1312,12 +1313,23 @@
if ( null === $content ) {
return $html_list;
}
- preg_match_all( '#<iframes+(?P<attrs>' . Utility::HTML_ATTR_PATTERN . ')>.*?</iframes*>#is', $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
+ // Offsets and lengths of complete iframe elements; a match that is not exactly one of them started inside another token or ran past its end tag.
+ $iframe_tokens = [];
+ Utility::html_tokens( $this->content, static function ( $token ) use ( &$iframe_tokens ) {
+ if ( ! empty( $token['raw'] ) && empty( $token['opaque'] ) && ! empty( $token['close'] ) && 'iframe' === strtolower( $token['raw'] ) ) {
+ $iframe_tokens[ $token['offset'] ] = strlen( $token[0] );
+ }
+ return $token[0];
+ } );
+ preg_match_all( '#<iframe[' . Utility::HTML_WS . ']+(?P<attrs>' . Utility::HTML_ATTR_PATTERN . ')>.*?</iframe[' . Utility::HTML_WS . ']*>#is', $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
foreach ( $matches as $source_match ) {
if ( ! isset( $source_match['attrs'] ) || -1 === $source_match['attrs'][1] ) {
continue;
}
$match = [ $source_match[0][0], $source_match['attrs'][0] ];
+ if ( ! isset( $iframe_tokens[ $source_match[0][1] ] ) || strlen( $match[0] ) !== $iframe_tokens[ $source_match[0][1] ] ) {
+ continue;
+ }
if ( substr( $eligible_content, $source_match[0][1], strlen( $match[0] ) ) !== $match[0] ) {
continue;
}
@@ -1410,9 +1422,13 @@
// parse srcset.
// todo: should apply this to cdn too.
- if ( ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_IMG_OPTM_WEBP_REPLACE_SRCSET ) ) && $this->webp_support() ) {
+ $replace_srcset = ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_IMG_OPTM_WEBP_REPLACE_SRCSET ) ) && $this->webp_support();
+ if ( $replace_srcset ) {
$content = Utility::srcset_replace( $content, [ $this, 'replace_webp' ] );
}
+ if ( false !== strpos( $content, 'woocommerce-product-gallery__image' ) ) {
+ $content = $this->_replace_gallery_images( $content, $replace_srcset );
+ }
// Replace background-image.
if ( ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_IMG_OPTM_WEBP ) ) && $this->webp_support() ) {
@@ -1423,6 +1439,67 @@
}
/**
+ * Replace image URLs in WooCommerce product gallery slides.
+ *
+ * @param string $content HTML buffer.
+ * @param bool $replace_srcset Whether to replace responsive candidates.
+ * @return string Modified content.
+ */
+ private function _replace_gallery_images( $content, $replace_srcset ) {
+ $slide_tag = '';
+ $slide_depth = 0;
+ $result = Utility::html_tokens( $content, function ( $token ) use ( &$slide_tag, &$slide_depth, $replace_srcset ) {
+ $html = $token[0];
+ if ( $slide_depth && preg_match( '~A</' . $slide_tag . '(?=[s/>])~i', $html ) ) {
+ --$slide_depth;
+ }
+
+ $tag = isset( $token['tag'] ) ? strtolower( $token['tag'] ) : '';
+ $attributes = [];
+ if ( 'div' === $tag || 'figure' === $tag ) {
+ $attrs = false !== strpos( $token['attrs'], 'woocommerce-product-gallery__image' ) ? Utility::parse_attr( $token['attrs'] ) : [];
+ $classes = isset( $attrs['class'] ) ? preg_split( '/[x09x0ax0cx0d ]+/', $attrs['class'] ) : [];
+ if ( in_array( 'woocommerce-product-gallery__image', $classes, true ) ) {
+ if ( ! $slide_depth ) {
+ $slide_tag = $tag;
+ }
+ $attributes = [ 'data-thumb' ];
+ if ( $replace_srcset ) {
+ $html = Utility::srcset_replace( $html, [ $this, 'replace_webp' ], 'data-thumb-srcset' );
+ }
+ }
+ if ( $tag === $slide_tag && ( $slide_depth || $attributes ) ) {
+ ++$slide_depth;
+ }
+ } elseif ( 1 === $slide_depth && 'a' === $tag ) {
+ $attributes = [ 'href' ];
+ } elseif ( 1 === $slide_depth && 'img' === $tag ) {
+ $attributes = [ 'src', 'data-src', 'data-large_image' ];
+ }
+
+ foreach ( $attributes as $attribute ) {
+ $pattern = '~A(<[a-z]+' . Utility::HTML_ATTR_PREFIX . 's+' . $attribute . 's*=s*)(['"])(.*?)2~is';
+ $updated = preg_replace_callback( $pattern, function ( $matches ) {
+ $url = $this->replace_webp( $matches[3] );
+ return $url ? $matches[1] . $matches[2] . $url . $matches[2] : $matches[0];
+ }, $html );
+ if ( null === $updated ) {
+ self::debug2( 'WooCommerce gallery attribute match failed: ' . $attribute . ' [PCRE ' . preg_last_error() . ']' );
+ continue;
+ }
+ $html = $updated;
+ }
+ return $html;
+ } );
+
+ if ( null === $result ) {
+ self::debug2( 'WooCommerce gallery HTML tokenization failed [PCRE ' . preg_last_error() . ']' );
+ return $content;
+ }
+ return $result;
+ }
+
+ /**
* Replace background image in inline styles and JSON blobs.
*
* @since 4.0
@@ -1476,53 +1553,65 @@
* @return string Modified content with replaced URLs inside JSON att