PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.7
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.7
1.3.7 1.3.6 1.3.5 1.3.4 1.3.3 1.3.2 1.3.1 1.3.0 1.2.4 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 All 33 releases
← All changes | includes/modules/Cache/CacheModule.php +490 -82 1.2.4 → 1.3.7 View file →
@@ -25,8 +25,130 @@
25 25 use XSpeed\Settings_Manager;
26 26
27 27 final class CacheModule extends Module {
28 28
29 + /**
30 + * Default Excluded Cookies.
31 + *
32 + * A constant for the same reason as DEFAULT_IGNORED_QUERY_PARAMS:
33 + * Cache::rewrite_block_lines() needs the list at boot, where building
34 + * the settings schema would translate its labels too early. The schema
35 + * and that fallback both read THIS, so they cannot drift.
36 + *
37 + * @var string[]
38 + */
39 + public const DEFAULT_EXCLUDED_COOKIES = array(
40 + 'comment_author',
41 + '~wordpress_[a-f0-9]+',
42 + 'wp-postpass',
43 + 'wordpress_no_cache',
44 + 'wordpress_logged_in',
45 + 'edd_items_in_cart',
46 + 'woocommerce_items_in_cart',
47 + 'fct_cart_hash',
48 + 'comment_',
49 + 'woocommerce_',
50 + 'wordpress',
51 + 'xf_',
52 + 'edd_',
53 + 'jetpack',
54 + 'yith_wcwl_session_',
55 + 'yith_wrvp_',
56 + 'wpsc_',
57 + 'ecwid',
58 + 'ec_',
59 + 'bookly',
60 + );
61 +
62 + /**
63 + * Default Ignored Query Parameters.
64 + *
65 + * A constant because Cache::sync_query_allowlist() needs this list at
66 + * boot, where building the settings schema would translate its labels
67 + * before WordPress allows it. Both the schema below and that boot-time
68 + * fallback read THIS, so the two cannot drift.
69 + *
70 + * @var string[]
71 + */
72 + public const DEFAULT_IGNORED_QUERY_PARAMS = array(
73 + '__s',
74 + '_ga',
75 + '_ke',
76 + '~[a-zA-Z0-9_-]+_sid',
77 + 'adgroupid',
78 + 'age-verified',
79 + 'ao_noptimize',
80 + 'campaignid',
81 + 'ck_subscriber_id',
82 + 'cn-reloaded',
83 + 'dclid',
84 + 'epik',
85 + 'fb_action_ids',
86 + 'fb_action_types',
87 + 'fb_source',
88 + 'fbclid',
89 + 'gclid',
90 + 'jobid',
91 + 'mc_cid',
92 + 'mc_eid',
93 + 'mkt_tok',
94 + 'msclkid',
95 + 'ref',
96 + // Twitter/X (`ref_src`, `ref_url`) and Facebook (`refid`)
97 + // decorations. Enumerated because param names match
98 + // whole-name: the bare `ref` above no longer absorbs them,
99 + // and a `ref*` glob would over-match `referrer` and
100 + // `refund_id`, which are page-selecting.
101 + 'ref_src',
102 + 'ref_url',
103 + 'refid',
104 + '~session_[a-zA-Z0-9_-]+_alive',
105 + 'sseid',
106 + 'sslid',
107 + 'usqp',
108 + '~utm_[a-zA-Z0-9_-]+',
109 + );
110 +
111 + /**
112 + * Click and campaign IDs added to the defaults in 1.3.6.
113 + *
114 + * Each is unique per click and never changes the page, yet each one
115 + * bypassed the page cache and, with xSpeed Pro, was a new CSS entry to
116 + * build: Google Merchant's `srsltid` and Ads' `gad_*`/`gbraid`/`wbraid`,
117 + * GA4's cross-domain `_gl`, TikTok, X, Instagram, Yandex, HubSpot email
118 + * and LinkedIn IDs. Kept as their own list so the upgrade can add exactly
119 + * these to a saved list without re-adding anything a site removed.
120 + *
121 + * @var string[]
122 + */
123 + public const TRACKING_PARAMS_1_3_6 = array(
124 + '_gl',
125 + '_hsenc',
126 + '_hsmi',
127 + 'gad_campaignid',
128 + 'gad_source',
129 + 'gbraid',
130 + 'igshid',
131 + 'li_fat_id',
132 + 'srsltid',
133 + 'ttclid',
134 + 'twclid',
135 + 'wbraid',
136 + 'yclid',
137 + );
138 +
139 +
140 + /**
141 + * The shipped default list: the base list plus later additions, sorted.
142 + *
143 + * @return string[]
144 + */
145 + public static function default_ignored_query_params(): array {
146 + $all = array_values( array_unique( array_merge( self::DEFAULT_IGNORED_QUERY_PARAMS, self::TRACKING_PARAMS_1_3_6 ) ) );
147 + sort( $all );
148 + return $all;
149 + }
150 +
29 151 public const SLUG = 'cache';
30 152 public const TIER = self::TIER_FREE;
31 153 public const VERSION = '1.0.0';
32 154
@@ -43,11 +165,12 @@
43 165 public const DEFAULT_EXPIRY_HOURS = 24 * 7;
44 166
45 167 public function ui_metadata(): array {
46 168 return array(
47 - 'label' => 'Page Cache',
169 + 'label' => __( 'Page Cache', 'xspeed' ),
48 170 'icon' => 'Database',
49 - 'description' => 'Page caching for non-logged-in visitors.',
171 + 'description' => __( 'Saves each page as a file and serves it to logged-out visitors.', 'xspeed' ),
172 + 'group' => 'cache',
50 173 );
51 174 }
52 175
53 176 /**
@@ -62,9 +185,9 @@
62 185 return array();
63 186 }
64 187
65 188 public function settings_schema(): array {
66 - return array(
189 + $schema = array(
67 190 'cache_expiry' => array(
68 191 'type' => 'int',
69 192 // Matches the wizard's Balanced preset, which is what a fresh
70 193 // install starts on — a shorter module default meant the two
@@ -71,11 +194,11 @@
71 194 // disagreed about what "default" means. (#284)
72 195 'default' => self::DEFAULT_EXPIRY_HOURS,
73 196 'min' => 1,
74 197 'max' => 720,
75 - 'label' => 'Cache Expiry (hours)',
198 + 'label' => __( 'Cache expiry (hours)', 'xspeed' ),
76 199 'unit' => 'hours',
77 - 'description' => 'How long cached pages live before regenerating. 1 to 720 hours (30 days).',
200 + 'description' => __( 'How long a cached page is kept before xSpeed builds it again. 1 to 720 hours (30 days).', 'xspeed' ),
78 201 ),
79 202 'excluded_urls' => array(
80 203 'type' => 'list',
81 204 // Comprehensive LiteSpeed / WP Rocket-parity default URL
@@ -87,9 +210,11 @@
87 210 '/xmlrpc.php',
88 211 '~wp-.*\.php',
89 212 '/feed/',
90 213 'index.php',
91 - '~sitemap(_index)?\.xml',
214 + // `sitemaps?` — SEOPress generates sitemaps.xml (plural).
215 + '~sitemaps?(_index)?\.xml',
216 + '/robots.txt',
92 217 // Bare (no trailing slash) so "contains" matches both
93 218 // /cart and /cart/items — WooCommerce serves both forms.
94 219 '/cart',
95 220 '/checkout',
@@ -101,10 +226,10 @@
101 226 '/edd-api',
102 227 '/wp-login',
103 228 ),
104 229 'item_type' => 'string',
105 - 'label' => 'Excluded URLs',
106 - 'description' => 'One pattern per line. Plain text matches anywhere in the URL (e.g. /cart). Use glob for anchored matches (/cart/* matches /cart/items but not /foo/cart/bar; *.pdf matches PDFs). Prefix with ~ for a raw regex (e.g. ~wp-.*\.php).',
230 + 'label' => __( 'Excluded URLs', 'xspeed' ),
231 + 'description' => __( 'Pages whose URL matches a line here are never cached. Plain text matches anywhere (/cart). A pattern with * matches from the start of the path: /cart/* matches /cart/items but not /shop/cart/items. ~ starts a regex.', 'xspeed' ),
107 232 ),
108 233 'excluded_cookies' => array(
109 234 'type' => 'list',
110 235 // Cookies that signal a logged-in / transactional visitor
@@ -109,40 +234,19 @@
109 234 'type' => 'list',
110 235 // Cookies that signal a logged-in / transactional visitor
111 236 // whose response must not be served from a shared cache.
112 237 // `~` prefix = raw regex (e.g. ~wordpress_[a-f0-9]+). (FBS-82181)
113 - 'default' => array(
114 - 'comment_author',
115 - '~wordpress_[a-f0-9]+',
116 - 'wp-postpass',
117 - 'wordpress_no_cache',
118 - 'wordpress_logged_in',
119 - 'edd_items_in_cart',
120 - 'woocommerce_items_in_cart',
121 - 'fct_cart_hash',
122 - 'comment_',
123 - 'woocommerce_',
124 - 'wordpress',
125 - 'xf_',
126 - 'edd_',
127 - 'jetpack',
128 - 'yith_wcwl_session_',
129 - 'yith_wrvp_',
130 - 'wpsc_',
131 - 'ecwid',
132 - 'ec_',
133 - 'bookly',
134 - ),
238 + 'default' => self::DEFAULT_EXCLUDED_COOKIES,
135 239 'item_type' => 'string',
136 - 'label' => 'Excluded Cookies',
137 - 'description' => 'Skip cache for any visitor whose request carries a cookie whose NAME matches one of these patterns. Plain text = "contains"; glob (woocommerce_*) and ~regex (~wordpress_[a-f0-9]+) supported. One per line.',
240 + 'label' => __( 'Excluded cookies', 'xspeed' ),
241 + 'description' => __( 'Visitors with a cookie whose name matches a line here always get a fresh page. One per line; * and ~regex work.', 'xspeed' ),
138 242 ),
139 243 'bypass_user_agents' => array(
140 244 'type' => 'list',
141 245 'default' => array(),
142 246 'item_type' => 'string',
143 - 'label' => 'Bypass User Agents',
144 - 'description' => 'Substring match against the visitor User-Agent. Matched UAs bypass cache (useful for screenshot bots, internal previews, monitoring). Glob + ~regex supported. One per line.',
247 + 'label' => __( 'Excluded browsers and bots', 'xspeed' ),
248 + 'description' => __( 'Visitors whose user agent contains a line here always get a fresh page. Useful for screenshot bots and uptime monitors.', 'xspeed' ),
145 249 ),
146 250 'ignored_query_params' => array(
147 251 'type' => 'list',
148 252 // Analytics / ad / session query keys stripped before the
@@ -149,63 +253,94 @@
149 253 // cache key is computed, so /post?utm_source=x and /post
150 254 // share one entry. `~` prefix = raw regex. (FBS-82181)
151 255 // Matched whole-name, so every entry here means the param
152 256 // it names and nothing that merely contains it.
153 - 'default' => array(
154 - '__s',
155 - '_ga',
156 - '_ke',
157 - '~[a-zA-Z0-9_-]+_sid',
158 - 'adgroupid',
159 - 'age-verified',
160 - 'ao_noptimize',
161 - 'campaignid',
162 - 'ck_subscriber_id',
163 - 'cn-reloaded',
164 - 'dclid',
165 - 'epik',
166 - 'fb_action_ids',
167 - 'fb_action_types',
168 - 'fb_source',
169 - 'fbclid',
170 - 'gclid',
171 - 'jobid',
172 - 'mc_cid',
173 - 'mc_eid',
174 - 'mkt_tok',
175 - 'msclkid',
176 - 'ref',
177 - // Twitter/X (`ref_src`, `ref_url`) and Facebook (`refid`)
178 - // decorations. Enumerated because param names match
179 - // whole-name: the bare `ref` above no longer absorbs them,
180 - // and a `ref*` glob would over-match `referrer` and
181 - // `refund_id`, which are page-selecting.
182 - 'ref_src',
183 - 'ref_url',
184 - 'refid',
185 - '~session_[a-zA-Z0-9_-]+_alive',
186 - 'sseid',
187 - 'sslid',
188 - 'usqp',
189 - '~utm_[a-zA-Z0-9_-]+',
190 - ),
257 + 'default' => self::default_ignored_query_params(),
191 258 'item_type' => 'string',
192 - 'label' => 'Ignored Query Parameters',
193 - 'description' => 'Query keys removed from the URL before computing the cache key, so /post?utm_source=x and /post share a cache entry. Defaults cover the common analytics + ad + session params. Each entry matches a whole param name — plain text is an exact name, and glob (utm_*) or ~regex are anchored too, so "ref" does not also match "preference". One per line.',
259 + 'label' => __( 'Ignored query parameters', 'xspeed' ),
260 + 'advanced' => true,
261 + 'description' => __( 'URL parameters to ignore, so /post?utm_source=x gets the same cached page as /post. Each line matches a whole parameter name.', 'xspeed' ),
194 262 ),
195 263 'purge_on_upgrade' => array(
196 264 'type' => 'bool',
197 265 'default' => true,
198 - 'label' => 'Purge After Updates',
199 - 'description' => 'Clear the page cache when a plugin, theme or WordPress core is updated. Cached HTML is produced by the code being replaced, so leaving it in place serves pre-update markup — and links to minified assets that no longer exist — until the cache expires. Translation updates are ignored, since a language pack changes no markup a cached page depends on. Updates to xSpeed itself always purge, regardless of this setting.',
266 + 'label' => __( 'Clear cache after updates', 'xspeed' ),
267 + 'description' => __( 'Clear the page cache when a plugin, theme or WordPress is updated, so visitors never get old pages with broken asset links.', 'xspeed' ),
200 268 ),
201 269 'mobile_separate' => array(
202 270 'type' => 'bool',
203 271 'default' => false,
204 - 'label' => 'Separate Mobile Cache',
205 - 'description' => 'Keep mobile and desktop responses in separate cache buckets. Turn on for AMP, mobile-specific themes (WPtouch / Jetpack mobile theme), or any setup that serves different HTML by device.',
272 + 'label' => __( 'Separate mobile cache', 'xspeed' ),
273 + 'description' => __( 'Keep a separate cached copy for phones. Turn on only if your theme or plugins show different pages on mobile.', 'xspeed' ),
206 274 ),
275 + 'edge_provider' => array(
276 + 'type' => 'enum',
277 + 'default' => 'auto',
278 + 'options' => array( 'auto', 'off', 'cloudflare', 'fastly', 'varnish', 'nginx', 'akamai', 'cloudfront', 'google', 'keycdn', 'bunny', 'sucuri', 'incapsula', 'generic', 'custom' ),
279 + 'option_labels' => array(
280 + 'auto' => 'Detect automatically',
281 + 'off' => 'Off — send nothing',
282 + 'cloudflare' => 'Cloudflare',
283 + 'varnish' => 'Varnish',
284 + 'nginx' => 'nginx proxy cache',
285 + 'cloudfront' => 'Amazon CloudFront',
286 + 'google' => 'Google Cloud CDN',
287 + 'keycdn' => 'KeyCDN',
288 + 'bunny' => 'Bunny',
289 + // These four cannot be presented as supported on the same
290 + // footing as the ones above. Vendor documentation either
291 + // does not establish that they honour what we send, or
292 + // establishes that they ignore origin cache headers until
293 + // the property is configured to respect them — Akamai
294 + // caches for a theoretically infinite time by default, and
295 + // Sucuri's default caching level ignores the headers
296 + // outright. Naming them without the caveat would promise a
297 + // protection the CDN is not currently giving.
298 + 'fastly' => 'Fastly (needs CDN configuration)',
299 + 'akamai' => 'Akamai (needs CDN configuration)',
300 + 'sucuri' => 'Sucuri (needs CDN configuration)',
301 + 'incapsula' => 'Imperva / Incapsula (needs CDN configuration)',
302 + 'generic' => 'Something else',
303 + 'custom' => 'Custom headers',
304 + ),
305 + 'label' => __( 'CDN or proxy in front', 'xspeed' ),
306 + 'description' => __( 'Tells your CDN or proxy not to store pages xSpeed does not cache. Leave on Detect automatically unless you know your provider.', 'xspeed' ),
307 + 'advanced' => true,
308 + 'info_title' => __( 'Cache in front of this site', 'xspeed' ),
309 + 'info' => __( 'Naming your provider narrows the headers to the one it reads. Detect automatically works it out per request and otherwise sends a set every cache ignores unless it understands it, so it is safe not to know. Run "wp xspeed cache edge" to see what was detected and what gets sent.', 'xspeed' )
310 + ),
311 + 'edge_custom_headers' => array(
312 + 'type' => 'list',
313 + 'default' => array(),
314 + 'item_type' => 'string',
315 + 'label' => __( 'Custom CDN headers', 'xspeed' ),
316 + 'advanced' => true,
317 + 'dependsOn' => array( 'field' => 'edge_provider', 'value' => 'custom' ),
318 + 'description' => __( 'One header per line, as Name: value, for example "Surrogate-Control: no-store". Lines starting with # are ignored.', 'xspeed' ),
319 + 'info_title' => __( 'Custom edge headers', 'xspeed' ),
320 + 'info' => __( 'These replace the headers xSpeed would have picked for your CDN. Two baselines are still added underneath: a Cache-Control, and "X-Accel-Expires: 0" for a page cache running in nginx on your own server. Name either one yourself and yours is used instead. Values containing $, % or a backslash are dropped — the same pairs go into nginx and Apache directives, where those cannot be escaped safely. Content-Length, Content-Encoding, Content-Type, Transfer-Encoding, Set-Cookie and Location are refused.', 'xspeed' )
321 + ),
207 322 );
323 +
324 + // LiteSpeed-only opt-in (#509): meaningless on any other server, so
325 + // the field only exists in the schema where it can act — elsewhere the
326 + // stored value survives via preserved_keys(). Inserted right after
327 + // mobile_separate, its sibling static-fast-path trade-off.
328 + if ( \XSpeed\Server::LITESPEED === \XSpeed\Server::type() ) {
329 + $litespeed = array(
330 + 'litespeed_static_rewrite' => array(
331 + 'type' => 'bool',
332 + 'default' => false,
333 + 'label' => __( 'LiteSpeed static fast path', 'xspeed' ),
334 + 'advanced' => true,
335 + 'description' => __( 'LiteSpeed serves cached pages without running PHP, which is faster on slow hosts. These visits are not counted in the dashboard hit ratio.', 'xspeed' ),
336 + ),
337 + );
338 + $pos = (int) array_search( 'mobile_separate', array_keys( $schema ), true ) + 1;
339 + $schema = array_slice( $schema, 0, $pos, true ) + $litespeed + array_slice( $schema, $pos, null, true );
340 + }
341 +
342 + return $schema;
208 343 }
209 344
210 345 /**
211 346 * `mobile_separate_review` lives outside the schema: migration sets it
@@ -218,9 +353,18 @@
218 353 *
219 354 * @return string[]
220 355 */
221 356 public function preserved_keys(): array {
222 - return array( 'mobile_separate_review' );
357 + $keys = array( 'mobile_separate_review' );
358 + // On non-LiteSpeed servers the litespeed_static_rewrite field is not
359 + // in the schema (see settings_schema()), so a schema-driven save
360 + // would silently drop a value chosen while the site ran LiteSpeed.
361 + // Preserve it so moving LiteSpeed → other → LiteSpeed keeps the
362 + // user's choice. On LiteSpeed itself the schema owns the key.
363 + if ( \XSpeed\Server::LITESPEED !== \XSpeed\Server::type() ) {
364 + $keys[] = 'litespeed_static_rewrite';
365 + }
366 + return $keys;
223 367 }
224 368
225 369 /**
226 370 * Seed per-module option from the legacy xspeed_options blob if we
@@ -352,19 +496,53 @@
352 496 'name' => 'budget',
353 497 'description' => 'Seconds to spend before stopping between steps. Default 120.',
354 498 'optional' => true,
355 499 ),
500 + array(
501 + 'type' => 'assoc',
502 + 'name' => 'measure-score',
503 + 'description' => 'auto (default) measures when the stored score is stale and after changes land; never reuses the stored score; always measures even for a dry run.',
504 + 'optional' => true,
505 + 'options' => array( 'auto', 'never', 'always' ),
506 + ),
356 507 ),
357 508 ),
358 509 array(
510 + 'name' => 'xspeed purge',
511 + 'callback' => array( $this, 'cli_purge' ),
512 + 'shortdesc' => 'Clear every cache xSpeed manages — page and static files, REST responses, minified assets, the object cache and the configured edge — and report per store what was cleared, what was skipped and why. Use --type to clear just one.',
513 + 'ai_hint' => 'Clear the cache after a change is live on the server but visitors still see the old version. Purges everything by default; --type=page for the local HTML only, --type=cloudflare for the edge only. Exits non-zero if a store that IS configured refused to purge, so its output can be trusted rather than assumed.',
514 + 'synopsis' => array(
515 + array(
516 + 'type' => 'assoc',
517 + 'name' => 'type',
518 + 'description' => 'What to clear: all (default), page, object, cloudflare, cdn — or a group name (edge). Comma-separate to clear several.',
519 + 'optional' => true,
520 + ),
521 + array(
522 + 'type' => 'assoc',
523 + 'name' => 'cause',
524 + 'description' => 'Label recorded in the purge log, so `wp xspeed cache purge-log` can tell this run apart from a click. Default "CLI".',
525 + 'optional' => true,
526 + ),
527 + array(
528 + 'type' => 'assoc',
529 + 'name' => 'format',
530 + 'description' => 'table (default, one line per store) or json (the full report, for scripts).',
531 + 'optional' => true,
532 + 'options' => array( 'table', 'json' ),
533 + ),
534 + ),
535 + ),
536 + array(
359 537 'name' => 'xspeed cache',
360 538 'callback' => array( $this, 'cli_handler' ),
361 - 'shortdesc' => 'Inspect the Cache module: `status` (settings), `inventory` (which pages are cached, and how old), `size` (where the disk usage goes), `purge-log` (what cleared the cache, when and why), `purge-url <url>` to clear one page, `recheck-rewrite` to re-run the static-rewrite probe, or `nginx-config` to print the unified nginx server-block for pasting into a vhost (site-wide purge / toggle use the dedicated commands).',
539 + 'shortdesc' => 'Inspect the Cache module: `status` (settings), `inventory` (which pages are cached, and how old), `size` (where the disk usage goes), `purge-log` (what cleared the cache, when and why), `purge-url <url>` to clear one page, `recheck-rewrite` to re-run the static-rewrite probe, or `nginx-config` to print the unified nginx server-block for pasting into a vhost, or `edge` to show which cache is in front of the site and what xSpeed tells it. To clear the whole site use `wp xspeed purge`.',
362 540 'synopsis' => array(
363 541 array(
364 542 'type' => 'positional',
365 543 'name' => 'action',
366 - 'options' => array( 'status', 'inventory', 'size', 'purge-log', 'purge-url', 'recheck-rewrite', 'nginx-config' ),
544 + 'options' => array( 'status', 'inventory', 'size', 'purge-log', 'purge-url', 'recheck-rewrite', 'nginx-config', 'edge' ),
367 545 'optional' => true,
368 546 ),
369 547 array(
370 548 'type' => 'positional',
@@ -411,8 +589,9 @@
411 589 array(
412 590 'aggressiveness' => (string) ( $assoc['aggressiveness'] ?? 'standard' ),
413 591 'dry_run' => isset( $assoc['dry-run'] ),
414 592 'budget_seconds' => isset( $assoc['budget'] ) ? (int) $assoc['budget'] : 120,
593 + 'measure_score' => (string) ( $assoc['measure-score'] ?? 'auto' ),
415 594 )
416 595 );
417 596
418 597 if ( is_wp_error( $result ) ) {
@@ -420,8 +599,14 @@
420 599 return;
421 600 }
422 601
423 602 if ( ! empty( $result['dry_run'] ) ) {
603 + // The summary carries the score AND its age. Printing the plan
604 + // without it left the one number a reader wants off the only
605 + // command they run before deciding to apply anything.
606 + if ( isset( $result['message'] ) ) {
607 + \WP_CLI::log( (string) $result['message'] );
608 + }
424 609 \WP_CLI::log( 'Plan (' . count( $result['plan'] ) . ' steps, nothing applied):' );
425 610 foreach ( $result['plan'] as $step ) {
426 611 \WP_CLI::log( ' - ' . $step['change'] . ' [' . $step['tier'] . ']' );
427 612 }
@@ -445,12 +630,149 @@
445 630 \WP_CLI::log( ' ! ' . $row['issue'] . ( '' !== $row['fix'] ? ' — ' . $row['fix'] : '' ) );
446 631 }
447 632
448 633 if ( ! empty( $result['applied'] ) ) {
449 - \WP_CLI::success( count( $result['applied'] ) . ' change(s) applied and verified.' );
634 + // "applied and verified" was more than the checks earn. They read
635 + // HTML in PHP and cannot run JavaScript, so this line was telling
636 + // someone the site was fine when the only honest claim is that
637 + // nothing in the markup looked broken.
638 + \WP_CLI::success( count( $result['applied'] ) . ' change(s) applied; HTML checks passed.' );
639 +
640 + if ( ! empty( $result['verify_urls'] ) ) {
641 + \WP_CLI::log( '' );
642 + \WP_CLI::log( 'Now open these and check they render, with no console errors:' );
643 + foreach ( $result['verify_urls'] as $u ) {
644 + \WP_CLI::log( ' ' . $u );
645 + }
646 + }
450 647 }
451 648 }
452 649
650 + /**
651 + * `wp xspeed purge` — clear every cache xSpeed owns, in one call.
652 + *
653 + * Reports per store rather than printing a success banner, because the
654 + * banner was the bug: a site whose Cloudflare token had lost its purge
655 + * permission saw "cache cleared" and kept serving stale HTML from the
656 + * edge. What is skipped is as much of the answer as what is cleared, so
657 + * every skip prints its reason.
658 + *
659 + * Exit code follows the same distinction. A store that is not configured
660 + * has nothing to clear and does not fail the run — otherwise every CI
661 + * pipeline on a site without Redis goes red for a purge that did exactly
662 + * what it should. A store that IS configured and refused is a failure.
663 + *
664 + * There is deliberately no `--url`: WP-CLI reserves that flag for
665 + * multisite site selection and consumes it before a handler ever sees it.
666 + * Clearing one page is `wp xspeed cache purge-url <url>`.
667 + *
668 + * @param array<int,string> $args Positional args (unused).
669 + * @param array<string,string> $assoc Flags.
670 + */
671 + public function cli_purge( array $args, array $assoc ): void {
672 + unset( $args );
673 +
674 + $requested = array_values(
675 + array_filter(
676 + array_map( 'trim', explode( ',', (string) ( $assoc['type'] ?? 'all' ) ) )
677 + )
678 + );
679 + if ( ! $requested ) {
680 + $requested = array( 'all' );
681 + }
682 +
683 + $accepted = \XSpeed\Purge_Runner::accepted_types();
684 + $unknown = array_diff( $requested, $accepted );
685 + if ( $unknown ) {
686 + // Refuse before purging anything: a typo in --type must not
687 + // quietly clear a DIFFERENT store than the one named.
688 + \WP_CLI::error(
689 + sprintf(
690 + 'Unknown purge type: %s. Expected one of: %s',
691 + implode( ', ', $unknown ),
692 + implode( ', ', $accepted )
693 + )
694 + );
695 + return;
696 + }
697 +
698 + $cause = isset( $assoc['cause'] ) && '' !== trim( (string) $assoc['cause'] ) ? trim( (string) $assoc['cause'] ) : 'CLI';
699 + $report = \XSpeed\Purge_Runner::run( $requested, $cause );
700 +
701 + if ( 'json' === ( $assoc['format'] ?? 'table' ) ) {
702 + // The report goes to STDOUT alone so `... --format=json | jq` works;
703 + // the failure message goes to STDERR via ::error, which is also
704 + // what produces the non-zero exit.
705 + \WP_CLI::line( (string) wp_json_encode( $report ) );
706 + if ( ! $report['ok'] ) {
707 + \WP_CLI::error( 'One or more cache stores failed to purge; see the report above.' );
708 + }
709 + return;
710 + }
711 +
712 + $cleared = 0;
713 + $skipped = 0;
714 + $failed = 0;
715 + foreach ( $report['types'] as $row ) {
716 + switch ( $row['status'] ) {
717 + case \XSpeed\Purge_Runner::CLEARED:
718 + ++$cleared;
719 + \WP_CLI::log( sprintf( ' cleared %s%s', $row['label'], self::purge_amount( $row ) ) );
720 + break;
721 + case \XSpeed\Purge_Runner::FAILED:
722 + ++$failed;
723 + \WP_CLI::log( sprintf( ' FAILED %s — %s', $row['label'], $row['reason'] ) );
724 + break;
725 + default:
726 + ++$skipped;
727 + \WP_CLI::log( sprintf( ' skipped %s — %s', $row['label'], $row['reason'] ) );
728 + }
729 + }
730 +
731 + if ( $failed ) {
732 + \WP_CLI::error(
733 + sprintf(
734 + '%d of %d cache store(s) failed to purge; %d cleared, %d skipped.',
735 + $failed,
736 + count( $report['types'] ),
737 + $cleared,
738 + $skipped
739 + )
740 + );
741 + return;
742 + }
743 +
744 + if ( ! $cleared ) {
745 + // Not a success banner: nothing was purged, and saying so is the
746 + // honest answer for a --type nobody has configured.
747 + \WP_CLI::log( sprintf( 'Nothing to purge — %d store(s) skipped.', $skipped ) );
748 + return;
749 + }
750 +
751 + \WP_CLI::success( sprintf( 'Purged %d cache store(s); %d skipped.', $cleared, $skipped ) );
752 + }
753 +
754 + /**
755 + * The " — 42 entries (1.3 MB)" tail on a cleared line.
756 + *
757 + * Entries and bytes are both optional: a Redis FLUSHALL reports neither,
758 + * and printing "0 entries" for it would read as an empty cache rather
759 + * than an uncountable one.
760 + *
761 + * @param array{entries:int|null,bytes:int|null} $row Report row.
762 + */
763 + private static function purge_amount( array $row ): string {
764 + $parts = array();
765 + if ( null !== $row['entries'] ) {
766 + $parts[] = sprintf( '%d entr%s', $row['entries'], 1 === (int) $row['entries'] ? 'y' : 'ies' );
767 + }
768 + if ( null !== $row['bytes'] && $row['bytes'] > 0 ) {
769 + $parts[] = size_format( $row['bytes'], 1 );
770 + }
771 +
772 + return $parts ? ' — ' . implode( ', ', $parts ) : '';
773 + }
774 +
453 775 public function cli_handler( array $args, array $assoc ): void {
454 776 $action = isset( $args[0] ) ? (string) $args[0] : 'status';
455 777 $limit = isset( $assoc['limit'] ) ? max( 1, (int) $assoc['limit'] ) : 20;
456 778
@@ -629,13 +951,99 @@
629 951 $this->cli_purge_log( $limit );
630 952 return;
631 953 }
632 954
955 + if ( 'edge' === $action ) {
956 + $this->cli_edge();
957 + return;
958 + }
959 +
633 960 $opts = Settings_Manager::get( self::SLUG );
634 961 \WP_CLI::log( 'cache_expiry ' . $opts['cache_expiry'] . 'h' );
635 962 \WP_CLI::log( 'excluded_urls ' . count( $opts['excluded_urls'] ) . ' entries' );
636 963 foreach ( $opts['excluded_urls'] as $u ) {
637 964 \WP_CLI::log( ' - ' . $u );
965 + }
966 + $edge = \XSpeed\Edge_Provider::detect();
967 + \WP_CLI::log( 'edge ' . ( '' !== $edge['provider'] ? $edge['provider'] : $edge['confidence'] ) . ' (' . $edge['source'] . ')' );
968 + }
969 +
970 + /**
971 + * `wp xspeed cache edge` — what we think is in front, and what we say to it.
972 + *
973 + * Worth printing even when nothing is held back. "You are behind
974 + * Cloudflare, and a Cache Rule set to ignore origin headers overrides
975 + * anything xSpeed sends" is the answer to a support question that
976 + * otherwise costs someone a week, and it is true whether or not a hold
977 + * ever fires.
978 + */
979 + private function cli_edge(): void {
980 + $answer = \XSpeed\Edge_Provider::detect();
981 +
982 + \WP_CLI::log( 'provider ' . ( '' !== $answer['provider'] ? $answer['provider'] : '(none named)' ) );
983 + \WP_CLI::log( 'confidence ' . $answer['confidence'] );
984 + \WP_CLI::log( 'source ' . $answer['source'] );
985 +
986 + // A pin outranks detection by design, so nothing re-checks it on the
987 + // site's behalf. Saying the two disagree is the whole mechanism by
988 + // which a site that changed CDN ever finds out.
989 + $sniffed = \XSpeed\Edge_Provider::sniffed();
990 + if ( in_array( $answer['source'], array( 'setting', 'constant', 'filter' ), true )
991 + && '' !== $sniffed['provider']
992 + && $sniffed['provider'] !== $answer['provider'] ) {
993 + \WP_CLI::warning(
994 + sprintf(
995 + 'This request looks like %s, but the provider is pinned to %s. If the site moved, change it — the pinned answer is also baked into the drop-in and the server rules.',
996 + $sniffed['provider'],
997 + '' !== $answer['provider'] ? $answer['provider'] : 'off'
998 + )
999 + );
1000 + }
1001 +
1002 + if ( \XSpeed\Edge_Provider::is_off( $answer ) ) {
1003 + \WP_CLI::log( '' );
1004 + \WP_CLI::log( 'Nothing is sent: this is switched off.' );
1005 + return;
1006 + }
1007 +
1008 + // Resolved through edge_headers_for() rather than straight off the
1009 + // provider, so this prints what the serve path would ACTUALLY send —
1010 + // including `X-XSpeed-Edge-Hold`, and including the evidence gate.
1011 + // Listing the provider's raw set ignored that gate and told operators
1012 + // a first render would be held on a site where it would not be.
1013 + //
1014 + // `bake`, not `request`. Two reasons, and the second one matters:
1015 + // this command answers for the site rather than for one response, and
1016 + // `request` fires `xspeed_edge_optimization_pending`, whose Pro
1017 + // listener resolves the CSS plan — which by its own description is
1018 + // what queues a build. A read-only command must not burn a build
1019 + // slot, quarantine an entry or purge a page just by being run, and
1020 + // under WP-CLI it would do all three against the home page.
1021 + $bypass = \XSpeed\Cache::edge_headers_for( 'BYPASS', 'bake', 'logged-in' );
1022 + $miss = \XSpeed\Cache::edge_headers_for( 'MISS', 'bake' );
1023 +
1024 + \WP_CLI::log( '' );
1025 + \WP_CLI::log( 'On a page xSpeed refuses to cache (a cart, a logged-in view):' );
1026 + foreach ( $bypass as $name => $value ) {
1027 + \WP_CLI::log( sprintf( ' %s: %s', $name, $value ) );
1028 + }
1029 +
1030 + \WP_CLI::log( '' );
1031 + if ( array() === $miss ) {
1032 + \WP_CLI::log( 'On a first render: nothing. A MISS is a performance hedge, so it is held only where a cache in front was detected — and none was. Name the provider in Cache In Front Of This Site to cover first renders too.' );
1033 + } else {
1034 + \WP_CLI::log( 'On a first render:' );
1035 + foreach ( $miss as $name => $value ) {
1036 + \WP_CLI::log( sprintf( ' %s: %s', $name, $value ) );
1037 + }
1038 + }
1039 +
1040 + \WP_CLI::log( '' );
1041 + \WP_CLI::log( 'X-XSpeed-Edge-Hold names why a response was held: bypass, bypass-shape, miss, mobile-split or pending. No header means nothing was held.' );
1042 +
1043 + if ( 'cloudflare' === $answer['provider'] ) {
1044 + \WP_CLI::log( '' );
1045 + \WP_CLI::log( 'A Cloudflare Cache Rule whose Edge TTL is "Ignore cache-control header and use this TTL" overrides all of the above. Use "Respect origin TTL" on that rule if pages are still being stored.' );
638 1046 }
639 1047 }
640 1048
641 1049 /** `wp xspeed cache inventory [--limit=N]` — which pages are cached, and how old. */