Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/wp-compress-image-optimizer/addons/cache/advancedCache.php
+++ b/wp-compress-image-optimizer/addons/cache/advancedCache.php
@@ -51,7 +51,7 @@
if ($stale_rewarm_count >= 4) {
return 'miss';
}
- return 'stale';
+ return wpc_stale_assets_ok($dir, $prefix) ? 'stale' : 'miss';
}
}
if (!defined('WPS_IC_CACHE')) {
@@ -85,16 +85,31 @@
if ($rewarm_count >= 4) {
return 'miss';
}
- return 'stale';
+ return wpc_stale_assets_ok($dir, $prefix) ? 'stale' : 'miss';
} catch (Throwable $e) {
return 'fresh';
}
}
+ function wpc_stale_assets_ok($dir, $prefix = '')
+ {
+ if (!function_exists('wpc_cache_p1_flag') || !wpc_cache_p1_flag()) {
+ return true;
+ }
+ $missing = wpc_copy_assets_missing($dir, $prefix);
+ if ($missing !== [] && function_exists('wpc_fs_log')) {
+ wpc_fs_log('stale-assets-missing', basename(rtrim((string) $dir, '/')), ['variant' => (string) $prefix, 'missing' => $missing]);
+ }
+ return $missing === [];
+ }
+
function wpc_stale_unlink_copies($dir, $prefix = '')
{
$dir = rtrim((string) $dir, '/') . '/';
- foreach (['index.html_br', 'index.html_gzip', 'index.html', 'index.html_md5', 'stale.html_br', 'stale.html_gzip', 'stale.html', 'wpc-rewarm43.txt', 'links.txt'] as $copy_file) {
+ if (defined('WPS_IC_CACHE') && function_exists('wpc_fs_link_below') && wpc_fs_link_below(WPS_IC_CACHE, $dir)) {
+ return;
+ }
+ foreach (['index.html_br', 'index.html_gzip', 'index.html', 'index.html_md5', 'stale.html_br', 'stale.html_gzip', 'stale.html', 'wpc-rewarm43.txt', 'links.txt', 'head.json'] as $copy_file) {
@unlink($dir . $prefix . $copy_file);
}
}
@@ -110,6 +125,7 @@
private $host;
private $cachePath;
+ private $userFolder = '';
private $url_key_class;
public function __construct()
@@ -121,117 +137,10 @@
$this->url_key_class = new wps_ic_url_key();
$this->urlKey = $this->url_key_class->setup();
- // Append user cookie hash to the cache path if user is logged in
- $user_hash = '';
- if (defined('WPC_CACHE_LOGGED_IN') && WPC_CACHE_LOGGED_IN){
- foreach ( $_COOKIE as $key => $value ) {
- if ( strpos( $key, 'wordpress_logged_in_' ) === 0 ) {
- $user_hash = md5( $key . substr( $value, 0, 10 ) ) . '/';
- break;
- }
- }
-
- }
-
- // Add cookie variation to cache path
- $cookie_string = '';
- if (defined('WPC_CACHE_COOKIES') && WPC_CACHE_COOKIES !== false) {
- $cookie_values = [];
- $cache_cookies = WPC_CACHE_COOKIES;
-
- foreach ($cache_cookies as $cookie_name) {
- // Check if this is a prefix cookie (ends with _)
- if (substr($cookie_name, -1) === '_') {
- // This is a prefix - find all cookies that start with this prefix
- $prefix = $cookie_name; // Keep the underscore for matching
- foreach ($_COOKIE as $actual_cookie_name => $cookie_value) {
- if (strpos($actual_cookie_name, $prefix) === 0 && !empty($cookie_value)) {
- // Get the suffix (part after the prefix)
- $suffix = substr($actual_cookie_name, strlen($prefix));
-
- // Create a 7-character hash of the suffix and append to cookie value
- $suffix_hash = substr(hash('md5', $suffix), 0, 7);
- $cookie_values[] = $cookie_value . '_' . $suffix_hash;
- }
- }
- } else {
- // Regular cookie - exact match
- if (isset($_COOKIE[$cookie_name]) && !empty($_COOKIE[$cookie_name])) {
- $cookie_values[] = $_COOKIE[$cookie_name];
- }
- }
- }
-
- if (!empty($cookie_values)) {
- $cookie_string = '_' . implode('_', $cookie_values);
- }
- }
-
- $this->cachePath = WPS_IC_CACHE . $user_hash . $this->urlKey . $cookie_string . '/';
-
-
- }
-
- /**
- * FrontEnd Editors Detection for various page builders
- * @return bool
- */
- public static function isPageBuilder()
- {
- $page_builders = ['run_compress',
- 'run_restore',
- 'elementor-preview',
- 'fl_builder',
- 'et_fb',
- 'preview', //WP Preview
- 'builder',
- 'brizy',
- 'fb-edit',
- 'bricks',
- 'ct_template',
- 'ct_builder',
- 'cs-render',
- 'tatsu',
- 'trp-edit-translation',
- 'brizy-edit-iframe',
- 'ct_builder',
- 'livecomposer_editor',
- 'tatsu',
- 'tatsu-header',
- 'tatsu-footer',
- 'is-editor-iframe',
- 'tve'
- ];
-
- if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], 'cornerstone') !== false) {
- return true;
- }
-
- if ((!empty($_GET['action']) && $_GET['action'] == 'in-front-editor')) {
-
- return true;
- }
-
- if ((!empty($_GET['action']) && sanitize_text_field($_GET['action']) == 'edit#op-builder') || !empty($_GET['op3editor'])) {
-
- return true;
- }
-
- if (!empty($_SERVER['REQUEST_URI'])) {
- if (strpos($_SERVER['REQUEST_URI'], 'wp-json') || strpos($_SERVER['REQUEST_URI'], 'rest_route')) {
- return false;
- }
- }
+ $this->userFolder = wps_ic_url_key::userFolder();
+ $this->cachePath = WPS_IC_CACHE . $this->userFolder . $this->urlKey . wps_ic_url_key::cookieSuffix() . '/';
- if (!empty($page_builders)) {
- foreach ($page_builders as $page_builder) {
- if (isset($_GET[$page_builder])) {
- return true;
- }
- }
- }
- return false;
}
/**
@@ -249,15 +158,6 @@
return false;
}
- public static function isFEBuilder()
- {
- if ((!empty($_GET['action']) && $_GET['action'] == 'in-front-editor') || !empty($_GET['trp-edit-translation']) || !empty($_GET['elementor-preview']) || !empty($_GET['tatsu']) || !empty($_GET['is-editor-iframe']) || !empty($_GET['preview']) || !empty($_GET['PageSpeed']) || !empty($_GET['tve']) || !empty($_GET['et_fb']) || (!empty($_GET['fl_builder']) || isset($_GET['fl_builder'])) || !empty($_GET['ct_builder']) || !empty($_GET['fb-edit']) || !empty($_GET['bricks']) || !empty($_GET['brizy-edit-iframe']) || !empty($_GET['brizy-edit']) || (!empty($_SERVER['SCRIPT_URL']) && $_SERVER['SCRIPT_URL'] == "/wp-admin/customize.php") || (!empty($_GET['page']) && $_GET['page'] == 'livecomposer_editor')) {
- return true;
- } else {
- return false;
- }
- }
-
public function init()
{
return '';
@@ -321,14 +221,6 @@
return true;
}
- if ( ! empty( $_COOKIE['woocommerce_cart_hash'] ) ) {
- return true;
- }
-
- if ( ! empty( $_COOKIE['woocommerce_items_in_cart'] ) ) {
- return true;
- }
-
if ((isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], 'wc-ajax=get_refreshed_fragments') !== false) ||
(isset($_GET['wc-ajax']) && $_GET['wc-ajax'] === 'get_refreshed_fragments')) {
return true;
@@ -340,6 +232,29 @@
public function byPass()
{
+ if (defined('WPC_NO_PAGE_CACHE') && WPC_NO_PAGE_CACHE) {
+ return true;
+ }
+
+ if ((string) $this->urlKey === '') {
+ return true;
+ }
+
+ if (wps_ic_url_key::userFolderDead()) {
+ return true;
+ }
+
+ // A personal cookie (a WooCommerce cart, a password-protected post, a commenter) makes
+ // the response that visitor's own: the drop-in serves no shared copy to it. The list is
+ // wps_ic_url_key::personalCookieNames(), the same one the in-WordPress reader and the
+ // store verdict ask; shoppers with items in the cart were served the cached empty-cart
+ // page (rosella.com.co, anacletababy.com, babypinkworld.com). Without the owner class
+ // loaded nothing can say the request is anonymous, so the drop-in serves nothing.
+ if (!class_exists('wps_ic_url_key') || !method_exists('wps_ic_url_key', 'personalCookieMatch')
+ || wps_ic_url_key::personalCookieMatch() !== '') {
+ return true;
+ }
+
// Cart Fragments
if ($this->isWooFragments()) {
return true;
@@ -351,10 +266,16 @@
$is_excluded_page = false;
if (!empty($request_uri) && $request_uri !== '/') {
- foreach ($excluded_pages as $page) {
- if (str_contains($request_uri, $page)) {
- $is_excluded_page = true;
- break;
+ $query_at = strpos($request_uri, '?');
+ $path_part = $query_at === false ? $request_uri : substr($request_uri, 0, $query_at);
+ $query_part = $query_at === false ? '' : substr($request_uri, $query_at);
+ $is_excluded_page = preg_match('#(?:^|/)(?:cart|checkout|my-account)(?:/|$)#', $path_part) === 1;
+ if (!$is_excluded_page) {
+ foreach ($excluded_pages as $page) {
+ if (str_contains($query_part, $page)) {
+ $is_excluded_page = true;
+ break;
+ }
}
}
}
@@ -365,8 +286,9 @@
}
// Check mandatory cookies - bypass if any required cookie is missing
- if (defined('WPC_MANDATORY_COOKIES') && WPC_MANDATORY_COOKIES !== false && is_array(WPC_MANDATORY_COOKIES)) {
- foreach (WPC_MANDATORY_COOKIES as $mandatoryCookie) {
+ $mandatoryCookies = wps_ic_url_key::mandatoryCookies();
+ if ($mandatoryCookies) {
+ foreach ($mandatoryCookies as $mandatoryCookie) {
if (substr($mandatoryCookie, -1) === '_') {
$found = false;
foreach ($_COOKIE as $cookieName => $cookieValue) {
@@ -396,7 +318,7 @@
$prefix = $prefix . '_';
}
- if (!empty($_SERVER['HTTP_X_WPC_CACHE_WARM'])) {
+ if (wpc_warm_request()) {
if (function_exists('ignore_user_abort')) {
@ignore_user_abort(true);
}
@@ -433,7 +355,7 @@
{
- if (!empty($_SERVER['HTTP_X_WPC_CACHE_WARM'])) {
+ if (wpc_warm_request()) {
return;
}
@@ -519,9 +441,9 @@
$this->setupCacheHeaders($brotliFile, 'br', $wpc_family);
wpc_hit_kick((string) $this->urlKey);
if ($stalePlan === 'stale') {
- wpc_serve_stale_copy($this->cachePath, $prefix);
+ wpc_serve_stale_copy($this->cachePath, $prefix, $this->userFolder !== '');
}
- header('Content-Encoding: br');
+ wpc_send_header('Content-Encoding: br');
readfile($brotliFile);
exit;
}
@@ -533,10 +455,11 @@
$this->setupCacheHeaders($this->cachePath . $prefix . $baseFileName . '_gzip', 'gzip', $wpc_family);
wpc_hit_kick((string) $this->urlKey);
if ($stalePlan === 'stale') {
- wpc_serve_stale_copy($this->cachePath, $prefix);
+ wpc_serve_stale_copy($this->cachePath, $prefix, $this->userFolder !== '');
+ }
+ if (!wpc_send_gzip_copy($gzipFile)) {
+ readgzfile($gzipFile);
}
- // Nginx instantly echoes readgzfile instead of saving it to variable.
- readgzfile($this->cachePath . $prefix . $baseFileName . '_gzip');
exit;
}
}
@@ -545,7 +468,7 @@
$this->setupCacheHeaders($this->cachePath . $prefix . $baseFileName, 'html', $wpc_family);
wpc_hit_kick((string) $this->urlKey);
if ($stalePlan === 'stale') {
- wpc_serve_stale_copy($this->cachePath, $prefix);
+ wpc_serve_stale_copy($this->cachePath, $prefix, $this->userFolder !== '');
}
readfile($this->cachePath . $prefix . $baseFileName);
exit;
@@ -610,10 +533,13 @@
* Headers for a copy served from the file. $family is the copy family the reader found: a
* local-only copy goes out private, with no s-maxage and no Cache-Tag, so no shared cache
* holds it on the second request either — the file carries the verdict the render made.
+ * A copy kept in a signed-in visitor's folder goes out the same way, whatever its family: it is
+ * that visitor's page, and a shared cache must neither hold it nor tag it.
*/
public function setupCacheHeaders($cache_filepath, $type = 'gzip', $family = '')
{
- $wpc_localonly = (string) $family !== '';
+ $wpc_signed_in_copy = $this->userFolder !== '';
+ $wpc_localonly = (string) $family !== '' || $wpc_signed_in_copy;
// Session cookies make CDNs refuse to store the response; cached-file serves are
// anonymous by definition.
if (function_exists('header_remove')) {
@@ -645,7 +571,7 @@
wpc_send_header('Cache-Control: ' . WPC_CC_LOCAL_ONLY);
wpc_send_header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
// The reason the render stored this copy private (wpc_copy_reason_label, wpc-fs.php).
- wpc_send_header('X-WPC-CC: local-only-' . wpc_copy_reason_label($cache_filepath));
+ wpc_send_header('X-WPC-CC: local-only-' . ($wpc_signed_in_copy ? 'signed-in' : wpc_copy_reason_label($cache_filepath)));
} else {
wpc_send_header('Cache-Control: ' . wpc_cc_freshness($browserMaxAge, $edgeMaxAge, wpc_edge_swr()));
wpc_send_header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $browserMaxAge) . ' GMT');
@@ -675,6 +601,11 @@
// A local-only copy never takes an edge directive from the stored set, whichever
// render wrote it.
$wpc_edge_directives = $wpc_localonly ? ['cache-tag' => 1, 'cache-control' => 1, 'cdn-cache-control' => 1, 'surrogate-control' => 1, 'expires' => 1] : [];
+ $wpc_edge_directives['set-cookie'] = 1;
+ // A signed-in visitor's copy takes no other directive a shared cache or a host's page cache acts on either.
+ if ($wpc_signed_in_copy) {
+ $wpc_edge_directives += ['surrogate-key' => 1, 'x-litespeed-cache-control' => 1, 'x-litespeed-tag' => 1, 'x-accel-expires' => 1, 'xkey' => 1, 'x-cache-tags' => 1];
+ }
// Check if cache file exists
if (file_exists($headerCacheFile)) {
@@ -694,7 +625,7 @@
if (is_array($cachedHeaders)) {
foreach ($cachedHeaders as $name => $value) {
if (!isset($existingHeaders[$name]) && !isset($wpc_edge_directives[strtolower((string) $name)])) {
- header($name . ': ' . $value);
+ wpc_send_header($name . ': ' . $value);
}
}
}
@@ -714,7 +645,7 @@
public function removeCacheFiles($post_id)
{
- if ($post_id == 'all') {
+ if (wpc_purge_scope_all($post_id)) {
self::removeDirectory(WPS_IC_CACHE);
return;
}
@@ -744,7 +675,7 @@
// sweep collects dead keys. JS combine DOES serve-from-existing, so its rebuild
// trigger becomes a stale marker (epoch for 'all', per-key file) that the gate
// honors — rebuild overwrites in place, no absence window for either lane.
- if ($post_id == 'all') {
+ if (wpc_purge_scope_all($post_id)) {
update_option('wpc_combine_stale_epoch', time(), false);
return;
}
@@ -773,7 +704,7 @@
'via' => implode('<', $wpc_tw_via),
]);
}
- if ($post_id == 'all') {
+ if (wpc_purge_scope_all($post_id)) {
if (class_exists('wps_ic_cache_integrations') && method_exists('wps_ic_cache_integrations', 'wipeCriticalPreservingStores')) {
--- a/wp-compress-image-optimizer/addons/cache/cacheHtml.php
+++ b/wp-compress-image-optimizer/addons/cache/cacheHtml.php
@@ -149,7 +149,7 @@
if ($stale_rewarm_count >= 4) {
return 'miss';
}
- return 'stale';
+ return wpc_stale_assets_ok($dir, $prefix) ? 'stale' : 'miss';
}
}
if (!defined('WPS_IC_CACHE')) {
@@ -183,16 +183,31 @@
if ($rewarm_count >= 4) {
return 'miss';
}
- return 'stale';
+ return wpc_stale_assets_ok($dir, $prefix) ? 'stale' : 'miss';
} catch (Throwable $e) {
return 'fresh';
}
}
+ function wpc_stale_assets_ok($dir, $prefix = '')
+ {
+ if (!function_exists('wpc_cache_p1_flag') || !wpc_cache_p1_flag()) {
+ return true;
+ }
+ $missing = wpc_copy_assets_missing($dir, $prefix);
+ if ($missing !== [] && function_exists('wpc_fs_log')) {
+ wpc_fs_log('stale-assets-missing', basename(rtrim((string) $dir, '/')), ['variant' => (string) $prefix, 'missing' => $missing]);
+ }
+ return $missing === [];
+ }
+
function wpc_stale_unlink_copies($dir, $prefix = '')
{
$dir = rtrim((string) $dir, '/') . '/';
- foreach (['index.html_br', 'index.html_gzip', 'index.html', 'index.html_md5', 'stale.html_br', 'stale.html_gzip', 'stale.html', 'wpc-rewarm43.txt', 'links.txt'] as $copy_file) {
+ if (defined('WPS_IC_CACHE') && function_exists('wpc_fs_link_below') && wpc_fs_link_below(WPS_IC_CACHE, $dir)) {
+ return;
+ }
+ foreach (['index.html_br', 'index.html_gzip', 'index.html', 'index.html_md5', 'stale.html_br', 'stale.html_gzip', 'stale.html', 'wpc-rewarm43.txt', 'links.txt', 'head.json'] as $copy_file) {
@unlink($dir . $prefix . $copy_file);
}
}
@@ -247,10 +262,21 @@
* own form or as the zone's transform of it (`<zone>/m:0/a:<site url>`), and that is a file on
* disk now. A link to a file that is
* already missing is never recorded, and neither are the files the plugin generates: their
- * owners keep them as long as the copies that link them. The one generated file the record
- * names is the delay registry sidecar, as `s:<file name>` (first, so the cap never drops it):
+ * owners keep them as long as the copies that link them (the sheet copies under cache/wpc-bgset,
+ * cache/wpc-hostfix and cache/wpc-fontsheet are recorded as c: tokens: their prune keeps the
+ * newest three of a stem, not the ones a page links). The generated files the record
+ * names are the delay registry sidecar, as `s:<file name>` (first, so the cap never drops it):
* its owner (wps_ic_js_delay_v3::wpc_registry_sidecar_trim) keeps every sidecar a stored copy
- * names, and the missing-asset audit does not read `s:` tokens.
+ * names; the files of the content-addressed stores, as `w:<css|js>/<file name>` (`w:*` when the
+ * page links more than 200 or a name this record cannot hold): their owner
+ * (wpc_processed_copy_gc) keeps every file a stored copy names; and the combined and bundled
+ * sheets, as `k:combine/<path>` and `k:critical/combined/<file name>`, and the used-css and
+ * sidecar sheets, as `k:critical/used-css/<file name>` (the rest sheet named only by a
+ * data-wpc-rest attribute included) and `k:critical/sidecar/<file name>`, which a stale copy is
+ * served only while they exist (wpc_copy_assets_missing). The missing-asset audit reads none of
+ * these. The body scripts' file
+ * (wpc-body-<hash>.js, policy.body_js_ext) is named the same way, as `b:<file name>` (the record's own `b:<bytes>` line is
+ * all digits), and kept by wpc_processed_copy_gc while a stored copy names it.
*/
function wpc_copy_links_scan($html)
{
@@ -264,8 +290,21 @@
$found['s:' . $sidecar] = true;
}
}
+ if (preg_match_all('#wpc-assets\\?/(wpc-body-[0-9a-f]{12}.js)b#', $html, $bodies)) {
+ foreach ($bodies[1] as $body) {
+ $found['b:' . $body] = true;
+ }
+ }
$values = preg_match_all('/(?<![w:-])[w:-]*(?:href|src)s*=s*(["'])(.*?)1/is', $html, $attributes) ? $attributes[2] : [];
$values = array_merge($values, wpc_copy_links_registry_sources($html));
+ if (stripos($html, 'data-wpc-rest') !== false && preg_match_all('/sdata-wpc-rests*=s*(["'])(.*?)1/is', $html, $parked)) {
+ $restAll = function_exists('wpc_policy_cohort') && ((int) wpc_policy_cohort('hero_same_origin') === 1 || (int) wpc_policy_cohort('bg_mobile_src') === 1);
+ foreach ($parked[2] as $restValue) {
+ if ($restAll || stripos($restValue, '/cache/critical/used-css/') !== false || preg_match('#.phone-[0-9a-f]{12}.css(?:[?#]|$)#i', html_entity_decode($restValue, ENT_QUOTES, 'UTF-8'))) {
+ $values[] = $restValue;
+ }
+ }
+ }
if ($values === []) {
return array_keys($found);
}
@@ -288,6 +327,8 @@
}
}
$known = [];
+ $stores = [];
+ $kept = [];
foreach ($values as $value) {
if (stripos($value, '.css') === false && stripos($value, '.js') === false) {
continue;
@@ -324,8 +365,18 @@
continue;
}
$relative = rawurldecode(substr($path, strlen($prefix) + 1));
+ if ($relative !== '' && $root === 'c' && strpos($relative, '..') === false && preg_match('#^cache/wp-cio/(css|js)/(.+)$#', $relative, $store)) {
+ $stores[count($stores) < 200 && preg_match('#^[A-Za-z0-9._/-]{1,200}$#', $store[2]) ? 'w:' . $store[1] . '/' . $store[2] : 'w:*'] = true;
+ break;
+ }
+ if ($relative !== '' && $root === 'c' && strpos($relative, '..') === false && preg_match('#^cache/((?:combine|critical/(?:combined|used-css|sidecar))/.+)$#', $relative, $keep)) {
+ if (count($kept) < 100 && preg_match('#^[A-Za-z0-9._/-]{1,200}$#', $keep[1])) {
+ $kept['k:' . $keep[1]] = true;
+ }
+ break;
+ }
if ($relative === '' || strpos($relative, '..') !== false || preg_match('/[x00-x1f\\]/', $relative)
- || preg_match('#^cache/(?:wp-cio|wp-cio-fonts|critical|combine|wpc-hostfix)/|(?:^|/)wpc-assets/#', $relative)) {
+ || preg_match('#^cache/(?:wp-cio|wp-cio-fonts|critical|combine)/|(?:^|/)wpc-assets/#', $relative)) {
break;
}
$token = $root . ':' . $relative;
@@ -341,7 +392,7 @@
} catch (Throwable $e) {
return [];
}
- return array_keys($found);
+ return array_merge(array_keys($found), array_keys($stores), array_keys($kept));
}
/** The file a link token names, or '' when the token does not name one this site can resolve. */
@@ -373,29 +424,32 @@
}
/**
- * Writes the links a copy carries beside it ($file, the 'links' name of wpc_copy_names): one
- * token per line, in one rename, and no file at all for a page that links none or when the write
- * fails: a record of the copy before it is never left beside the copy that replaced it. Returns
- * how many tokens it wrote.
+ * Writes the links a copy carries beside it ($file, the 'links' name of wpc_copy_names): `v:2`
+ * first, which says the writer listed every generated file the page links, `b:<bytes>`, the size
+ * of the document (the shrink check of the next store reads it), then one token per line, in one
+ * rename. A page that links nothing keeps the record with the marker alone, so a
+ * copy with no record is a copy whose writer did not record (wpc_stored_copies_survey holds
+ * every file for it). No file at all when the write fails: a record of the copy before it is
+ * never left beside the copy that replaced it. Returns how many tokens it wrote besides the
+ * marker.
*/
function wpc_copy_links_record($file, $html)
{
try {
$tokens = wpc_copy_links_scan($html);
- if ($tokens === []) {
- if (@is_file($file)) {
- @unlink($file);
- }
- return 0;
- }
$tmp = $file . '.tmp.' . getmypid() . '.' . substr(md5(uniqid('', true)), 0, 8);
- if (wpc_fs_put($tmp, implode("n", $tokens) . "n") === false || !@rename($tmp, $file)) {
+ if (wpc_fs_put($tmp, implode("n", array_merge(['v:2', 'b:' . strlen((string) $html)], $tokens)) . "n") === false || !@rename($tmp, $file)) {
@unlink($tmp);
@unlink($file);
return 0;
}
if (function_exists('wpc_missing_asset_audit_arm')) {
- wpc_missing_asset_audit_arm();
+ foreach ($tokens as $token) {
+ if (strpos($token, 'w:') !== 0 && strpos($token, 'k:') !== 0) {
+ wpc_missing_asset_audit_arm();
+ break;
+ }
+ }
}
return count($tokens);
} catch (Throwable $e) {
@@ -404,6 +458,280 @@
}
}
+if (!function_exists('wpc_br_prestore')) {
+ /**
+ * Queues the Brotli copy of a page just stored: after the response is released, quality 11, the
+ * `_br` sibling of the gzip copy is written once, and only while the md5 sidecar still names this
+ * document (the sibling is always the current copy's pair: saveGzCache removes it before every
+ * write). The server needs no Brotli: the drop-in sends the bytes itself, as it does for the
+ * copies crit's land writes. Needs ext-brotli; a page larger than 1.5 MB is left to gzip.
+ */
+ function wpc_br_prestore($brFile, $md5File, $document)
+ {
+ if (!function_exists('brotli_compress') || !is_string($document) || strlen($document) > (int) apply_filters('wpc_br_prestore_max_bytes', 1500000)) {
+ return false;
+ }
+ if (empty($GLOBALS['wpc_br_prestore_queue'])) {
+ register_shutdown_function('wpc_br_prestore_run');
+ }
+ $GLOBALS['wpc_br_prestore_queue'][$brFile] = [$md5File, $document];
+ return true;
+ }
+
+ /** Writes the queued Brotli copies (see wpc_br_prestore); answers how many it wrote. */
+ function wpc_br_prestore_run()
+ {
+ $written = 0;
+ try {
+ $queue = isset($GLOBALS['wpc_br_prestore_queue']) ? (array) $GLOBALS['wpc_br_prestore_queue'] : [];
+ unset($GLOBALS['wpc_br_prestore_queue']);
+ if ($queue === []) {
+ return 0;
+ }
+ if (function_exists('wpc_finish_request') && empty($GLOBALS['wpc_response_released'])) {
+ wpc_finish_request();
+ }
+ if (function_exists('ignore_user_abort')) {
+ @ignore_user_abort(true);
+ }
+ foreach ($queue as $target => $job) {
+ if (strtolower(trim((string) @file_get_contents($job[0]))) !== md5($job[1])) {
+ continue;
+ }
+ $packed = @brotli_compress($job[1], 11);
+ if (!is_string($packed) || $packed === '') {
+ continue;
+ }
+ $tmp = $target . '.tmp.' . getmypid() . '.' . substr(md5(uniqid('', true)), 0, 8);
+ if (wpc_fs_put($tmp, $packed) === false) {
+ @unlink($tmp);
+ continue;
+ }
+ if (strtolower(trim((string) @file_get_contents($job[0]))) !== md5($job[1]) || !@rename($tmp, $target)) {
+ @unlink($tmp);
+ continue;
+ }
+ $written++;
+ if (function_exists('wpc_cache_first_log')) {
+ wpc_cache_first_log('br-prestored', basename(dirname($target)), '', ['bytes' => strlen($packed), 'device' => strpos(basename($target), 'mobile_') === 0 ? 'mobile' : 'desktop']);
+ }
+ }
+ } catch (Throwable $e) {
+ }
+ return $written;
+ }
+}
+
+if (!function_exists('wpc_served_head_matcher')) {
+ /**
+ * The one list of what the plugin puts in a page's head, as three patterns: 'crit' tests an
+ * element's opening tag for the critical CSS and the inline faces, 'tag' tests it for any mark
+ * of the plugin (an id or class of ours, a data-wpc attribute, a wpc- type, rel or meta name, a
+ * file of ours, a hint link to the CDN host), and 'body' tests the first bytes of an inline
+ * style or script that carries none of those. An element matching none is the theme's.
+ */
+ function wpc_served_head_matcher()
+ {
+ $zone = '[^"'s/>:]*.zapwp.(?:com|net)';
+ if (function_exists('wpc_cdn_host')) {
+ $host = (string) wpc_cdn_host();
+ if ($host !== '') {
+ $zone .= '|' . preg_quote($host, '~');
+ }
+ }
+ return [
+ 'crit' => '~(?<![w:-])ids*=s*["']?wpc-(?:critical-css|font-faces|font-subsets|font-fallbacks|crit-faces|fonts-css|font-carrier|live-faces)~i',
+ 'tag' => '~' . implode('|', [
+ '(?<![w:-])ids*=s*["']?(?:wpc-|wpcompress|wps[-_]ic)',
+ '(?<![w:-])classs*=s*(["'])(?:(?!1)[^>])*?(?<![w-])(?:wpc-|wps-inline|wps-ic)',
+ '(?<=[s"'])data-(?:wpc|wps-ic)[w-]*',
+ '(?<=[s"'])data-script-ids*=',
+ '(?<![w:-])(?:type|rel)s*=s*["']?(?:text/)?wpc[-/]',
+ '(?<![w:-])names*=s*["']?wpc-',
+ '(?<![w:-])(?:src|href)s*=s*["']?[^"'s>]*(?:/plugins/wp-compress-image-optimizer/|/cache/wp-cio/|/wpc-assets/|/wpc-yield-)',
+ '^<linkb(?=[^>]*(?<![w:-])rels*=s*["']?(?:dns-prefetch|preconnect|preload|prefetch|modulepreload)b)[^>]*(?<![w:-])hrefs*=s*["']?(?:https?:)?//(?:' . $zone . ')(?:[/"'s>:]|$)',
+ ]) . '~i',
+ 'theme' => '~(?<![w:-])(?:type|rel)s*=s*["']?wpc-(?:mobile-)?stylesheetb~i',
+ 'body' => '~^s*(?:(?:picture)?.wpc-|vars+(?:n489D_vars|integrationActive)b|window.(?:__)?wpc|(function()s*{s*//s*Flag to track if our handler is active)~i',
+ ];
+ }
+
+ /**
+ * The head of a document, <head> to </head>, split by whose elements they are, in document
+ * order: ['head' => the whole head, 'crit' => the critical CSS and the inline faces, 'wpc' =>
+ * every other element the plugin put there, 'other' => the rest: the theme's elements, the text
+ * between elements, the comments and the head's own tags]. Each byte of the head is in exactly
+ * one slice. Null when the document has no head that closes before its body.
+ */
+ function wpc_served_head_slices($html)
+ {
+ if (!is_string($html) || $html === '' || preg_match('~<head(?=[s>/])~i', $html, $opening, PREG_OFFSET_CAPTURE) !== 1) {
+ return null;
+ }
+ $start = $opening[0][1];
+ $matcher = wpc_served_head_matcher();
+ $rawText = ['script' => 1, 'style' => 1, 'title' => 1, 'textarea' => 1, 'noscript' => 1, 'template' => 1];
+ $slices = ['crit' => '', 'wpc' => '', 'other' => ''];
+ if (preg_match('~G<headb(?:[^>"']++|"[^"]*+"|'[^']*+')*+>~i', $html, $tag, 0, $start) !== 1) {
+ return null;
+ }
+ $slices['other'] .= $tag[0];
+ $at = $start + strlen($tag[0]);
+ $limit = $start + 4194304;
+ while ($at < $limit) {
+ $lt = strpos($html, '<', $at);
+ if ($lt === false) {
+ return null;
+ }
+ if ($lt > $at) {
+ $slices['other'] .= substr($html, $at, $lt - $at);
+ }
+ $at = $lt;
+ $next = isset($html[$at + 1]) ? $html[$at + 1] : '';
+ if ($next === '!' && substr($html, $at, 4) === '<!--') {
+ $end = strpos($html, '-->', $at + 4);
+ if ($end === false) {
+ return null;
+ }
+ $slices['other'] .= substr($html, $at, $end + 3 - $at);
+ $at = $end + 3;
+ continue;
+ }
+ if ($next === '!' || $next === '?') {
+ $end = strpos($html, '>', $at);
+ if ($end === false) {
+ return null;
+ }
+ $slices['other'] .= substr($html, $at, $end + 1 - $at);
+ $at = $end + 1;
+ continue;
+ }
+ if ($next === '/') {
+ $closing = preg_match('~G</([a-zA-Z][a-zA-Z0-9:-]*)[^>]*+>~', $html, $tag, 0, $at);
+ if ($closing === false) {
+ return null;
+ }
+ if ($closing !== 1) {
+ $slices['other'] .= '<';
+ $at++;
+ continue;
+ }
+ $slices['other'] .= $tag[0];
+ $at += strlen($tag[0]);
+ if (strtolower($tag[1]) === 'head') {
+ return ['head' => substr($html, $start, $at - $start)] + $slices;
+ }
+ continue;
+ }
+ $opened = preg_match('~G<([a-zA-Z][a-zA-Z0-9:-]*+)(?:[^>"']++|"[^"]*+"|'[^']*+')*+>~', $html, $tag, 0, $at);
+ if ($opened === false) {
+ return null;
+ }
+ if ($opened !== 1) {
+ $slices['other'] .= '<';
+ $at++;
+ continue;
+ }
+ $name = strtolower($tag[1]);
+ if ($name === 'body') {
+ return null;
+ }
+ $end = $at + strlen($tag[0]);
+ if (isset($rawText[$name])) {
+ $close = stripos($html, '</' . $name, $end);
+ $closeEnd = $close === false ? false : strpos($html, '>', $close);
+ if ($closeEnd === false) {
+ return null;
+ }
+ $end = $closeEnd + 1;
+ }
+ $piece = substr($html, $at, $end - $at);
+ $owner = 'other';
+ $crit = preg_match($matcher['crit'], $tag[0]);
+ $mark = $crit === 1 ? 0 : preg_match($matcher['tag'], $name === 'noscript' || $name === 'template' ? $piece : $tag[0]);
+ if ($crit === false || $mark === false) {
+ return null;
+ }
+ if ($crit === 1) {
+ $owner = 'crit';
+ } elseif ($mark === 1 && !($name === 'style' && preg_match($matcher['theme'], $tag[0]) === 1)) {
+ $owner = 'wpc';
+ } elseif (($name === 'style' || $name === 'script') && stripos($tag[0], ' src') === false) {
+ $inline = preg_match($matcher['body'], substr($piece, strlen($tag[0]), 96));
+ if ($inline === false) {
+ return null;
+ }
+ $owner = $inline === 1 ? 'wpc' : 'other';
+ }
+ $slices[$owner] .= $piece;
+ $at = $end;
+ }
+ return null;
+ }
+
+ /**
+ * The byte sizes of a document's head: raw and gzip level 6 for the whole head and for each
+ * slice of wpc_served_head_slices() alone (a slice with no bytes is 0, so the gzip sizes of the
+ * slices do not add up to the head's). Null when the head cannot be measured.
+ */
+ function wpc_served_head_measure($html, $device)
+ {
+ if (!function_exists('gzencode')) {
+ return null;
+ }
+ $slices = wpc_served_head_slices($html);
+ if ($slices === null) {
+ return null;
+ }
+ $gz = function ($bytes) {
+ return $bytes === '' ? 0 : strlen((string) gzencode($bytes, 6));
+ };
+ return [
+ 'raw_b' => strlen($slices['head']),
+ 'gz6_b' => $gz($slices['head']),
+ 'crit_b' => strlen($slices['crit']),
+ 'crit_gz6_b' => $gz($slices['crit']),
+ 'wpc_b' => strlen($slices['wpc']),
+ 'wpc_gz6_b' => $gz($slices['wpc']),
+ 'other_b' => strlen($slices['other']),
+ 'other_gz6_b' => $gz($slices['other']),
+ 'device' => $device === 'mobile' ? 'mobile' : 'desktop',
+ 'stored_at' => 0,
+ ];
+ }
+
+ /**
+ * Writes the head record of a copy beside it ($file, the 'head' name of wpc_copy_names), once,
+ * when the copy is stored: the sizes of $html's head for the device $prefix names, with the
+ * copy's modification time as stored_at. One rename; no record at all when the head cannot be
+ * measured or the write fails, so a record of the copy before is never left beside the copy
+ * that replaced it. Returns whether a record was written.
+ */
+ function wpc_served_head_record($file, $html, $prefix, $copyFile)
+ {
+ try {
+ $head = wpc_served_head_measure($html, strpos((string) $prefix, 'mobile') === 0 ? 'mobile' : 'desktop');
+ if ($head !== null) {
+ clearstatcache(true, $copyFile);
+ $head['stored_at'] = (int) @filemtime($copyFile);
+ }
+ if ($head === null || $head['stored_at'] <= 0) {
+ @unlink($file);
+ return false;
+ }
+ $tmp = $file . '.tmp.' . getmypid() . '.' . substr(md5(uniqid('', true)), 0, 8);
+ if (wpc_fs_put($tmp, json_encode($head)) === false || !@rename($tmp, $file)) {
+ @unlink($tmp);
+ @unlink($file);
+ return false;
+ }
+ return true;
+ } catch (Throwable $e) {
+ return false;
+ }
+ }
+}
+
class wps_cacheHtml
{
@@ -414,6 +742,7 @@
private $host;
private $cachePath;
+ private $userFolder = '';
private $options;
private $url_key_class;
@@ -432,115 +761,9 @@
$this->url_key_class = new wps_ic_url_key();
$this->urlKey = $this->url_key_class->setup();
- // Append user cookie hash to the cache path if user is logged in
- $user_hash = '';
- if (defined('WPC_CACHE_LOGGED_IN') && WPC_CACHE_LOGGED_IN) {
- foreach ($_COOKIE as $key => $value) {
- if (strpos($key, 'wordpress_logged_in_') === 0) {
- $user_hash = md5($key . substr($value, 0, 10)) . '/';
- break;
- }
- }
-
- }
-
- // Add cookie variation to cache path
- $cookie_string = '';
- if (defined('WPC_CACHE_COOKIES') && WPC_CACHE_COOKIES !== false) {
- $cookie_values = [];
- $cache_cookies = WPC_CACHE_COOKIES;
-
- foreach ($cache_cookies as $cookie_name) {
- // Check if this is a prefix cookie (ends with _)
- if (substr($cookie_name, -1) === '_') {
- // This is a prefix - find all cookies that start with this prefix
- $prefix = $cookie_name; // Keep the underscore for matching
- foreach ($_COOKIE as $actual_cookie_name => $cookie_value) {
- if (strpos($actual_cookie_name, $prefix) === 0 && !empty($cookie_value)) {
- // Get the suffix (part after the prefix)
- $suffix = substr($actual_cookie_name, strlen($prefix));
-
- // Create a 7-character hash of the suffix and append to cookie value
- $suffix_hash = substr(hash('md5', $suffix), 0, 7);
- $cookie_values[] = $cookie_value . '_' . $suffix_hash;
- }
- }
- } else {
- // Regular cookie - exact match
- if (isset($_COOKIE[$cookie_name]) && !empty($_COOKIE[$cookie_name])) {
- $cookie_values[] = $_COOKIE[$cookie_name];
- }
- }
- }
-
- if (!empty($cookie_values)) {
- $cookie_string = '_' . implode('_', $cookie_values);
- }
- }
-
- $this->cachePath = WPS_IC_CACHE . $user_hash . $this->urlKey . $cookie_string . '/';
- }
-
- /**
- * FrontEnd Editors Detection for various page builders
- * @return bool
- */
- public static function isPageBuilder()
- {
- $page_builders = ['run_compress',
- 'run_restore',
- 'elementor-preview',
- 'fl_builder',
- 'et_fb',
- 'preview', //WP Preview
- 'builder',
- 'brizy',
- 'fb-edit',
- 'bricks',
- 'ct_template',
- 'ct_builder',
- 'cs-render',
- 'tatsu',
- 'trp-edit-translation',
- 'brizy-edit-iframe',
- 'ct_builder',
- 'livecomposer_editor',
- 'tatsu',
- 'tatsu-header',
- 'tatsu-footer',
- 'is-editor-iframe',
- 'tve'
- ];
-
- if ((!empty($_GET['action']) && $_GET['action'] == 'in-front-editor')) {
-
- return true;
- }
-
- if ((!empty($_GET['action']) && sanitize_text_field($_GET['action']) == 'edit#op-builder') || !empty($_GET['op3editor'])) {
-
- return true;
- }
-
- if (!empty($_SERVER['REQUEST_URI'])) {
- if (strpos($_SERVER['REQUEST_URI'], 'wp-json') || strpos($_SERVER['REQUEST_URI'], 'rest_route')) {
- return false;
- }
- }
-
- if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], 'cornerstone') !== false) {
- return true;
- }
-
- if (!empty($page_builders)) {
- foreach ($page_builders as $page_builder) {
- if (isset($_GET[$page_builder])) {
- return true;
- }
- }
- }
+ $this->userFolder = wps_ic_url_key::userFolder();
- return false;
+ $this->cachePath = WPS_IC_CACHE . $this->userFolder . $this->urlKey . wps_ic_url_key::cookieSuffix() . '/';
}
/**
@@ -558,15 +781,6 @@
return false;
}
- public static function isFEBuilder()
- {
- if ((!empty($_GET['action']) && $_GET['action'] == 'in-front-editor') || !empty($_GET['trp-edit-translation']) || !empty($_GET['elementor-preview']) || !empty($_GET['tatsu']) || !empty($_GET['is-editor-iframe']) || !empty($_GET['preview']) || !empty($_GET['PageSpeed']) || !empty($_GET['tve']) || !empty($_GET['et_fb']) || (!empty($_GET['fl_builder']) || isset($_GET['fl_builder'])) || !empty($_GET['ct_builder']) || !empty($_GET['fb-edit']) || !empty($_GET['bricks']) || !empty($_GET['brizy-edit-iframe']) || !empty($_GET['brizy-edit']) || (!empty($_SERVER['SCRIPT_URL']) && $_SERVER['SCRIPT_URL'] == "/wp-admin/customize.php") || (!empty($_GET['page']) && $_GET['page'] == 'livecomposer_editor')) {
- return true;
- } else {
- return false;
- }
- }
-
public function init()
{
return '';
@@ -649,7 +863,7 @@
$prefix = $prefix . '_';
}
- if (!empty($_SERVER['HTTP_X_WPC_CACHE_WARM'])) {
+ if (wpc_warm_request()) {
if (function_exists('ignore_user_abort')) {
@ignore_user_abort(true);
}
@@ -691,7 +905,9 @@
// fetchpriority=high; crit regenerates with the page, so the URL is always live.
/**
* Proposes the first background url() of the inlined crit as the page's preload
- * (wpc-crit-bg-preload, below every measured candidate in the set's rank).
+ * (wpc-crit-bg-preload, below every measured candidate in the set's rank). A UI sprite
+ * first is passed over only for a later url() that is the rendition of the picture the
+ * service measured as the LCP of a device the render serves.
*/
public static function critBgPreload($buffer, $imagePreloads = null)
{
@@ -704,22 +920,85 @@
|| !preg_match('/<style[^>]*id="wpc-critical-css"[^>]*>(.*?)</style>/s', $buffer, $wpc_pm)) {
return $buffer;
}
- if (!preg_match('/background(?:-image)?s*:s*[^;{}]*url(s*(['"]?)((?:https?:)?/[^)'"]{8,500}.(?:jpe?g|png|webp|avif|svg)(?:?[^)'"]{0,120})?)1/i', $wpc_pm[1], $wpc_pu)) {
+ $wpc_pick = self::critBgPick($wpc_pm[1]);
+ if ($wpc_pick === null) {
+ return $buffer;
+ }
+ $wpc_chrome_veto = $wpc_pick['veto'];
+ if ($wpc_pick['url'] === '') {
+ if (function_exists('wpc_belt_receipt')) {
+ wpc_belt_receipt('crit-bg-preload-vetoed', $wpc_chrome_veto, true);
+ }
return $buffer;
}
- // v7.21.58 — the FIRST bg url() in crit is not always a hero: ctfx preloaded
- // WooCommerce's photoswipe default-skin.png sprite at fetchpriority=high through the
- // q:i queue. UI-chrome sprites/skins/icons are never the LCP — veto them instead of
- // spending the page's highest-priority fetch on one.
- if (preg_match('/default-skin|photoswipe|sprite|/icons?[/.-]|loading|spinner|arrow/i', (string) $wpc_pu[2])) {
- // The veto withholds the page's highest-priority fetch. The same crit vetoes on every
- // render until it regenerates, so the line is sampled once an hour per page.
+ // A MEASURED PAGE GETS NO GUESSED PRELOAD FOR A LEG THE SERVICE COULD NOT MEASURE. This
+ // fallback is for pages the service never measured (perkzilla, 2025). On a page with its
+ // own lcp.json the LCP lane fills the legs that were measured, and a null leg means "could
+ // not measure" (crit-push 3.198.346 contract: a challenged or timed-out leg), not "no
+ // image", so the crit's first background is a guess about a page we have facts for:
+ // hartwood.biz (ticket 12072, 2026-10-20), desktop measured as `::before` and mobile null
+ // (Turnstile blocks the pod on phones), got the full-size origin cover-2026.webp (379 KB)
+ // preloaded at high priority under the phone media query for a pseudo-element the crit
+ // sets to display:none on phones. Same file resolution as wps_ic_atf_observation's
+ // page-only document: the page's own lcp.json, never the home page's.
+ if (class_exists('wps_rewriteLogic') && method_exists('wps_rewriteLogic', 'wpc_page_lcp_json_file')
+ && (string) wps_rewriteLogic::wpc_page_lcp_json_file() !== '') {
+ // The page keeps its observation until it regenerates, so the line is sampled once an
+ // hour per page.
if (function_exists('wpc_belt_receipt')) {
- wpc_belt_receipt('crit-bg-preload-vetoed', ['why' => 'ui-chrome', 'src' => substr((string) $wpc_pu[2], -120)], true);
+ wpc_belt_receipt('crit-bg-preload-skipped', ['why' => 'observation-present', 'src' => substr((string) $wpc_pick['url'], -120)], true);
}
return $buffer;
}
- $wpc_ph = html_entity_decode($wpc_pu[2], ENT_QUOTES);
+ $wpc_text = $wpc_pick['text'];
+ $wpc_url = $wpc_pick['url'];
+ $wpc_matched = $wpc_pick['matched'];
+ $wpc_set = null;
+ if (class_exists('wps_rewriteLogic') && wps_rewriteLogic::bg_hero_match_on()) {
+ $wpc_set = self::critBgSet($wpc_pm[1], (int) strpos($wpc_pm[1], $wpc_text));
+ if ($wpc_set !== null && self::critBgDense($wpc_set)) {
+ if (function_exists('wpc_belt_receipt')) {
+ wpc_belt_receipt('crit-bg-preload-vetoed', ['why' => 'density-set', 'src' => substr($wpc_set['url'], -120)]
+ + ($wpc_chrome_veto === null ? [] : ['after' => 'ui-chrome']), true);
+ }
+ return $buffer;
+ }
+ }
+ if ($wpc_chrome_veto !== null && function_exists('wpc_belt_receipt')) {
+ wpc_belt_receipt('crit-bg-preload-vetoed', $wpc_chrome_veto, true);
+ }
+ $wpc_preload_device = 'both';
+ if (class_exists('wps_ic_atf_observation') && wps_ic_atf_observation::heroFold()) {
+ $wpc_standdown = [];
+ foreach (['mobile', 'desktop'] as $wpc_stand_device) {
+ if (wps_ic_atf_observation::lcpHeld($wpc_stand_device) || wps_ic_atf_observation::lcpUnknown($wpc_stand_device)) {
+ $wpc_standdown[] = $wpc_stand_device;
+ }
+ }
+ if (!empty($wpc_standdown)) {
+ $wpc_combined = class_exists('wps_rewriteLogic') && wps_rewriteLogic::wpc_combined_crit_on();
+ $wpc_render_device = (function_exists('wpc_ua_is_mobile') && wpc_ua_is_mobile()) ? 'mobile' : 'desktop';
+ if (!$wpc_combined) {
+ if (in_array($wpc_render_device, $wpc_standdown, true)) {
+ $imagePreloads->declined('lcp-hold');
+ return $buffer;
+ }
+ } elseif (count($wpc_standdown) > 1) {
+ $imagePreloads->declined('lcp-hold');
+ return $buffer;
+ } else {
+ $wpc_preload_device = $wpc_standdown[0] === 'mobile' ? 'desktop' : 'mobile';
+ }
+ }
+ }
+ if ($wpc_matched !== null && class_exists('wps_rewriteLogic') && wps_rewriteLogic::wpc_combined_crit_on()) {
+ if ($wpc_preload_device === 'both') {
+ $wpc_preload_device = count($wpc_matched) === 2 ? 'both' : $wpc_matched[0];
+ } elseif (!in_array($wpc_preload_device, $wpc_matched, true)) {
+ return $buffer;
+ }
+ }
+ $wpc_ph = html_entity_decode($wpc_url, ENT_QUOTES);
if (strpos($wpc_ph, '//') === 0) {
$wpc_ph = 'https:' . $wpc_ph;
} elseif ($wpc_ph[0] === '/' && !empty($_SERVER['HTTP_HOST'])) {
@@ -731,11 +1010,154 @@
$wpc_ph = $aligned_match[1];
}
}
- $imagePreloads->add('wpc-crit-bg-preload', esc_url($wpc_ph), 'both', 'crit-bg',
- wps_ic_image_preload_set::RANK_CRIT_BACKGROUND, ['kind' => wps_ic_image_preload_set::KIND_BACKGROUND]);
+ $wpc_type = '';
+ $wpc_painted = self::critBgPainted($wpc_set);
+ if ($wpc_painted !== null) {
+ $wpc_ph = $wpc_painted[0];
+ $wpc_type = $wpc_painted[1];
+ }
+ $imagePreloads->add('wpc-crit-bg-preload', esc_url($wpc_ph), $wpc_preload_device, 'crit-bg',
+ wps_ic_image_preload_set::RANK_CRIT_BACKGROUND, ['kind' => wps_ic_image_preload_set::KIND_BACKGROUND] + ($wpc_type !== '' ? ['type' => $wpc_type] : [])
+ + ($wpc_matched === null ? [] : ['supersedes' => [wps_ic_image_preload_set::SLOT_ATF_BG], 'exact' => true]));
return $buffer;
}
+ /**
+ * The first background url() of a crit block that is not UI chrome (a sprite, skin or icon passed over for a later url() that
+ * is the rendition of the picture the service measured, critBgPastChrome): ['text' => the declaration, 'url' => the address as
+ * written, 'matched' => the devices that url() was matched to or null, 'veto' => the ui-chrome receipt fields or null]. 'url' is ''
+ * when only chrome was found, null is returned when the block holds no background url() at all.
+ */
+ public static function critBgPick($crit)
+ {
+ $wpc_rx = '/background(?:-image)?s*:s*[^;{}]*url(s*(['"]?)((?:https?:)?/[^)'"]{8,500}.(?:jpe?g|png|webp|avif|svg)(?:?[^)'"]{0,120})?)1/i';
+ if (!is_string($crit) || !preg_match($wpc_rx, $crit, $wpc_pu, PREG_OFFSET_CAPTURE)) {
+ return null;
+ }
+ $wpc_text = $wpc_pu[0][0];
+ $wpc_url = $wpc_pu[2][0];
+ $wpc_matched = null;
+ $wpc_chrome_veto = null;
+ if (self::critBgChrome($wpc_url)) {
+ $wpc_next = self::critBgPastChrome($crit, $wpc_pu[0][1] + strlen($wpc_text), $wpc_rx);
+ $wpc_chrome_veto = ['why' => 'ui-chrome', 'src' => substr((string) $wpc_url, -120)]
+ + ($wpc_next === null ? [] : ['then' => substr((string) $wpc_next[1], -120)]);
+ if ($wpc_next === null) {
+ return ['text' => $wpc_text, 'url' => '', 'matched' => null, 'veto' => $wpc_chrome_veto];
+ }
+ list($wpc_text, $wpc_url, $wpc_matched) = $wpc_next;
+ }
+ return ['text' => $wpc_text, 'url' => $wpc_url, 'matched' => $wpc_matched, 'veto' => $wpc_chrome_veto];
+ }
+
+ private const CRIT_BG_CHROME = '/default-skin|photoswipe|sprite|/icons?[/.-]|loading|spinner|arrow/i';
+
+ private static function critBgChrome($url)
+ {
+ return preg_match(self::CRIT_BG_CHROME, (string) $url) === 1;
+ }
+
+ /**
+ * The first background url() of the crit after offset $from that is not UI chrome and names the rendition of the picture the service
+ * measured as the LCP of a device this render serves, as [matched text, url, the devices it is the LCP of], or null. Only the page's own
+ * lcp.json measures; nothing is looked for when no served device has a measured background LCP, or under policy.off_bg_preload_scan.
+ */
+ private static function critBgPastChrome($css, $from, $rx)
+ {
+ if (!class_exists('wps_ic_atf_observation') || !class_exists('wps_rewriteLogic') || wps_rewriteLogic::bg_preload_scan_off()) {
+ return null;
+ }
+ $devices = wps_rewriteLogic::wpc_combined_crit_on() ? ['mobile', 'desktop'] : [(function_exists('wpc_ua_is_mobile') && wpc_ua_is_mobile()) ? 'mobile' : 'desktop'];
+ $measured = [];
+ foreach ($devices as $device) {
+ $url = wps_ic_atf_observation::lcpBackgroundUrl($device);
+ if ($url !== '') {
+ $measured[$device] = $url;
+ }
+ }
+ if (!$measured || !preg_match_all($rx, (string) substr((string) $css, $from), $found, PREG_SET_ORDER)) {
+ return null;
+ }
+ foreach ($found as $candidate) {
+ if (self::critBgChrome($candidate[2])) {
+ continue;
+ }
+ $matched = [];
+ foreach ($measured as $device => $url) {
+ if (wps_ic_image_preload_set::sameRendition($candidate[2], $url)) {
+ $matched[] = $device;
+ }
+ }
+ if ($matched) {
+ return [$candidate[0], $candidate[2], $matched];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * The image-set() the browser takes for the crit rule that holds the offset: the last standard declaration of the rule, else the last prefixed one. As ['url' => its first
+ * candidate, 'type' => that candidate's mime type or '', 'args' => the text between the function's parentheses, null when the rule never closes them], or null.
+ */
+ private static function critBgSet($css, $offset)
+ {
+ $open = strrpos(substr((string) $css, 0, $offset), '{');
+ $close = strpos((string) $css, '}', $offset);
+ if ($open === false || $close === false) {
+ return null;
+ }
+ $block = substr((string) $css, $open + 1, $close - $open - 1);
+ foreach (['(?<![-w])image-set', '-webkit-image-set'] as $function) {
+ if (!preg_match_all('/background(?:-image)?s*:s*[^;{}]*?(' . $function . ')(s*(?:url(s*(?<q>['"]?)(?<u>[^)'"s]+)k<q>s*)|(?<sq>['"])(?<s>[^'"]+)k<sq>)(?:s*type(s*(?<tq>['"])(?<t>[^'"]+)k<tq>s*))?/i', $block, $matches, PREG_OFFSET_CAPTURE)) {
+ continue;
+ }
+ $last = count($matches[0]) - 1;
+ $paren = $matches[1][$last][1] + strlen($matches[1][$last][0]);
+ $depth = 0;
+ $quote = '';
+ $args = null;
+ for ($i = $paren, $length = strlen($block); $i < $length; $i++) {
+ $char = $block[$i];
+ if ($quote !== '') {
+ if ($char === '\') {
+ $i++;
+ } elseif ($char === $quote) {
+ $quote = '';
+ }
+ } elseif ($char === '"' || $char === "'") {
+ $quote = $char;
+ } elseif ($char === '(') {
+ $depth++;
+ } elseif ($char === ')' && --$depth === 0) {
+ $args = substr($block, $paren + 1, $i - $paren - 1);
+ break;
+ }
+ }
+ $candidate = $matches['u'][$last][0] !== '' ? $matches['u'][$last][0] : $matches['s'][$last][0];
+ return ['url' => html_entity_decode($candidate, ENT_QUOTES), 'type' => isset($matches['t'][$last][0]) ? $matches['t'][$last][0] : '', 'args' => $args];
+ }
+ return null;
+ }
+
+ /** True when a candidate of the set carries a density descriptor (1x, 2x, 1.5x, 96dpi, dppx, dpcm): a screen at 2x paints another file than the first candidate. */
+ private static function critBgDense(array $set)
+ {
+ if ($set['args'] === null) {
+ return false;
+ }
+ $bare = preg_replace('/url(s*(?:"[^"]*"|'[^']*'|[^)]*)s*)|"[^"]*"|'[^']*'/i', ' ', $set['args']);
+ return is_string($bare) && preg_match('/(?<![w.-])(?:d+.?d*|.d+)(?:x|dpi|dppx|dpcm)(?![w-])/i', $bare) === 1;
+ }
+
+ /** The file a browser paints for the set, as [url, mime type or ''], or null: no set, a set the rule never closes, or a url the UI-chrome veto holds back. */
+ private static function critBgPainted($set)
+ {
+ if (!is_array($set) || $set['args'] === null || self::critBgChrome($set['url'])) {
+ return null;
+ }
+ return [$set['url'], $set['type']];
+ }
+
// Bricks marks bg-image elements .bricks-lazy-hidden (background-image:none!important)
// and only its JS — which the delay holds — removes the class: ATF backgrounds paint
// white until the timer. Re-assert every crit background rule at higher specificity
@@ -1075,8 +1497,9 @@
$media = $media_match[1];
}
$id_attr = $style_id !== '' ? ' id="' . $style_id . '"' : '';
+ $hold_attr = preg_match('/bdata-wpc-hold=["']([a-z]{1,16})["']/i', $style_match[1], $hold_match) ? ' data-wpc-hold="' . $hold_match[1] . '"' : '';
$link_tag = '<link rel="' . $style_match[2] . '"' . $id_attr
- . ' href="' . esc_url($sidecar_url) . '" media="' . esc_attr($medi