Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/w3-total-cache/BrowserCache_Environment_Apache.php
+++ b/w3-total-cache/BrowserCache_Environment_Apache.php
@@ -114,7 +114,7 @@
$imploded = implode( '|', $exceptions );
if ( ! empty( $imploded ) ) {
- $rules .= " RewriteCond %{REQUEST_URI} !(" . $imploded . ")n";
+ $rules .= ' RewriteCond %{REQUEST_URI} "!(' . $imploded . ')"' . "n";
}
$rules .= " RewriteCond %{REQUEST_URI} \.(" . implode( '|', $extensions ) . ")$ [NC]n";
--- a/w3-total-cache/BrowserCache_Plugin.php
+++ b/w3-total-cache/BrowserCache_Plugin.php
@@ -199,7 +199,7 @@
$domain_url_regexp = Util_Environment::home_domain_root_url_regexp();
$buffer = preg_replace_callback(
- '~(href|src|action|extsrc|asyncsrc|w3tc_load_js()=?(['"])((' . $domain_url_regexp . ')?(/[^'"/][^'"]*.([a-z-_]+)([?#][^'"]*)?))['"]~Ui',
+ '~(href|src|action|extsrc|asyncsrc|w3tc_load_js()=?(['"])((' . $domain_url_regexp . ')?(/[^'"/][^'"]*.([a-z-_]+)([?#][^'"]*)?))2~Ui',
array( $this, 'link_replace_callback' ),
$buffer
);
--- a/w3-total-cache/BrowserCache_RuleDirectives.php
+++ b/w3-total-cache/BrowserCache_RuleDirectives.php
@@ -112,8 +112,9 @@
/**
* Normalizes no404wp exception patterns for rule rendering.
*
- * Sanitizes each entry, drops empties/non-strings, de-duplicates, and
- * sorts so equivalent inputs produce identical Apache/Nginx output.
+ * Sanitizes each entry, drops empties/non-strings and entries that are
+ * not a self-contained regular expression, de-duplicates, and sorts so
+ * equivalent inputs produce identical Apache/Nginx output.
*
* @since 2.10.6
*
@@ -123,9 +124,34 @@
*/
public static function normalize_exceptions( $exceptions ) {
$out = Util_Rule::sanitize_directive_values( $exceptions );
+ $out = array_filter( $out, array( __CLASS__, 'is_valid_exception_pattern' ) );
$out = array_values( array_unique( $out ) );
sort( $out, SORT_STRING );
return $out;
}
+
+ /**
+ * Checks that a no404wp exception compiles as a standalone regex.
+ *
+ * Each entry is rendered as one alternative inside a `(...|...)` group.
+ * An entry with unbalanced parentheses, a trailing backslash, or other
+ * invalid syntax could close that group early or make the server reject
+ * the whole rules file, so such entries are dropped.
+ *
+ * @since 2.11.1
+ *
+ * @param string $pattern Sanitized exception pattern.
+ *
+ * @return bool True when the pattern is a valid regular expression.
+ */
+ private static function is_valid_exception_pattern( $pattern ) {
+ if ( ! is_string( $pattern ) || '' === $pattern ) {
+ return false;
+ }
+
+ $delimited = '~' . str_replace( '~', '~', $pattern ) . '~';
+
+ return false !== @preg_match( $delimited, '' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
+ }
}
--- a/w3-total-cache/Cache_Base.php
+++ b/w3-total-cache/Cache_Base.php
@@ -294,6 +294,58 @@
}
/**
+ * Constructs a fixed-length item key from all key components.
+ *
+ * Memcache-family stores cap key length at 250 bytes, so every component
+ * is hashed and the key is always 70 bytes: `w3tc_` . md5( scope ) . `_` .
+ * md5( name ), where scope covers the instance id, blog id, module and host.
+ *
+ * @since 2.11.1
+ *
+ * @param string $w3tc_name Name.
+ *
+ * @return string
+ */
+ protected function get_fixed_length_item_key( $w3tc_name ) {
+ $scope = implode(
+ '|',
+ array(
+ (int) $this->_instance_id,
+ (int) $this->_blog_id,
+ (string) $this->_module,
+ (string) $this->_host,
+ )
+ );
+
+ return 'w3tc_' . md5( $scope ) . '_' . md5( (string) $w3tc_name );
+ }
+
+ /**
+ * Constructs a fixed-length key version key from all key components.
+ *
+ * Fixed-length counterpart of _get_key_version_key() for memcache-family
+ * stores; always 82 bytes.
+ *
+ * @since 2.11.1
+ *
+ * @param string $w3tc_group Group.
+ *
+ * @return string
+ */
+ protected function get_fixed_length_key_version_key( $w3tc_group = '' ) {
+ $scope = implode(
+ '|',
+ array(
+ (int) $this->_instance_id,
+ (int) $this->_blog_id,
+ (string) $this->_module,
+ )
+ );
+
+ return 'w3tc_' . md5( $scope ) . '_' . md5( (string) $w3tc_group ) . '_key_version';
+ }
+
+ /**
* Use key as a counter and add integer value to it
*
* @abstract
--- a/w3-total-cache/Cache_File.php
+++ b/w3-total-cache/Cache_File.php
@@ -234,7 +234,8 @@
$w3tc_data = null;
if ( false !== $expires_at ) {
- list( , $expires_at ) = @unpack( 'L', $expires_at );
+ $unpacked = @unpack( 'L', $expires_at );
+ $expires_at = is_array( $unpacked ) ? $unpacked[1] : 0;
if ( time() > $expires_at ) {
if ( $this->_use_expired_data ) {
@@ -357,7 +358,7 @@
* @return bool Always returns true.
*/
public function flush( $w3tc_group = '' ) {
- @set_time_limit( $this->_flush_timelimit ); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged
+ Util_Environment::set_time_limit( $this->_flush_timelimit );
if ( 'sitemaps' === $w3tc_group ) {
$w3tc_config = Dispatcher::config();
--- a/w3-total-cache/Cache_File_Cleaner.php
+++ b/w3-total-cache/Cache_File_Cleaner.php
@@ -56,7 +56,7 @@
* @return void
*/
public function clean() {
- @set_time_limit( $this->_clean_timelimit ); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged
+ Util_Environment::set_time_limit( $this->_clean_timelimit );
$this->_clean( $this->_cache_dir, false );
}
@@ -67,7 +67,7 @@
* @return void
*/
public function clean_before() {
- @set_time_limit( $this->_clean_timelimit ); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged
+ Util_Environment::set_time_limit( $this->_clean_timelimit );
$this->_clean( $this->_cache_dir, false );
}
--- a/w3-total-cache/Cache_File_Generic.php
+++ b/w3-total-cache/Cache_File_Generic.php
@@ -170,6 +170,167 @@
}
/**
+ * Keeps a stored page when the new content is identical, instead of replacing it.
+ *
+ * Apache builds ETag and Last-Modified from the file mtime (`FileETag MTime Size`), so a
+ * rewrite of unchanged HTML makes browsers download it again. The same mtime is the
+ * freshness clock for Cache_File_Cleaner_Generic, and the one the Always Cached
+ * ahead-generation clean compares with `before_time`. An old file is only kept while
+ * enough of the lifetime is left, so a regenerated page is not expired right after it
+ * was written; otherwise the file is rewritten with a new mtime.
+ *
+ * Pages are compared without the trailing W3TC footer comment, see {@see self::strip_footer()},
+ * since its "Served from" time differs on every render. When only the footer differs the stored
+ * file, with its old footer, stays.
+ *
+ * The current file is checked first, then `$path . '_old'`, which a purge, flush or garbage
+ * collection pass leaves behind. A matching `_old` file is moved back with its mtime.
+ *
+ * @since 2.11.1
+ *
+ * @param string $path Absolute cache file path.
+ * @param string $content New content, not empty.
+ * @param int $expire Lifetime in seconds, 0 for the configured one.
+ * @param array $data Cache entry. An optional `before_time` is the oldest mtime the ahead-generation clean keeps. An optional `c` is the compression of `content`.
+ *
+ * @return bool True when a file with this content is in place at $path.
+ */
+ private function keep_identical_file( $path, $content, $expire, $data ) {
+ $lifetime = $expire > 0 ? min( $expire, W3TC_CACHE_FILE_EXPIRE_MAX ) : $this->_expire;
+ $min_time = time() - intdiv( $lifetime, 2 );
+
+ if ( ! empty( $data['before_time'] ) ) {
+ $min_time = max( $min_time, (int) $data['before_time'] );
+ }
+
+ $compression = isset( $data['c'] ) ? (string) $data['c'] : '';
+ $decoded = $this->decode_content( $content, $compression );
+ $body = false === $decoded ? null : $this->strip_footer( $decoded );
+
+ if ( $this->file_matches( $path, $content, $min_time, $compression, $body ) ) {
+ return true;
+ }
+
+ $path_old = $path . '_old';
+ if ( ! $this->file_matches( $path_old, $content, $min_time, $compression, $body ) ) {
+ return false;
+ }
+
+ @unlink( $path );
+
+ return @rename( $path_old, $path );
+ }
+
+ /**
+ * Checks whether a file holds this content, ignoring the footer comment, and is recent enough.
+ *
+ * @since 2.11.1
+ *
+ * @param string $file File path.
+ * @param string $content New content, as stored.
+ * @param int $min_time Oldest accepted mtime.
+ * @param string $compression Compression of the content: gzip, deflate, br or empty.
+ * @param string|null $body New content without its footer, null when it has no footer.
+ *
+ * @return bool
+ */
+ private function file_matches( $file, $content, $min_time, $compression, $body ) {
+ if ( ! is_file( $file ) ) {
+ return false;
+ }
+
+ $mtime = @filemtime( $file );
+ if ( ! $mtime || $mtime < $min_time ) {
+ return false;
+ }
+
+ // Without a footer on the new page only identical bytes count.
+ if ( null === $body ) {
+ return @filesize( $file ) === strlen( $content ) && @file_get_contents( $file ) === $content;
+ }
+
+ $stored = @file_get_contents( $file );
+ if ( ! is_string( $stored ) ) {
+ return false;
+ }
+
+ if ( $stored === $content ) {
+ return true;
+ }
+
+ $stored = $this->decode_content( $stored, $compression );
+ if ( false === $stored ) {
+ return false;
+ }
+
+ return $this->strip_footer( $stored ) === $body;
+ }
+
+ /**
+ * Returns the uncompressed form of stored page content.
+ *
+ * @since 2.11.1
+ *
+ * @param string $content Content as stored.
+ * @param string $compression Compression: gzip, deflate, br or empty.
+ *
+ * @return string|false The HTML, or false when the content cannot be decoded here.
+ */
+ private function decode_content( $content, $compression ) {
+ switch ( $compression ) {
+ case '':
+ return $content;
+
+ case 'gzip':
+ return function_exists( 'gzdecode' ) ? @gzdecode( $content ) : false;
+
+ case 'deflate':
+ return function_exists( 'gzinflate' ) ? @gzinflate( $content ) : false;
+
+ case 'br':
+ return function_exists( 'brotli_uncompress' ) ? @brotli_uncompress( $content ) : false;
+
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Removes the W3TC footer comment that ends a page.
+ *
+ * Generic_Plugin::ob_callback() appends one comment, `rn<!--rn...rnrnServed from: host @ date by W3 Total Cachern-->`,
+ * before the page cache stores the page. Other `w3tc_footer_comment` lines (page cache engine, debug info,
+ * minify, CDN, object cache) are inside the same comment, so the whole block goes. Only a last comment that
+ * holds the "Served from" line is removed, and only when nothing but whitespace follows it.
+ *
+ * @since 2.11.1
+ *
+ * @param string $html Uncompressed page.
+ *
+ * @return string|null The page without the footer, null when it does not end with the footer.
+ */
+ private function strip_footer( $html ) {
+ $trimmed = rtrim( $html );
+ if ( '-->' !== substr( $trimmed, -3 ) ) {
+ return null;
+ }
+
+ $start = strrpos( $trimmed, '<!--' );
+ if ( false === $start ) {
+ return null;
+ }
+
+ $comment = substr( $trimmed, $start );
+ if ( strpos( $comment, '-->' ) !== strlen( $comment ) - 3
+ || ! preg_match( '/Served from: [^rn]* @ [^rn]* by W3 Total Caches*-->$/', $comment )
+ ) {
+ return null;
+ }
+
+ return substr( $trimmed, 0, $start );
+ }
+
+ /**
* Sets data
*
* @param string $w3tc_key Key.
@@ -200,47 +361,56 @@
}
}
- $tmppath = $path . '.' . getmypid();
+ $content = (string) $w3tc_value['content'];
- $fp = @fopen( $tmppath, 'wb' );
- if ( ! $fp ) {
- return false;
- }
+ // Identical bytes keep the stored file, so its mtime (the ETag and Last-Modified Apache sends) stays the same.
+ if ( '' !== $content && $this->keep_identical_file( $path, $content, (int) $expire, $w3tc_value ) ) {
+ // some hostings create files with restrictive permissions not allowing apache to read it later.
+ @chmod( $path, 0644 );
+ } else {
+ $tmppath = $path . '.' . getmypid();
- if ( $this->_locking ) {
- @flock( $fp, LOCK_EX );
- }
+ $fp = @fopen( $tmppath, 'wb' );
+ if ( ! $fp ) {
+ return false;
+ }
- @fputs( $fp, $w3tc_value['content'] );
+ if ( $this->_locking ) {
+ @flock( $fp, LOCK_EX );
+ }
- if ( $this->_locking ) {
- @fflush( $fp );
- @flock( $fp, LOCK_UN );
- }
+ @fputs( $fp, $content );
- @fclose( $fp );
+ if ( $this->_locking ) {
+ @fflush( $fp );
+ @flock( $fp, LOCK_UN );
+ }
- $chmod = 0644;
- if ( defined( 'FS_CHMOD_FILE' ) ) {
- $chmod = FS_CHMOD_FILE;
- }
+ @fclose( $fp );
+
+ $chmod = 0644;
+ if ( defined( 'FS_CHMOD_FILE' ) ) {
+ $chmod = FS_CHMOD_FILE;
+ }
- @chmod( $tmppath, $chmod );
+ @chmod( $tmppath, $chmod );
- // some hostings create files with restrictive permissions not allowing apache to read it later.
- @chmod( $path, 0644 );
+ // some hostings create files with restrictive permissions not allowing apache to read it later.
+ @chmod( $path, 0644 );
- if ( @filesize( $tmppath ) > 0 ) {
- @unlink( $path );
- @rename( $tmppath, $path );
- }
+ if ( @filesize( $tmppath ) > 0 ) {
+ @unlink( $path );
+ @rename( $tmppath, $path );
+ }
- @unlink( $tmppath );
+ @unlink( $tmppath );
+ }
$old_entry_path = $path . '_old';
@unlink( $old_entry_path );
- if ( Util_Environment::is_apache() && isset( $w3tc_value['headers'] ) ) {
+ // Runs even without header rules, so a re-cache can remove .htaccess left by an earlier write.
+ if ( Util_Environment::is_apache() ) {
$rules = '';
if ( isset( $w3tc_value['headers']['Content-Type'] ) && 'text/xml' === substr( $w3tc_value['headers']['Content-Type'], 0, 8 ) ) {
@@ -295,18 +465,23 @@
}
}
- if ( ! empty( $rules ) ) {
- $htaccess_path = dirname( $path ) . DIRECTORY_SEPARATOR . '.htaccess';
-
- $htaccess_dir = realpath( dirname( $path ) );
- $base_path = realpath( $this->_cache_dir );
- if ( false !== $htaccess_dir && false !== $base_path ) {
- $base_norm = rtrim( str_replace( '\', '/', $base_path ), '/' );
- $base_prefix = $base_norm . '/';
- $htaccess_norm = str_replace( '\', '/', $htaccess_dir );
- $htaccess_ok = ( $htaccess_norm === $base_norm || 0 === strpos( $htaccess_norm, $base_prefix ) );
+ $htaccess_path = dirname( $path ) . DIRECTORY_SEPARATOR . '.htaccess';
- if ( $htaccess_ok ) {
+ $htaccess_dir = realpath( dirname( $path ) );
+ $base_path = realpath( $this->_cache_dir );
+ if ( false !== $htaccess_dir && false !== $base_path ) {
+ $base_norm = rtrim( str_replace( '\', '/', $base_path ), '/' );
+ $base_prefix = $base_norm . '/';
+ $htaccess_norm = str_replace( '\', '/', $htaccess_dir );
+ $htaccess_ok = ( $htaccess_norm === $base_norm || 0 === strpos( $htaccess_norm, $base_prefix ) );
+
+ if ( $htaccess_ok ) {
+ if ( empty( $rules ) ) {
+ // No rules now: drop the file an earlier write left, so its stale headers stop applying.
+ if ( file_exists( $htaccess_path ) && ! $this->is_pgcache_rules_file( $htaccess_path ) ) {
+ @unlink( $htaccess_path );
+ }
+ } else {
@file_put_contents( $htaccess_path, $rules );
$chmod = 0644;
@@ -324,6 +499,27 @@
}
/**
+ * Checks whether a .htaccess file holds the page cache rules block.
+ *
+ * On multisite each site's home page is cached in the folder that also holds that site's page cache rules.
+ *
+ * @since 2.11.1
+ *
+ * @param string $htaccess_path Path to the .htaccess file.
+ *
+ * @return bool
+ */
+ private function is_pgcache_rules_file( $htaccess_path ) {
+ if ( ! defined( 'W3TC_MARKER_BEGIN_PGCACHE_CACHE' ) ) {
+ return false;
+ }
+
+ $contents = @file_get_contents( $htaccess_path );
+
+ return is_string( $contents ) && false !== strpos( $contents, W3TC_MARKER_BEGIN_PGCACHE_CACHE );
+ }
+
+ /**
* Escape header name
*
* @param string $v Value.
--- a/w3-total-cache/Cache_Memcache.php
+++ b/w3-total-cache/Cache_Memcache.php
@@ -482,18 +482,29 @@
}
/**
+ * Constructs the key version key for a cache group.
+ *
+ * @since 2.11.1
+ *
+ * @param string $w3tc_group Cache group. Default is an empty string.
+ *
+ * @return string
+ */
+ protected function _get_key_version_key( $w3tc_group = '' ) {
+ return $this->get_fixed_length_key_version_key( $w3tc_group );
+ }
+
+ /**
* Generates a unique storage key for a given cache item.
*
- * The key includes the instance ID, host, blog ID, module, and an MD5 hash of the item name. Spaces in the name are sanitized
- * to ensure compatibility with Memcache.
+ * The key is a fixed-length hash of the instance ID, host, blog ID, module, and item name. See
+ * Cache_Base::get_fixed_length_item_key().
*
* @param string $w3tc_name The name of the cache item.
*
* @return string The unique storage key for the cache item.
*/
public function get_item_key( $w3tc_name ) {
- // memcached doesn't survive spaces in a key.
- $w3tc_key = sprintf( 'w3tc_%d_%s_%d_%s_%s', $this->_instance_id, $this->_host, $this->_blog_id, $this->_module, md5( $w3tc_name ) );
- return $w3tc_key;
+ return $this->get_fixed_length_item_key( $w3tc_name );
}
}
--- a/w3-total-cache/Cache_Memcached.php
+++ b/w3-total-cache/Cache_Memcached.php
@@ -665,19 +665,29 @@
}
/**
+ * Constructs the key version key for a cache group.
+ *
+ * @since 2.11.1
+ *
+ * @param string $w3tc_group Cache group. Default is an empty string.
+ *
+ * @return string
+ */
+ protected function _get_key_version_key( $w3tc_group = '' ) {
+ return $this->get_fixed_length_key_version_key( $w3tc_group );
+ }
+
+ /**
* Generates a unique Memcached key for the given item name.
*
- * This method generates a unique key for an item to be stored in Memcached. The key is constructed using various instance-specific
- * properties (e.g., instance ID, host, blog ID, module) combined with the md5 hash of the item name. This ensures that keys are
- * unique and can safely be used in a multi-instance or multi-module environment.
+ * The key is a fixed-length hash of the instance ID, host, blog ID, module, and item name. See
+ * Cache_Base::get_fixed_length_item_key().
*
* @param string $w3tc_name The item name to generate a key for.
*
* @return string The generated unique Memcached key.
*/
public function get_item_key( $w3tc_name ) {
- // memcached doesn't survive spaces in a key.
- $w3tc_key = sprintf( 'w3tc_%d_%s_%d_%s_%s', $this->_instance_id, $this->_host, $this->_blog_id, $this->_module, md5( $w3tc_name ) );
- return $w3tc_key;
+ return $this->get_fixed_length_item_key( $w3tc_name );
}
}
--- a/w3-total-cache/Cache_Nginx_Memcached.php
+++ b/w3-total-cache/Cache_Nginx_Memcached.php
@@ -13,6 +13,7 @@
* PECL Memcached class
*
* phpcs:disable PSR2.Classes.PropertyDeclaration.Underscore
+ * phpcs:disable PSR2.Methods.MethodDeclaration.Underscore
* phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
* phpcs:disable Universal.CodeAnalysis.ConstructorDestructorReturn.ReturnValueFound
*/
@@ -409,19 +410,29 @@
}
/**
+ * Constructs the key version key for a cache group.
+ *
+ * @since 2.11.1
+ *
+ * @param string $w3tc_group Cache group. Default is an empty string.
+ *
+ * @return string
+ */
+ protected function _get_key_version_key( $w3tc_group = '' ) {
+ return $this->get_fixed_length_key_version_key( $w3tc_group );
+ }
+
+ /**
* Generates a unique storage key for a given name.
*
- * This method generates a unique key for an item in Memcached by including the instance ID, host, blog ID, module, and a
- * hashed version of the provided name. Memcached keys cannot contain spaces, so this method ensures the key format is valid
- * for Memcached.
+ * The key is a fixed-length hash of the instance ID, host, blog ID, module, and item name. See
+ * Cache_Base::get_fixed_length_item_key().
*
* @param string $w3tc_name The name for which to generate a unique key.
*
* @return string The generated storage key.
*/
public function get_item_key( $w3tc_name ) {
- // memcached doesn't survive spaces in a key.
- $w3tc_key = sprintf( 'w3tc_%d_%s_%d_%s_%s', $this->_instance_id, $this->_host, $this->_blog_id, $this->_module, md5( $w3tc_name ) );
- return $w3tc_key;
+ return $this->get_fixed_length_item_key( $w3tc_name );
}
}
--- a/w3-total-cache/Cache_Redis.php
+++ b/w3-total-cache/Cache_Redis.php
@@ -84,6 +84,60 @@
private $_read_timeout;
/**
+ * Seconds to skip a server after a failed connect or command.
+ *
+ * @since 2.11.1
+ *
+ * @var int
+ */
+ const BYPASS_SECONDS = 30;
+
+ /**
+ * Seconds a server stays held after a replay claim was seen, before the claim is checked again.
+ *
+ * @since 2.11.1
+ *
+ * @var int
+ */
+ const HOLD_RECHECK_SECONDS = 2;
+
+ /**
+ * When each held server was last found claimed, keyed by server index.
+ *
+ * @since 2.11.1
+ *
+ * @var array<int,int>
+ */
+ private $_held_since = array();
+
+ /**
+ * Process-local bypass expiry, keyed by server and database.
+ *
+ * @since 2.11.1
+ *
+ * @var array<string,int>
+ */
+ private static $bypass_until = array();
+
+ /**
+ * Directory for the cross-request bypass files. Tests set this.
+ *
+ * @since 2.11.1
+ *
+ * @var string|null
+ */
+ public static $bypass_directory = null;
+
+ /**
+ * Optional factory for the Redis client. Tests set this.
+ *
+ * @since 2.11.1
+ *
+ * @var callable|null
+ */
+ public static $client_factory = null;
+
+ /**
* Constructor.
*
* @param array $w3tc_config Config.
@@ -96,9 +150,9 @@
$this->_verify_tls_certificates = self::verify_tls_certificates_enabled( $w3tc_config );
$this->_password = $w3tc_config['password'];
$this->_dbid = $w3tc_config['dbid'];
- $this->_timeout = $w3tc_config['timeout'] ?? 3600000;
+ $this->_timeout = self::fail_fast_seconds( $w3tc_config['timeout'] ?? 0 );
$this->_retry_interval = $w3tc_config['retry_interval'] ?? 3600000;
- $this->_read_timeout = $w3tc_config['read_timeout'] ?? 60.0;
+ $this->_read_timeout = self::fail_fast_seconds( $w3tc_config['read_timeout'] ?? 0 );
/**
* When disabled - no extra requests are made to obtain key version,
@@ -283,8 +337,11 @@
public function delete( $w3tc_key, $w3tc_group = '' ) {
$storage_key = $this->get_item_key( $w3tc_key );
$accessor = $this->_get_accessor( $storage_key );
+ $op = $this->_use_expired_data ? 'delete_expired' : 'delete';
if ( is_null( $accessor ) ) {
+ // Queue the invalidation so recovery applies it before any read.
+ $this->queue_invalidation( $storage_key, $op, $w3tc_group );
return false;
}
@@ -292,14 +349,29 @@
$v = $accessor->get( $storage_key );
$ttl = $accessor->ttl( $storage_key );
- if ( is_array( $v ) ) {
+ if ( is_array( $v ) && ! $this->accessor_failed( $accessor ) ) {
$v['key_version'] = 0;
- $accessor->setex( $storage_key, $ttl, $v );
- return true;
+ $wrote = $accessor->setex( $storage_key, $ttl, $v );
+
+ if ( false !== $wrote && ! $this->accessor_failed( $accessor ) ) {
+ return true;
+ }
+
+ $this->mark_bypass_unless_failed( $accessor, $storage_key );
+ $this->queue_invalidation( $storage_key, $op, $w3tc_group );
+ return false;
}
}
- return $accessor->setex( $storage_key, 1, '' );
+ $wrote = $accessor->setex( $storage_key, 1, '' );
+
+ if ( false === $wrote || $this->accessor_failed( $accessor ) ) {
+ $this->mark_bypass_unless_failed( $accessor, $storage_key );
+ $this->queue_invalidation( $storage_key, $op, $w3tc_group );
+ return false;
+ }
+
+ return true;
}
/**
@@ -314,10 +386,19 @@
$accessor = $this->_get_accessor( $storage_key );
if ( is_null( $accessor ) ) {
+ $this->queue_invalidation( $storage_key, 'hard_delete', $w3tc_group );
return false;
}
- return $accessor->setex( $storage_key, 1, '' );
+ $wrote = $accessor->setex( $storage_key, 1, '' );
+
+ if ( false === $wrote || $this->accessor_failed( $accessor ) ) {
+ $this->mark_bypass_unless_failed( $accessor, $storage_key );
+ $this->queue_invalidation( $storage_key, 'hard_delete', $w3tc_group );
+ return false;
+ }
+
+ return true;
}
/**
@@ -330,9 +411,15 @@
$this->_get_key_version( $w3tc_group ); // Initialize $this->_key_version.
if ( isset( $this->_key_version[ $w3tc_group ] ) ) {
++$this->_key_version[ $w3tc_group ];
- $this->_set_key_version( $this->_key_version[ $w3tc_group ], $w3tc_group );
+
+ if ( $this->_set_key_version( $this->_key_version[ $w3tc_group ], $w3tc_group ) ) {
+ return true;
+ }
}
+ // No live server: queue the group so recovery moves its version on.
+ $this->queue_invalidation( $this->_get_key_version_key( $w3tc_group ), 'flush', $w3tc_group );
+
return true;
}
@@ -363,7 +450,9 @@
public function flush_group_after_ahead_generation( $w3tc_group, $w3tc_extension ) {
$v = $this->_get_key_version( $w3tc_group );
if ( $w3tc_extension['key_version'] > $v ) {
- $this->_set_key_version( $w3tc_extension['key_version'], $w3tc_group );
+ if ( ! $this->_set_key_version( $w3tc_extension['key_version'], $w3tc_group ) ) {
+ $this->queue_invalidation( $this->_get_key_version_key( $w3tc_group ), 'flush', $w3tc_group );
+ }
}
}
@@ -409,8 +498,13 @@
}
$v_original = $accessor->get( $storage_key );
- $v = intval( $v_original );
- $v = ( $v > 0 ? $v : 1 );
+
+ if ( method_exists( $accessor, 'is_failed' ) && $accessor->is_failed() ) {
+ return 0;
+ }
+
+ $v = intval( $v_original );
+ $v = ( $v > 0 ? $v : 1 );
if ( (string) $v_original !== (string) $v ) {
$accessor->set( $storage_key, $v );
@@ -437,12 +531,50 @@
return false;
}
- $accessor->set( $storage_key, $v );
+ $wrote = $accessor->set( $storage_key, $v );
+
+ if ( false === $wrote || $this->accessor_failed( $accessor ) ) {
+ $this->mark_bypass_unless_failed( $accessor, $storage_key );
+ return false;
+ }
return true;
}
/**
+ * Whether the guarded client already failed a command.
+ *
+ * @since 2.11.1
+ *
+ * @param object $accessor Redis client.
+ * @return bool
+ */
+ private function accessor_failed( $accessor ) {
+ return method_exists( $accessor, 'is_failed' ) && $accessor->is_failed();
+ }
+
+ /**
+ * Skip the server when a write failed without the guard noticing.
+ *
+ * @since 2.11.1
+ *
+ * @param object $accessor Redis client.
+ * @param string $storage_key Storage key.
+ * @return void
+ */
+ private function mark_bypass_unless_failed( $accessor, $storage_key ) {
+ if ( $this->accessor_failed( $accessor ) ) {
+ return;
+ }
+
+ $server = $this->server_for_key( $storage_key );
+
+ if ( null !== $server ) {
+ self::mark_server_bypassed( $server, $this->_dbid );
+ }
+ }
+
+ /**
* Used to replace as atomically as possible known value to new one.
*
* @param string $w3tc_key Key.
@@ -698,7 +830,7 @@
$connect_args[] = $port;
}
- $connect_args[] = $this->_timeout;
+ $connect_args[] = self::fail_fast_seconds( $this->_timeout );
$connect_args[] = $this->_persistent ? $this->_instance_id . '_' . $this->_dbid : null;
$connect_args[] = $this->_retry_interval;
@@ -706,7 +838,7 @@
// The read_timeout parameter was added in phpredis 3.1.3.
if ( version_compare( $phpredis_version, '3.1.3', '>=' ) ) {
- $connect_args[] = $this->_read_timeout;
+ $connect_args[] = self::fail_fast_seconds( $this->_read_timeout );
}
// Support for stream context was added in phpredis 5.3.2.
@@ -720,8 +852,13 @@
/**
* Get accessor.
*
+ * A stored false means the server is held because another worker is
+ * replaying its queue. It is returned as null. The claim is checked again
+ * after HOLD_RECHECK_SECONDS, so a long-running process such as WP-CLI or
+ * cron does not stay off the server once the replay ends.
+ *
* @param string $w3tc_key Key.
- * @return object
+ * @return object|null
*/
private function _get_accessor( $w3tc_key ) {
if ( count( $this->_servers ) <= 1 ) {
@@ -731,37 +868,1107 @@
}
if ( isset( $this->_accessors[ $w3tc_index ] ) ) {
- return $this->_accessors[ $w3tc_index ];
+ $cached = $this->_accessors[ $w3tc_index ];
+
+ if ( false === $cached ) {
+ // Another worker is replaying the queue. Stay off this server until the next check.
+ $held_since = isset( $this->_held_since[ $w3tc_index ] ) ? $this->_held_since[ $w3tc_index ] : 0;
+
+ if ( time() - $held_since < self::HOLD_RECHECK_SECONDS ) {
+ return null;
+ }
+ } elseif (
+ ! method_exists( $cached, 'is_failed' ) ||
+ ! $cached->is_failed() ||
+ self::is_server_bypassed( $this->_servers[ $w3tc_index ], $this->_dbid )
+ ) {
+ return $cached;
+ }
+
+ unset( $this->_accessors[ $w3tc_index ] );
}
if ( ! isset( $this->_servers[ $w3tc_index ] ) ) {
$this->_accessors[ $w3tc_index ] = null;
} else {
- try {
- $server = $this->_servers[ $w3tc_index ];
- $connect_args = $this->build_connect_args( $server );
+ $server = $this->_servers[ $w3tc_index ];
- $accessor = new Redis();
+ $pending = self::pending_path( $server, $this->_dbid );
- if ( $this->_persistent ) {
- $accessor->pconnect( ...$connect_args );
- } else {
- $accessor->connect( ...$connect_args );
+ if ( self::is_server_bypassed( $server, $this->_dbid ) ) {
+ $accessor = null;
+ } elseif ( self::replay_claim_exists( $pending ) ) {
+ // Another worker is applying the queue. Do not connect or read yet.
+ $accessor = false;
+ } else {
+ try {
+ $connect_args = $this->build_connect_args( $server );
+ $accessor = $this->new_redis_client();
+
+ if ( $this->_persistent ) {
+ $accessor->pconnect( ...$connect_args );
+ } else {
+ $accessor->connect( ...$connect_args );
+ }
+
+ $ready = ( empty( $this->_password ) || false !== $accessor->auth( $this->_password ) )
+ && false !== $accessor->select( $this->_dbid );
+
+ // Queued invalidations apply before this connection serves any read.
+ if ( $ready && $this->replay_queued_invalidations( $accessor, $server ) ) {
+ self::clear_server_bypass( $server, $this->_dbid );
+ $accessor = $this->guard_client( $accessor, $server );
+ } elseif ( $ready && self::replay_claim_exists( $pending ) ) {
+ // Another request took the queue while this one connected. Do not read yet.
+ $accessor = false;
+ } else {
+ error_log( __METHOD__ . ': AUTH, SELECT, or queued replay failed for database ' . $this->_dbid ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
+ self::mark_server_bypassed( $server, $this->_dbid );
+ $accessor = null;
+ }
+ } catch ( Exception $e ) {
+ error_log( __METHOD__ . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
+ self::mark_server_bypassed( $server, $this->_dbid );
+ $accessor = null;
}
+ }
+
+ $this->_accessors[ $w3tc_index ] = $accessor;
+
+ if ( false === $accessor ) {
+ $this->_held_since[ $w3tc_index ] = time();
+ }
+ }
+
+ return false === $this->_accessors[ $w3tc_index ] ? null : $this->_accessors[ $w3tc_index ];
+ }
- if ( ! empty( $this->_password ) ) {
- $accessor->auth( $this->_password );
+ /**
+ * A configured timeout of 0 waits forever. Use one second instead.
+ *
+ * @since 2.11.1
+ *
+ * @param mixed $timeout Configured seconds.
+ * @return float
+ */
+ public static function fail_fast_seconds( $timeout ) {
+ $timeout = (float) $timeout;
+
+ return $timeout > 0 ? $timeout : 1.0;
+ }
+
+ /**
+ * Drop Redis engine and connection changes that did not answer a probe.
+ *
+ * Unchanged Redis connection settings are left alone so an outage does
+ * not block saving unrelated settings. A failed probe restores the
+ * previous engine and every Redis connection setting for that module,
+ * so old servers are never paired with new credentials or options.
+ *
+ * @since 2.11.1
+ *
+ * @param object $new_config New config.
+ * @param object|null $old_config Previous config.
+ * @param callable|null $probe Optional probe ( $servers, $module ) : bool.
+ * @return string[] Module names that were reverted.
+ */
+ public static function enforce_verified_servers( $new_config, $old_config, $probe = null ) {
+ // Out of scope: the fragment cache extension keeps its Redis settings in a nested extension config that connection_settings() does not read, so it is not probed.
+ $modules = array( 'dbcache', 'objectcache', 'pgcache', 'minify' );
+ $reverted = array();
+
+ foreach ( $modules as $module ) {
+ $engine_key = $module . '.engine';
+
+ if ( 'redis' !== (string) $new_config->get_string( $engine_key ) ) {
+ continue;
+ }
+
+ $new_settings = self::connection_settings( $new_config, $module );
+ $old_engine = $old_config ? (string) $old_config->get_string( $engine_key ) : '';
+ $old_settings = $old_config ? self::connection_settings( $old_config, $module ) : array();
+
+ if ( 'redis' === $old_engine && $new_settings === $old_settings ) {
+ continue;
+ }
+
+ $new_servers = $new_settings[ $module . '.redis.servers' ];
+
+ if ( null === $probe ) {
+ $ok = self::probe_servers(
+ $new_servers,
+ $new_settings[ $module . '.redis.password' ],
+ $new_settings[ $module . '.redis.dbid' ],
+ $new_settings[ $module . '.redis.verify_tls_certificates' ],
+ $new_settings[ $module . '.redis.timeout' ],
+ $new_settings[ $module . '.redis.read_timeout' ]
+ );
+ } else {
+ $ok = (bool) call_user_func( $probe, $new_servers, $module );
+ }
+
+ if ( $ok ) {
+ continue;
+ }
+
+ if ( $old_config ) {
+ $new_config->set( $engine_key, $old_engine );
+
+ foreach ( $old_settings as $key => $value ) {
+ $new_config->set( $key, $value );
}
+ }
+
+ $reverted[] = $module;
+ }
+
+ return $reverted;
+ }
+
+ /**
+ * Redis connection settings for one module, keyed by config key.
+ *
+ * @since 2.11.1
+ *
+ * @param object $config Config.
+ * @param string $module Module prefix.
+ * @return array
+ */
+ private static function connection_settings( $config, $module ) {
+ $prefix = $module . '.redis.';
+
+ return array(
+ $prefix . 'servers' => $config->get_array( $prefix . 'servers' ),
+ $prefix . 'password' => (string) $config->get_string( $prefix . 'password' ),
+ $prefix . 'dbid' => $config->get_integer( $prefix . 'dbid' ),
+ $prefix . 'verify_tls_certificates' => $config->get_boolean( $prefix . 'verify_tls_certificates', true ),
+ $prefix . 'persistent' => $config->get_boolean( $prefix . 'persistent' ),
+ $prefix . 'timeout' => $config->get_integer( $prefix . 'timeout' ),
+ $prefix . 'retry_interval' => $config->get_integer( $prefix . 'retry_interval' ),
+ $prefix . 'read_timeout' => $config->get_integer( $prefix . 'read_timeout' ),
+ );
+ }
- $accessor->select( $this->_dbid );
+ /**
+ * Connect and write a short-lived key. False when any server fails.
+ *
+ * Any bypass for the server is cleared before and after the probe, so a
+ * recovered server is actually tried and a rejected save does not skip
+ * the settings still in use.
+ *
+ * @since 2.11.1
+ *
+ * @param array $servers Server strings.
+ * @param string $password Password.
+ * @param mixed $dbid Database id.
+ * @param bool $verify_tls_certificates Whether to verify TLS certificates.
+ * @param mixed $timeout Connect timeout; 0 uses one second.
+ * @param mixed $read_timeout Read timeout; 0 uses one second.
+ * @return bool
+ */
+ public static function probe_servers( $servers, $password, $dbid, $verify_tls_certificates = true, $timeout = 0, $read_timeout = 0 ) {
+ if ( ! is_callable( self::$client_factory ) && ! class_exists( 'Redis' ) ) {
+ return false;
+ }
+
+ foreach ( (array) $servers as $server ) {
+ $server = trim( (string) $server );
+
+ if ( '' === $server ) {
+ return false;
+ }
+
+ self::clear_server_bypass( $server, $dbid );
+
+ try {
+ $cache = new self(
+ array(
+ 'blog_id' => 0,
+ 'servers' => array( $server ),
+ 'persistent' => false,
+ 'password' => (string) $password,
+ 'dbid' => $dbid,
+ 'timeout' => self::fail_fast_seconds( $timeout ),
+ 'retry_interval' => 0,
+ 'read_timeout' => self::fail_fast_seconds( $read_timeout ),
+ 'verify_tls_certificates' => (bool) $verify_tls_certificates,
+ )
+ );
+ $wrote = $cache->set( 'w3tc_redis_probe', array( 'content' => '1' ), 30 );
+ } catch ( Exception $e ) {
+ $wrote = false;
+ }
+
+ /**
+ * The marker is keyed by server and database only, so a rejected
+ * edit must not leave it behind for the configuration still in use.
+ */
+ self::clear_server_bypass( $server, $dbid );
+
+ if ( ! $wrote ) {
+ return false;
+ }
+ }
+
+ return ! empty( $servers );
+ }
+
+ /**
+ * Forget process-local test overrides.
+ *
+ * @since 2.11.1
+ *
+ * @return void
+ */
+ public static function reset_runtime_state() {
+ self::$bypass_until = array();
+ self::$bypass_directory = null;
+ self::$client_factory = null;
+ }
+
+ /**
+ * Whether this server should be skipped until the probe window ends.
+ *
+ * @since 2.11.1
+ *
+ * @param string $server Server URI.
+ * @param mixed $dbid Database id.
+ * @return bool
+ */
+ public static function is_server_bypassed( $server, $dbid ) {
+ $key = self::bypass_key( $server, $dbid );
+ $until = isset( self::$bypass_until[ $key ] ) ? (int) self::$bypass_until[ $key ] : 0;
+
+ if ( $until > time() ) {
+ return true;
+ }
+
+ $path = self::bypass_path( $server, $dbid );
+
+ if ( '' === $path || ! is_file( $path ) ) {
+ return false;
+ }
+
+ // Concurrent requests may remove the file between these calls.
+ $until = (int) @file_get_contents( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents, WordPress.PHP.NoSilencedErrors.Discouraged
+
+ if ( $until > time() ) {
+ self::$bypass_until[ $key ] = $until;
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Skip this server for BYPASS_SECONDS.
+ *
+ * @since 2.11.1
+ *
+ * @param string $server Server URI.
+ * @param mixed $dbid Database id.
+ * @return void
+ */
+ public static function mark_server_bypassed( $server, $dbid ) {
+ $key = self::bypass_key( $server, $dbid );
+ $until = time() + self::BYPASS_SECONDS;
+
+ self::$bypass_until[ $key ] = $until;
+
+ $path = self::bypass_path( $server, $dbid );
+
+ if ( '' === $path ) {
+ return;
+ }
+
+ $dir = dirname( $path );
+
+ if ( ! is_dir( $dir ) ) {
+ @mkdir( $dir, 0755, true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir, WordPress.PHP.NoSilencedErrors.Discouraged
+ }
+
+ if ( is_dir( $dir ) && is_writable( $dir ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
+ @file_put_contents( $path, (string) $until, LOCK_EX ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPress.PHP.NoSilencedErrors.Discouraged
+ }
+ }
+
+ /**
+ * Allow this server to be used again.
+ *
+ * @since 2.11.1
+ *
+ * @param string $server Server URI.
+ * @param mixed $dbid Database id.
+ * @return void
+ */
+ public static function clear_server_bypass( $server, $dbid ) {
+ unset( self::$bypass_until[ self::bypass_key( $server, $dbid ) ] );
+
+ $path = self::bypass_path( $server, $dbid );
+
+ if ( '' !== $path && is_file( $path ) ) {
+ @unlink( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink, WordPress.PHP.NoSilencedErrors.Discouraged
+ }
+ }
+
+ /**
+ * Key for one server and database.
+ *
+ * @param string $server Server URI.
+ * @param mixed $dbid Database id.
+ * @return string
+ */
+ private static function bypass_key( $server, $dbid ) {
+ return md5( (string) $server . '|' . (string) $dbid );
+ }
+
+ /**
+ * Path of the cross-request bypass file.
+ *
+ * @param string $server Server URI.
+ * @param mixed $dbid Database id.
+ * @return string
+ */
+ private static function bypass_path( $server, $dbid ) {
+ $dir = self::$bypass_directory;
+
+ if ( ! is_string( $dir ) || '' === $dir ) {
+ if ( defined( 'W3TC_CACHE_DIR' ) ) {
+ $dir = W3TC_CACHE_DIR;
+ } else {
+ $dir = defined( 'WP_CONTENT_DIR' ) ? WP_CONTENT_DIR . '/cache' : '';
+ }
+ }
+
+ if ( '' === $dir ) {
+ return '';
+ }
+
+ return $dir . '/w3tc-redis-bypass-' . self::bypass_key( $server, $dbid );
+ }
+
+ /**
+ * Queue file size above which the queue collapses to one group version bump per engine.
+ *
+ * @since 2.11.1
+ */
+ const PENDING_MAX_BYTES = 1048576;
+
+ /**
+ * Age after which a replay claim belongs to a crashed worker and is adopted.
+ *
+ * Longer than a live replay of a queue near PENDING_MAX_BYTES. BYPASS_SECONDS
+ * is the post-failure skip window and is not used for claim ownership.
+ *
+ * @since 2.11.1
+ */
+ const REPLAY_CLAIM_MAX_AGE = 300;
+
+ /**
+ * Path of the cross-request queue of invalidations skipped during a bypass.
+ *
+ * @since 2.11.1
+ *
+ * @param string $server Server URI.
+ * @param mixed $dbid Database id.
+ * @return string
+ */
+ private static function pending_path( $server, $dbid ) {
+ $path = self::bypass_path( $server, $dbid );
+
+ if ( '' === $path ) {
+ return '';
+ }
+
+ return dirname( $path ) . '/w3tc-redis-pending-' . self::bypass_key( $server, $dbid );
+ }
+
+ /**
+ * Replay claims for a pending queue, live or abandoned.
+ *
+ * @since 2.11.1
+ *
+ * @param string $path Pending queue path.
+ * @param bool $stale True for claims older than REPLAY_CLAIM_MAX_AGE, false for live claims.
+ * @return string[]
+ */
+ private static function replay_claims( $path, $stale ) {
+ if ( '' === $path || ! is_dir( dirname( $path ) ) ) {
+ return array();
+ }
+
+ $matches = glob( $path . '.replay-*' );
+
+ if ( ! is_array( $matches ) ) {
+ return array();
+ }
+
+ $cutoff = time() - self::REPLAY_CLAIM_MAX_AGE;
+
+ return array_values(
+ array_filter(
+ $matches,
+ function ( $file ) use ( $stale, $cutoff ) {
+ $size = @filesize( $file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
+
+ // An empty claim holds no entries, so it never blocks a read.
+ $is_stale = ( self::replay_claim_last_seen( $file ) <= $cutoff ) || ( false === $size ) || ( 0 === $size );
+
+ return $stale === $is_stale;
+ }
+ )
+ );
+ }
+
+ /**
+ * Last time a replay claim was alive: the later of its file time and the time in its name.
+ *
+ * The name carries the creation time, so a claim is live from the moment it is renamed. A claim
+ * is refreshed by each applied entry. A stalled claim ages out after REPLAY_CLAIM_MAX_AGE.
+ *
+ * @since 2.11.1
+ *
+ * @param string $file Claim path.
+ * @return int
+ */
+ private static function replay_claim_last_seen( $file ) {
+ $mtime = @filemtime( $file ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
+ $last = false === $mtime ? 0 : (int) $mtime;
+
+ if ( preg_match( '~.replay-d+-([0-9a-f]{8})~', basename( $file ), $matches ) ) {
+ $last = max( $last, (int) hexdec( $matches[1] ) );
+ }
+
+ return $last;
+ }
+
+ /**
+ * Claim path for a pending queue, named with the time it counts from.
+ *
+ * @since 2.11.1
+ *
+ * @param string $path Pending queue path.
+ * @param int|null $time Unix time to record in the name, or null for now.
+ * @return string
+ */
+ private static function claim_path( $path, $time = null ) {
+ if ( null === $time ) {
+ return $path . '.replay-' . getmypid() . '-' . uniqid( '', true );
+ }
+
+ return $path . '.replay-' . getmypid() . '-' . sprintf( '%08x00000', (int) $time ) . '.' . uniqid( '', true );
+ }
+
+ /**
+ * Whether another worker holds a live replay claim.
+ *
+ * A claim younger than REPLAY_CLAIM_MAX_AGE is never taken over, so a slow
+ * replay keeps its queue. Readers get a null accessor while it runs.
+ *
+ * @since 2.11.1
+ *
+ * @param string $path Pending queue path.
+ * @return bool
+ */
+ private static function replay_claim_exists( $path ) {
+ return array() !== self::replay_claims( $path, false );
+ }
+
+ /**
+ * Server that owns a storage key, mirroring _get_accessor().
+ *
+ * @since 2.11.1
+ *
+ * @param string $storage_key Storage key.
+ * @return string|null
+ */
+ private function server_for_key( $storage_key ) {
+ $count = count( $this->_servers );
+ $index = $count <= 1 ? 0 : crc32( $storage_key ) % $count;
+
+ return isset( $this->_servers[ $index ] ) ? $this->_servers[ $index ] : null;
+ }
+
+ /**
+ * Record an invalidation that could not reach Redis, for replay on recovery.
+ *
+ * @since 2.11.1
+ *
+ * @param string $storage_key Storage key, or version key for 'flush'.
+ * @param string $op One of delete, delete_expired, hard_delete, flush.
+ * @param string $group Group, for 'flush'.
+ * @return bool
+ */
+ private function queue_invalidation( $storage_key, $op, $group = '' ) {
+ $server = $this->server_for_key( $storage_key );
+
+ if ( null === $server ) {
+ return false;
+ }
+
+ $path = self::pending_path( $server, $this->_dbid );
+
+ if ( '' === $path ) {
+ return false;
+ }
+
+ $dir = dirname( $path );
+
+ if ( ! is_dir( $dir ) ) {
+ @mkdir( $dir, 0755, true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir, WordPress.PHP.NoSilencedErrors.Discouraged
+ }
+
+ if ( ! is_dir( $dir ) || ! is_writable( $dir ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
+ return false;
+ }
+
+ $version_key = 'flush' === $op ? (string) $storage_key : $this->_get_key_version_key( $group );
+
+ if ( is_file( $path ) && (int) @filesize( $path ) > self::PENDING_MAX_BYTES ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
+ $compacted = $this->compact_pending_queue( $path, $server, $version_key );
+
+ if ( null !== $compacted ) {
+ return $compacted;
+ }
+ }
+
+ if ( 'flush' === $op ) {
+ // The version key carries instance, blog, and module; the queue is shared by all of them.
+ $entry = array(
+ 'op' => 'flush',
+ 'key' => (string) $storage_key,
+ 'group' => (string) $group,
+ );
+ } else {
+ $entry = array(
+ 'op' => $op,
+ 'key' => (string) $storage_key,
+ 'vkey' => $version_key,
+ );
+ }
+
+ $line = json_encode( $entry ) . "n"; // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
+
+ return false !== @file_put_contents( $path, $line, FILE_APPEND | LOCK_EX ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPress.PHP.NoSilencedErrors.Discouraged
+ }
+
+ /**
+ * Collapse an oversized queue to one group version bump per queued version key.
+ *
+ * The whole read and rewrite runs under one exclusive lock, which appenders
+ * also take, so no concurrent entry is lost. Each bump goes to the queue of
+ * the server that owns its version key, because replay runs on that
+ * server's client.
+ *
+ * @since 2.11.1
+ *
+ * @param string $path Pending queue path.
+ * @param string $server Server URI that owns the queue.
+ * @param string $version_key Version key of the invalidation being queued.
+ * @return bool|null Null when the queue no longer needs compaction and the entry should be appended.
+ */
+ private function compact_pending_queue( $path, $server, $version_key ) {
+ $handle = @fopen( $path, 'c+' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen, WordPress.PHP.NoSilencedErrors.Discouraged
+
+ if ( false === $handle ) {
+ return false;
+ }
+
+ if ( ! flock( $handle, LOCK_EX ) ) {
+ fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
+
+ return false;
+ }
+
+ clearstatcache( true, $path );
+ $stat = fstat( $handle );
+ $current = @stat( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
+
+ // Another worker compacted it first, or a replay claimed this file and appends now start a new one.
+ if (
+ false === $stat ||
+ false === $current ||
+ $stat['ino'] !== $current['ino'] ||
+ $stat['size'] <= self::PENDING_MAX_BYTES
+ ) {
+ flock( $handle, LOCK_UN );
+ fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
+
+ return null;
+ }
+
+ $contents = (string) stream_get_contents( $handle, -1, 0 );
+ $version_keys = self::queued_version_keys( explode( "n", $contents ) );
+ $version_keys[] = $version_key;
+ $by_server = array();
+
+ foreach ( array_unique( $version_keys ) as $queued_key ) {
+ $owner = $this->server_for_key( $queued_key );
+ $owner = null === $owner ? $server : $owner;
+
+ if ( ! isset( $by_server[ $owner ] ) ) {
+ $by_server[ $owner ] = '';
+ }
+
+ $by_server[ $owner ] .= json_encode( // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
+ array(
+ 'op' => 'flush',
+ 'key' => $queued_key,
+ )
+ ) . "n";
+ }
+
+ $local = isset( $by_server[ $server ] ) ? $by_server[ $server ] : '';
+ unset( $by_server[ $server ] );
+
+ $ok = ftruncate( $handle, 0 ) && rewind( $handle );
+ $ok = $ok && ( '' === $local || strlen( $local ) === fwrite( $handle, $local ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
+ $ok = fflush( $handle ) && $ok;
+
+ flock( $handle, LOCK_UN );
+ fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
+
+ // Appended after this lock is released, so two queues are never locked at once.
+ foreach ( $by_server as $owner => $lines ) {
+ $owner_path = self::pending_path( $owner, $this->_dbid );
+
+ if ( '' === $owner_path || false === @file_put_contents( $owner_path, $lines, FILE_APPEND | LOCK_EX ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPress.PHP.NoSilencedErrors.Discouraged
+ $ok = false;
+ }
+ }
+
+ return $ok;
+ }
+
+ /**
+ * Group version keys named by the entries of a pending queue.
+ *
+ * @since 2.11.1
+ *
+ * @param string[] $lines Queue lines.
+ * @return string[]
+ */
+ private static function queued_version_keys( array $lines ) {
+ $keys = array();
+
+ foreach ( $lines as $line ) {
+ if ( '' === trim( $line ) ) {
+ continue;
+ }
+
+ $entry = json_decode( $line, true );
+
+ if ( ! is_array( $entry ) ) {
+ continue;
+ }
+
+ if ( isset( $entry['op'], $entry['key'] ) && 'flush' === $entry['op'] ) {
+ $keys[] = (string) $entry['key'];
+ } elseif ( isset( $entry['vkey'] ) ) {
+ $keys[] = (string) $entry['vkey'];
+ }
+ }
+
+ return $keys;
+ }
+
+ /**
+ * Replay queued invalidations on a freshly connected client.
+ *
+ * Each pass claims one file by rename, so a concurrent request appends to a
+ * new file. An abandoned claim is adopted before the pending queue, so older
+ * entries apply first. Entries that fail to apply are written back for the
+ * next try.
+ *
+ * @since 2.11.1
+ *
+ * @param object $redis Connected client, before any guard.
+ * @param string $server Server URI.
+ * @return bool False when the server must stay bypassed or another worker holds the queue.
+ */
+ private function replay_queued_invalidations( $redis, $server ) {
+ $path = self::pending_path( $server, $this->_dbid );
+
+ if ( '' === $path ) {
+ return true;
+ }
+
+ while ( true ) {
+ if ( self::replay_claim_exists( $path ) ) {
+ // Another worker is applying the queue. Its entries apply first.
+ return false;
+ }
+
+ $claimed = $this->claim_pending_queue( $path );
+
+ if ( null === $claimed ) {
+ // Nothing is queued, unless another worker just took the queue.
+ return ! self::replay_claim_exists( $path );
+ }
+
+ if ( false === $claimed ) {
+ return false;
+ }
+
+ $lines = self::read_claim_lines( $claimed );
+ $applied = 0;
+
+ try {
+ foreach ( $lines as $line ) {
+ $entry = json_decode( $line, true );
+
+ if ( is_array( $entry ) && ! $this->apply_queued_invalidation( $redis, $entry ) ) {
+ break;
+ }
+
+ ++$applied;
+
+ // Progress keeps the claim live. Only a replay that stalls goes stale. Never re-create a claim that was moved away.
+ if ( is_file( $claimed ) ) {
+ @touch( $claimed ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_touch, WordPress.PHP.NoSilencedErrors.Discouraged
+ }
+ }
} catch ( Exception $e ) {
error_log( __METHOD__ . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
- $accessor = null;
}
- $this->_accessors[ $w3tc_index ] = $accessor;
+ if ( $applied < count( $lines ) ) {
+ // Keep the unapplied tail as an abandoned claim. The next request adopts it before any newer entries.
+ $rest = implode( "n", array_slice( $lines, $applied ) ) . "n";
+ $this->abandon_claim( $path, $claimed, $rest );
+
+ return false;
+ }
+
+ // The replay applied. A claim that cannot be removed is emptied, so its entries never apply again.
+ if (
+ ! @unlink( $claimed ) && // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink, WordPress.PHP.NoSilencedErrors.Discouraged
+ is_file( $claimed ) &&
+ false === @file_put_contents( $claimed, '', LOCK_EX ) // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPress.PHP.NoSilencedErrors.Discouraged
+ ) {
+ // Neither worked. The next request adopts it; stop here so this one does not replay it again.
+ $this->abandon_claim( $path, $claimed );
+ $this->_key_version = array();
+
+ return true;
+ }
+
+ // In-process version cache may be behind Redis after replay.
+ $this->_key_version = array();
+ }
+ }
+
+ /**
+ * Lines of a claimed queue, read after any compaction that held the file finishes.
+ *
+ * @since 2.11.1
+ *
+ * @param string $claimed Claim path.
+ * @return string[]
+ */
+ private static function read_claim_lines( $claimed ) {
+ $handle = @fopen( $claimed, 'r' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen, WordPress.PHP.NoSilencedErrors.Discouraged
+
+ if ( false === $handle ) {
+ return array();
}
- return $this->_accessors[ $w3tc_index ];
+ flock( $handle, LOCK_SH );
+ $contents = (string) stream_get_contents( $handle );
+ flock( $handle, LOCK_UN );
+ fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
+
+ return array_values(
+ array_filter(
+ explode( "n", $contents ),
+ function ( $line ) {
+ return '' !== trim( $line );
+ }
+ )
+ );
+ }
+
+ /**
+ * Claim the next file to replay: an abandoned claim first, then the pending queue.
+ *
+ * @since 2.11.1
+ *
+ * @param string $path Pending queue path.
+ * @return string|false|null Claimed path, false when another request won the claim, null when nothing is queued.
+ */
+ private function claim_pending_queue( $path ) {
+ $sources = self::replay_claims( $path, true );
+
+ // Oldest abandoned claim first, so earlier entries apply first.
+ usort(
+ $sources,
+ function ( $a, $b ) {
+ return self::replay_claim_last_seen( $a ) - self::replay_claim_last_seen( $b );
+ }
+ );
+
+ if ( is_file( $path ) ) {
+ $sources[] = $path;
+ }
+
+ foreach ( $sources as $source ) {
+ // The claim name carries the current time, so the claim is live as soon as rename() succeeds.
+ $claimed = self::claim_path( $path );
+
+ if ( @rename( $source, $claimed ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename, WordPress.PHP.NoSilencedErrors.Discouraged
+ return $claimed;
+ }
+
+ // An emptied claim that cannot be moved holds nothing to replay. Anything else is held by another request.
+ if ( $source === $path || ! is_file( $source ) || 0 !== (int) @filesize( $source ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
+ return false;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Make a claim abandoned so the next request adopts it before newer entries.
+ *
+ * With a tail, the unapplied entries are written to a new claim with an old
+ * time, so no write goes to a path another worker may have moved. Without one,
+ * the claim is renamed to an old time. If that fails, the claim is emptied.
+ *
+ * @since 2.11.1
+ *
+ * @param string $path Pending queue path.
+ * @param string $claimed Claim path.
+ * @param string $rest Unapplied entries, or empty.
+ * @return void
+ */
+ private function abandon_claim( $path, $claimed, $rest = '' ) {
+ $old = time() - self::REPLAY_CLAIM_MAX_AGE - 1;
+
+ if ( '' !== $rest ) {
+ $tail = self::claim_path( $path, $old );
+
+ if ( false === @file_put_contents( $tail, $rest, LOCK_EX ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPress.PHP.NoSilencedErrors.Discouraged
+ // Keep the claim as is, so the unapplied entries are not lost.
+ return;
+ }
+
+ @touch( $tail, $old ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_touch, WordPress.PHP.NoSilencedErrors.Discouraged
+
+ if ( ! @unlink( $claimed ) && is_file( $claimed ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink, WordPress.PHP.NoSilencedErrors.Discouraged
+ // Applied entries must not stay live in the old claim.
+ @file_put_contents( $claimed, '', LOCK_EX ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPress.PHP.NoSilencedErrors.Discouraged
+ }
+
+ return;
+ }
+
+ if ( ! @rename( $claimed, self::claim_path( $path, $old ) ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename, WordPress.PHP.NoSilencedErrors.Discouraged
+ if ( is_file( $claimed ) ) {
+ @file_put_contents( $claimed, '', LOCK_EX ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents, WordPress.PHP.NoSilencedErrors.Discouraged
+ }
+ }
+ }
+
+ /**
+ * Apply one queued invalidation.
+ *
+ * @since 2.11.1
+ *
+ * @param object $redis Connected client.
+ * @param array $entry Decoded queue line.
+ * @return bool False when the command did not succeed.
+ */
+ private function apply_queued_invalidation( $redis, array $entry ) {
+ $op = isset( $entry['op'] ) ? $entry['op'] : '';
+
+ if ( 'flush' === $op ) {
+ $version_key = isset( $entry['key'] )
+ ? (string) $entry['key']
+ : $this->_get_key_version_key( isset( $entry['group'] ) ? (string) $entry['group'] : '' );
+ $v = intval( $redis->get( $version_key ) );
+ $v = $v > 0 ? $v : 1;
+
+ return false !== $redis->set( $version_key, $v + 1 );
+ }
+
+ if ( ! isset( $entry['key'] ) ) {
+ return true;
+ }
+
+ $key = $entry['key'];
+
+ if ( 'delete_expired' === $op ) {
+ $v = $redis->get( $key );
+ $ttl = $redis->ttl( $key );
+
+ if ( is_array(