PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.3
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.3
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 1.1.5 1.1.6 1.1.7 1.1.8 All 29 releases
← All changes | includes/modules/Cache/CacheModule.php +939 -20 1.0.31.3.3 View file →
@@ -18,73 +18,284 @@
18 18 declare(strict_types=1);
19 19
20 20 namespace XSpeed\Modules\Cache;
21 21
22 +defined( 'ABSPATH' ) || exit;
23 +
22 24 use XSpeed\Module;
23 25 use XSpeed\Settings_Manager;
24 26
25 27 final class CacheModule extends Module {
26 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 +
27 112 public const SLUG = 'cache';
28 113 public const TIER = self::TIER_FREE;
29 114 public const VERSION = '1.0.0';
30 115
116 + /**
117 + * Default cache lifetime in hours (7 days).
118 + *
119 + * Named so the readers that need a fallback share ONE value with the
120 + * schema below. Three of them carried their own hardcoded `?? 24`, which
121 + * silently became a stale copy the moment the default moved. They are
122 + * unreachable today — Settings_Manager::get() always merges defaults —
123 + * but an unreachable wrong number is still a trap for the next change.
124 + * (#284 B5)
125 + */
126 + public const DEFAULT_EXPIRY_HOURS = 24 * 7;
127 +
31 128 public function ui_metadata(): array {
32 129 return array(
33 - 'label' => 'Cache',
130 + 'label' => __( 'Page Cache', 'xspeed' ),
34 131 'icon' => 'Database',
35 - 'description' => 'Page caching for non-logged-in visitors.',
132 + 'description' => __( 'Page caching for non-logged-in visitors.', 'xspeed' ),
36 133 );
37 134 }
38 135
136 + /**
137 + * @inheritDoc
138 + *
139 + * Nothing exempt. Purging only ever touches xSpeed's own cache, so on an
140 + * occupied site the setting is inert either way — but a host installing xSpeed
141 + * on a user's behalf should leave nothing switched on that the user did not
142 + * ask for, and "inert today" is a weak reason to make an exception.
143 + */
144 + public function conflict_safe_exempt(): array {
145 + return array();
146 + }
147 +
39 148 public function settings_schema(): array {
40 149 return array(
41 150 'cache_expiry' => array(
42 151 'type' => 'int',
43 - 'default' => 24,
152 + // Matches the wizard's Balanced preset, which is what a fresh
153 + // install starts on — a shorter module default meant the two
154 + // disagreed about what "default" means. (#284)
155 + 'default' => self::DEFAULT_EXPIRY_HOURS,
44 156 'min' => 1,
45 157 'max' => 720,
46 - 'label' => 'Cache Expiry (hours)',
47 - 'description' => 'How long cached pages live before regenerating. 1 to 720 hours (30 days).',
158 + 'label' => __( 'Cache Expiry (hours)', 'xspeed' ),
159 + 'unit' => 'hours',
160 + 'description' => __( 'How long cached pages live before regenerating. 1 to 720 hours (30 days).', 'xspeed' ),
48 161 ),
49 162 'excluded_urls' => array(
50 163 'type' => 'list',
51 - 'default' => array(),
164 + // Comprehensive LiteSpeed / WP Rocket-parity default URL
165 + // exclusions (FBS-82181). Plain text = "contains", glob via
166 + // * ? [ ], or a `~` prefix for raw regex (e.g. ~wp-.*\.php).
167 + 'default' => array(
168 + '/wp-admin/',
169 + '/wp-json/',
170 + '/xmlrpc.php',
171 + '~wp-.*\.php',
172 + '/feed/',
173 + 'index.php',
174 + // `sitemaps?` — SEOPress generates sitemaps.xml (plural).
175 + '~sitemaps?(_index)?\.xml',
176 + '/robots.txt',
177 + // Bare (no trailing slash) so "contains" matches both
178 + // /cart and /cart/items — WooCommerce serves both forms.
179 + '/cart',
180 + '/checkout',
181 + '/my-account',
182 + 'ao_noptirocket',
183 + 'ao_speedup_cachebuster',
184 + 'removed_item',
185 + '/wc-api',
186 + '/edd-api',
187 + '/wp-login',
188 + ),
52 189 'item_type' => 'string',
53 - 'label' => 'Excluded URLs',
54 - 'description' => 'One path per line. Plain text matches anywhere in the URL (e.g. /cart). Use glob syntax for anchored matches: /cart/* matches /cart/items but not /foo/cart/bar; *.pdf matches PDFs.',
190 + 'label' => __( 'Excluded URLs', 'xspeed' ),
191 + '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).', 'xspeed' ),
55 192 ),
56 193 'excluded_cookies' => array(
57 194 'type' => 'list',
58 - 'default' => array(),
195 + // Cookies that signal a logged-in / transactional visitor
196 + // whose response must not be served from a shared cache.
197 + // `~` prefix = raw regex (e.g. ~wordpress_[a-f0-9]+). (FBS-82181)
198 + 'default' => self::DEFAULT_EXCLUDED_COOKIES,
59 199 'item_type' => 'string',
60 - 'label' => 'Excluded Cookies',
61 - 'description' => 'Skip cache for any visitor whose request carries a cookie whose NAME matches one of these patterns. Glob supported (comment_author_*, woocommerce_*). One per line.',
200 + 'label' => __( 'Excluded Cookies', 'xspeed' ),
201 + '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.', 'xspeed' ),
62 202 ),
63 203 'bypass_user_agents' => array(
64 204 'type' => 'list',
65 205 'default' => array(),
66 206 'item_type' => 'string',
67 - 'label' => 'Bypass User Agents',
68 - 'description' => 'Substring match against the visitor User-Agent. Matched UAs bypass cache (useful for screenshot bots, internal previews, monitoring). One per line.',
207 + 'label' => __( 'Bypass User Agents', 'xspeed' ),
208 + '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.', 'xspeed' ),
69 209 ),
70 210 'ignored_query_params' => array(
71 211 'type' => 'list',
72 - 'default' => array( 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid' ),
212 + // Analytics / ad / session query keys stripped before the
213 + // cache key is computed, so /post?utm_source=x and /post
214 + // share one entry. `~` prefix = raw regex. (FBS-82181)
215 + // Matched whole-name, so every entry here means the param
216 + // it names and nothing that merely contains it.
217 + 'default' => self::DEFAULT_IGNORED_QUERY_PARAMS,
73 218 'item_type' => 'string',
74 - 'label' => 'Ignored Query Parameters',
75 - '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 params. One per line.',
219 + 'label' => __( 'Ignored Query Parameters', 'xspeed' ),
220 + '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.', 'xspeed' ),
76 221 ),
222 + 'purge_on_upgrade' => array(
223 + 'type' => 'bool',
224 + 'default' => true,
225 + 'label' => __( 'Purge After Updates', 'xspeed' ),
226 + '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.', 'xspeed' ),
227 + ),
77 228 'mobile_separate' => array(
78 229 'type' => 'bool',
79 230 'default' => false,
80 - 'label' => 'Separate Mobile Cache',
81 - '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.',
231 + 'label' => __( 'Separate Mobile Cache', 'xspeed' ),
232 + '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.', 'xspeed' ),
82 233 ),
234 + 'edge_provider' => array(
235 + 'type' => 'enum',
236 + 'default' => 'auto',
237 + 'options' => array( 'auto', 'off', 'cloudflare', 'fastly', 'varnish', 'nginx', 'akamai', 'cloudfront', 'google', 'keycdn', 'bunny', 'sucuri', 'incapsula', 'generic', 'custom' ),
238 + 'option_labels' => array(
239 + 'auto' => 'Detect automatically',
240 + 'off' => 'Off — send nothing',
241 + 'cloudflare' => 'Cloudflare',
242 + 'varnish' => 'Varnish',
243 + 'nginx' => 'nginx proxy cache',
244 + 'cloudfront' => 'Amazon CloudFront',
245 + 'google' => 'Google Cloud CDN',
246 + 'keycdn' => 'KeyCDN',
247 + 'bunny' => 'Bunny',
248 + // These four cannot be presented as supported on the same
249 + // footing as the ones above. Vendor documentation either
250 + // does not establish that they honour what we send, or
251 + // establishes that they ignore origin cache headers until
252 + // the property is configured to respect them — Akamai
253 + // caches for a theoretically infinite time by default, and
254 + // Sucuri's default caching level ignores the headers
255 + // outright. Naming them without the caveat would promise a
256 + // protection the CDN is not currently giving.
257 + 'fastly' => 'Fastly (needs CDN configuration)',
258 + 'akamai' => 'Akamai (needs CDN configuration)',
259 + 'sucuri' => 'Sucuri (needs CDN configuration)',
260 + 'incapsula' => 'Imperva / Incapsula (needs CDN configuration)',
261 + 'generic' => 'Something else',
262 + 'custom' => 'Custom headers',
263 + ),
264 + 'label' => __( 'Cache In Front Of This Site', 'xspeed' ),
265 + 'description' => __( 'Ask a CDN or proxy in front of your site not to store pages xSpeed refused to cache. Leave it on Detect automatically unless you know what is in front of you; the marked providers ignore origin headers until you configure them to respect it.', 'xspeed' ),
266 + 'info_title' => __( 'Cache in front of this site', 'xspeed' ),
267 + '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' )
268 + ),
269 + 'edge_custom_headers' => array(
270 + 'type' => 'list',
271 + 'default' => array(),
272 + 'item_type' => 'string',
273 + 'label' => __( 'Custom Edge Headers', 'xspeed' ),
274 + 'dependsOn' => array( 'field' => 'edge_provider', 'value' => 'custom' ),
275 + 'description' => __( 'One header per line, as Name: value — for example "Surrogate-Control: no-store". Lines starting with # are ignored.', 'xspeed' ),
276 + 'info_title' => __( 'Custom edge headers', 'xspeed' ),
277 + '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' )
278 + ),
83 279 );
84 280 }
85 281
86 282 /**
283 + * `mobile_separate_review` lives outside the schema: migration sets it
284 + * (bool) when a source plugin had "separate mobile cache" on, so the
285 + * dashboard can prompt the user to re-enable it deliberately instead of
286 + * silently importing it (which would kill the device-blind static fast
287 + * path). Without preserving it here, the first schema-driven cache save
288 + * would rebuild the option from the schema alone and drop the flag before
289 + * the user ever saw the prompt. (FBS-83145)
290 + *
291 + * @return string[]
292 + */
293 + public function preserved_keys(): array {
294 + return array( 'mobile_separate_review' );
295 + }
296 +
297 + /**
87 298 * Seed per-module option from the legacy xspeed_options blob if we
88 299 * haven't done so yet. Idempotent — once xspeed_module_cache exists
89 300 * or the legacy keys are gone, this is a no-op. Runs on both boot
90 301 * and activate so installs on every code path are covered.
@@ -90,14 +301,79 @@
90 301 * and activate so installs on every code path are covered.
91 302 */
92 303 public function boot(): void {
93 304 $this->seed_from_legacy_if_needed();
305 +
306 + // Keep every mobile_separate-dependent artifact (the drop-in's
307 + // `.mobile-separate` flag, the device-blind server rewrite, and the
308 + // device-keyed caches) in lockstep with the setting — on boot, and
309 + // whenever the cache settings are saved. The drop-in can't read WP
310 + // options, so it reads the sidecar marker Cache maintains here.
311 + \XSpeed\Cache::reconcile_mobile_separate();
312 + // Both write paths matter. On a fresh install `xspeed_module_cache`
313 + // does not exist yet, so core's update_option() delegates to
314 + // add_option() and fires `add_option_…` INSTEAD of
315 + // `update_option_…`. Hooking only the latter meant the very first
316 + // save of Cache Expiry never re-baked the drop-in: the panel and the
317 + // DB read the new value while the drop-in kept enforcing the old
318 + // one, and re-saving the same value could not recover it because
319 + // update_option() short-circuits on an unchanged value (#251).
320 + $xspeed_resync_cache_artifacts = static function () {
321 + \XSpeed\Cache::reconcile_mobile_separate();
322 + // Re-bake the cookie / user-agent exclusion rules into the
323 + // drop-in. It runs before WordPress loads and so carries a
324 + // COPY of those rules, substituted at install time — and
325 + // auto_heal() deliberately only reinstalls when the file is
326 + // missing, foreign, or an older version, none of which a
327 + // settings change makes true. Without this, adding an
328 + // excluded cookie left the drop-in serving the shared
329 + // anonymous page to exactly the visitors it excluded, until
330 + // the next plugin upgrade happened to reinstall it.
331 + //
332 + // ONLY when page caching is actually on, for the same reason
333 + // refresh_rewrite_if_installed() below refuses to write a
334 + // block that isn't there: re-baking is maintenance of an
335 + // artifact the user opted into, never a way to acquire one.
336 + // Re-baking unconditionally reached past our own module — a
337 + // site that had declined our page cache got the drop-in
338 + // installed anyway on the next Cache Expiry save, and the
339 + // following toggle(false) then removed it. auto_heal() has
340 + // always gated on this flag; this path simply never did.
341 + // (#251)
342 + //
343 + // Through toggle() rather than install_dropin() so the re-bake
344 + // gets the same ownership check, lock and rollback as every
345 + // other page-cache write. A drop-in that turned out not to be
346 + // ours between the save and now is refused here too.
347 + $xspeed_options = get_option( 'xspeed_options', array() );
348 + if ( ! empty( $xspeed_options['cache_enabled'] ) ) {
349 + \XSpeed\Cache::toggle( true );
350 + }
351 + // Same staleness applies to the .htaccess block, which is
352 + // written to disk from the same generator. Refresh it only
353 + // when a block is already installed — writing one here would
354 + // enable the static path on a site that never opted in.
355 + \XSpeed\Cache::refresh_rewrite_if_installed();
356 + };
357 + add_action( 'update_option_xspeed_module_cache', $xspeed_resync_cache_artifacts );
358 + add_action( 'add_option_xspeed_module_cache', $xspeed_resync_cache_artifacts );
359 +
360 + // Time-driven collection of expired entries and superseded minified
361 + // assets. Scheduled here as well as in activate() because a site that
362 + // upgrades into this version never runs the activation hook again.
363 + add_action( \XSpeed\Cache_GC::CRON_HOOK, array( \XSpeed\Cache_GC::class, 'run' ) );
364 + \XSpeed\Cache_GC::ensure_scheduled();
94 365 }
95 366
96 367 public function activate(): void {
97 368 $this->seed_from_legacy_if_needed();
369 + \XSpeed\Cache_GC::ensure_scheduled();
98 370 }
99 371
372 + public function deactivate(): void {
373 + \XSpeed\Cache_GC::unschedule();
374 + }
375 +
100 376 private function seed_from_legacy_if_needed(): void {
101 377 if ( null !== get_option( 'xspeed_module_cache', null ) ) {
102 378 return;
103 379 }
@@ -125,24 +401,491 @@
125 401
126 402 public function cli_commands(): array {
127 403 return array(
128 404 array(
405 + 'name' => 'xspeed optimize',
406 + 'callback' => array( $this, 'cli_optimize' ),
407 + 'shortdesc' => 'Measure, apply the recommended settings one at a time, verify the page still works after each, and report what changed. Use --dry-run to see the plan without touching anything.',
408 + 'synopsis' => array(
409 + array(
410 + 'type' => 'assoc',
411 + 'name' => 'aggressiveness',
412 + 'description' => 'safe (removals + server-side only), standard (default), or aggressive (includes settings known to break some themes).',
413 + 'optional' => true,
414 + 'options' => array( 'safe', 'standard', 'aggressive' ),
415 + ),
416 + array(
417 + 'type' => 'flag',
418 + 'name' => 'dry-run',
419 + 'description' => 'Show the plan and stop. Changes nothing.',
420 + 'optional' => true,
421 + ),
422 + array(
423 + 'type' => 'assoc',
424 + 'name' => 'budget',
425 + 'description' => 'Seconds to spend before stopping between steps. Default 120.',
426 + 'optional' => true,
427 + ),
428 + array(
429 + 'type' => 'assoc',
430 + 'name' => 'measure-score',
431 + '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.',
432 + 'optional' => true,
433 + 'options' => array( 'auto', 'never', 'always' ),
434 + ),
435 + ),
436 + ),
437 + array(
438 + 'name' => 'xspeed purge',
439 + 'callback' => array( $this, 'cli_purge' ),
440 + '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.',
441 + '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.',
442 + 'synopsis' => array(
443 + array(
444 + 'type' => 'assoc',
445 + 'name' => 'type',
446 + 'description' => 'What to clear: all (default), page, object, cloudflare, cdn — or a group name (edge). Comma-separate to clear several.',
447 + 'optional' => true,
448 + ),
449 + array(
450 + 'type' => 'assoc',
451 + 'name' => 'cause',
452 + 'description' => 'Label recorded in the purge log, so `wp xspeed cache purge-log` can tell this run apart from a click. Default "CLI".',
453 + 'optional' => true,
454 + ),
455 + array(
456 + 'type' => 'assoc',
457 + 'name' => 'format',
458 + 'description' => 'table (default, one line per store) or json (the full report, for scripts).',
459 + 'optional' => true,
460 + 'options' => array( 'table', 'json' ),
461 + ),
462 + ),
463 + ),
464 + array(
129 465 'name' => 'xspeed cache',
130 466 'callback' => array( $this, 'cli_handler' ),
131 - 'shortdesc' => 'Inspect Cache module settings (purge / toggle use the dedicated commands).',
467 + '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`.',
132 468 'synopsis' => array(
133 469 array(
134 470 'type' => 'positional',
135 471 'name' => 'action',
136 - 'options' => array( 'status' ),
472 + 'options' => array( 'status', 'inventory', 'size', 'purge-log', 'purge-url', 'recheck-rewrite', 'nginx-config', 'edge' ),
137 473 'optional' => true,
138 474 ),
475 + array(
476 + 'type' => 'positional',
477 + 'name' => 'url',
478 + 'optional' => true,
479 + ),
480 + array(
481 + 'type' => 'assoc',
482 + 'name' => 'limit',
483 + 'description' => 'Rows to print for inventory / purge-log. Default 20.',
484 + 'optional' => true,
485 + ),
486 + array(
487 + 'type' => 'assoc',
488 + 'name' => 'cause',
489 + 'description' => 'Label recorded in the purge log for purge-url. Default "CLI".',
490 + 'optional' => true,
491 + ),
492 + array(
493 + 'type' => 'assoc',
494 + 'name' => 'server',
495 + 'description' => 'Server type to assume for nginx-config, skipping detection. Detection needs SERVER_SOFTWARE, which the command line does not have; an undetectable host is assumed to be nginx anyway, so this is for stating it outright — or for the case detection is positively wrong, such as nginx in front of Apache.',
496 + 'options' => array( 'nginx', 'apache', 'litespeed' ),
497 + 'optional' => true,
498 + ),
139 499 ),
140 500 ),
141 501 );
142 502 }
143 503
504 + /**
505 + * `wp xspeed optimize` — run the autopilot.
506 + *
507 + * Prints what it DID, not what it hoped to do: applied steps, reverted
508 + * steps with the reason they were undone, and the problems it could not
509 + * touch. A run that changes nothing prints that plainly rather than a
510 + * success banner.
511 + *
512 + * @param array<int,string> $args Positional args (unused).
513 + * @param array<string,string> $assoc Flags.
514 + */
515 + public function cli_optimize( array $args, array $assoc ): void {
516 + $result = \XSpeed\Optimize_Runner::run(
517 + array(
518 + 'aggressiveness' => (string) ( $assoc['aggressiveness'] ?? 'standard' ),
519 + 'dry_run' => isset( $assoc['dry-run'] ),
520 + 'budget_seconds' => isset( $assoc['budget'] ) ? (int) $assoc['budget'] : 120,
521 + 'measure_score' => (string) ( $assoc['measure-score'] ?? 'auto' ),
522 + )
523 + );
524 +
525 + if ( is_wp_error( $result ) ) {
526 + \WP_CLI::error( $result->get_error_message() );
527 + return;
528 + }
529 +
530 + if ( ! empty( $result['dry_run'] ) ) {
531 + // The summary carries the score AND its age. Printing the plan
532 + // without it left the one number a reader wants off the only
533 + // command they run before deciding to apply anything.
534 + if ( isset( $result['message'] ) ) {
535 + \WP_CLI::log( (string) $result['message'] );
536 + }
537 + \WP_CLI::log( 'Plan (' . count( $result['plan'] ) . ' steps, nothing applied):' );
538 + foreach ( $result['plan'] as $step ) {
539 + \WP_CLI::log( ' - ' . $step['change'] . ' [' . $step['tier'] . ']' );
540 + }
541 + foreach ( $result['skipped'] as $row ) {
542 + \WP_CLI::log( ' skipped: ' . $row['id'] . ' — ' . $row['why'] );
543 + }
544 + return;
545 + }
546 +
547 + if ( isset( $result['message'] ) ) {
548 + \WP_CLI::success( (string) $result['message'] );
549 + }
550 +
551 + foreach ( $result['applied'] as $row ) {
552 + \WP_CLI::log( ' ✓ ' . $row['change'] );
553 + }
554 + foreach ( $result['reverted'] as $row ) {
555 + \WP_CLI::warning( 'Undone: ' . $row['id'] . ' — ' . $row['why'] );
556 + }
557 + foreach ( $result['unfixable'] as $row ) {
558 + \WP_CLI::log( ' ! ' . $row['issue'] . ( '' !== $row['fix'] ? ' — ' . $row['fix'] : '' ) );
559 + }
560 +
561 + if ( ! empty( $result['applied'] ) ) {
562 + // "applied and verified" was more than the checks earn. They read
563 + // HTML in PHP and cannot run JavaScript, so this line was telling
564 + // someone the site was fine when the only honest claim is that
565 + // nothing in the markup looked broken.
566 + \WP_CLI::success( count( $result['applied'] ) . ' change(s) applied; HTML checks passed.' );
567 +
568 + if ( ! empty( $result['verify_urls'] ) ) {
569 + \WP_CLI::log( '' );
570 + \WP_CLI::log( 'Now open these and check they render, with no console errors:' );
571 + foreach ( $result['verify_urls'] as $u ) {
572 + \WP_CLI::log( ' ' . $u );
573 + }
574 + }
575 + }
576 + }
577 +
578 + /**
579 + * `wp xspeed purge` — clear every cache xSpeed owns, in one call.
580 + *
581 + * Reports per store rather than printing a success banner, because the
582 + * banner was the bug: a site whose Cloudflare token had lost its purge
583 + * permission saw "cache cleared" and kept serving stale HTML from the
584 + * edge. What is skipped is as much of the answer as what is cleared, so
585 + * every skip prints its reason.
586 + *
587 + * Exit code follows the same distinction. A store that is not configured
588 + * has nothing to clear and does not fail the run — otherwise every CI
589 + * pipeline on a site without Redis goes red for a purge that did exactly
590 + * what it should. A store that IS configured and refused is a failure.
591 + *
592 + * There is deliberately no `--url`: WP-CLI reserves that flag for
593 + * multisite site selection and consumes it before a handler ever sees it.
594 + * Clearing one page is `wp xspeed cache purge-url <url>`.
595 + *
596 + * @param array<int,string> $args Positional args (unused).
597 + * @param array<string,string> $assoc Flags.
598 + */
599 + public function cli_purge( array $args, array $assoc ): void {
600 + unset( $args );
601 +
602 + $requested = array_values(
603 + array_filter(
604 + array_map( 'trim', explode( ',', (string) ( $assoc['type'] ?? 'all' ) ) )
605 + )
606 + );
607 + if ( ! $requested ) {
608 + $requested = array( 'all' );
609 + }
610 +
611 + $accepted = \XSpeed\Purge_Runner::accepted_types();
612 + $unknown = array_diff( $requested, $accepted );
613 + if ( $unknown ) {
614 + // Refuse before purging anything: a typo in --type must not
615 + // quietly clear a DIFFERENT store than the one named.
616 + \WP_CLI::error(
617 + sprintf(
618 + 'Unknown purge type: %s. Expected one of: %s',
619 + implode( ', ', $unknown ),
620 + implode( ', ', $accepted )
621 + )
622 + );
623 + return;
624 + }
625 +
626 + $cause = isset( $assoc['cause'] ) && '' !== trim( (string) $assoc['cause'] ) ? trim( (string) $assoc['cause'] ) : 'CLI';
627 + $report = \XSpeed\Purge_Runner::run( $requested, $cause );
628 +
629 + if ( 'json' === ( $assoc['format'] ?? 'table' ) ) {
630 + // The report goes to STDOUT alone so `... --format=json | jq` works;
631 + // the failure message goes to STDERR via ::error, which is also
632 + // what produces the non-zero exit.
633 + \WP_CLI::line( (string) wp_json_encode( $report ) );
634 + if ( ! $report['ok'] ) {
635 + \WP_CLI::error( 'One or more cache stores failed to purge; see the report above.' );
636 + }
637 + return;
638 + }
639 +
640 + $cleared = 0;
641 + $skipped = 0;
642 + $failed = 0;
643 + foreach ( $report['types'] as $row ) {
644 + switch ( $row['status'] ) {
645 + case \XSpeed\Purge_Runner::CLEARED:
646 + ++$cleared;
647 + \WP_CLI::log( sprintf( ' cleared %s%s', $row['label'], self::purge_amount( $row ) ) );
648 + break;
649 + case \XSpeed\Purge_Runner::FAILED:
650 + ++$failed;
651 + \WP_CLI::log( sprintf( ' FAILED %s — %s', $row['label'], $row['reason'] ) );
652 + break;
653 + default:
654 + ++$skipped;
655 + \WP_CLI::log( sprintf( ' skipped %s — %s', $row['label'], $row['reason'] ) );
656 + }
657 + }
658 +
659 + if ( $failed ) {
660 + \WP_CLI::error(
661 + sprintf(
662 + '%d of %d cache store(s) failed to purge; %d cleared, %d skipped.',
663 + $failed,
664 + count( $report['types'] ),
665 + $cleared,
666 + $skipped
667 + )
668 + );
669 + return;
670 + }
671 +
672 + if ( ! $cleared ) {
673 + // Not a success banner: nothing was purged, and saying so is the
674 + // honest answer for a --type nobody has configured.
675 + \WP_CLI::log( sprintf( 'Nothing to purge — %d store(s) skipped.', $skipped ) );
676 + return;
677 + }
678 +
679 + \WP_CLI::success( sprintf( 'Purged %d cache store(s); %d skipped.', $cleared, $skipped ) );
680 + }
681 +
682 + /**
683 + * The " — 42 entries (1.3 MB)" tail on a cleared line.
684 + *
685 + * Entries and bytes are both optional: a Redis FLUSHALL reports neither,
686 + * and printing "0 entries" for it would read as an empty cache rather
687 + * than an uncountable one.
688 + *
689 + * @param array{entries:int|null,bytes:int|null} $row Report row.
690 + */
691 + private static function purge_amount( array $row ): string {
692 + $parts = array();
693 + if ( null !== $row['entries'] ) {
694 + $parts[] = sprintf( '%d entr%s', $row['entries'], 1 === (int) $row['entries'] ? 'y' : 'ies' );
695 + }
696 + if ( null !== $row['bytes'] && $row['bytes'] > 0 ) {
697 + $parts[] = size_format( $row['bytes'], 1 );
698 + }
699 +
700 + return $parts ? ' — ' . implode( ', ', $parts ) : '';
701 + }
702 +
144 703 public function cli_handler( array $args, array $assoc ): void {
704 + $action = isset( $args[0] ) ? (string) $args[0] : 'status';
705 + $limit = isset( $assoc['limit'] ) ? max( 1, (int) $assoc['limit'] ) : 20;
706 +
707 + /*
708 + * Print the unified nginx server-block so an installer, provisioning
709 + * script, or another plugin can fetch it non-interactively and write
710 + * it into a vhost. Previously this was only reachable via
711 + * `wp eval 'echo \XSpeed\Cache::full_nginx_server_block();'`, which
712 + * is not a supported surface (and is unavailable over MCP, where
713 + * run_command dispatches these same callbacks).
714 + *
715 + * Output discipline matters here: the config goes to STDOUT with
716 + * nothing else, so `wp xspeed cache nginx-config > site.conf` yields a
717 + * pasteable file. Every diagnostic goes to STDERR via WP_CLI::warning
718 + * / ::error, and a non-nginx host or an empty block exits non-zero so
719 + * a script can branch on it rather than writing an empty file.
720 + *
721 + * --server exists because detection cannot work here. WP-CLI runs
722 + * without SERVER_SOFTWARE, so Server::type() falls back to the value
723 + * a previous web request cached — and on a site provisioned entirely
724 + * over WP-CLI there is no such value, leaving `unknown` on a genuine
725 + * nginx host. Rather than guess (a loopback request is the one thing
726 + * least likely to work mid-provisioning), let the caller state it:
727 + * the script writing to /etc/nginx/ already knows the answer.
728 + * Without the flag nothing changes, so a script sweeping a mixed
729 + * fleet still gets its non-zero exit on Apache.
730 + *
731 + * It pins Server::type() rather than being passed down, because the
732 + * decision is re-made at every level: full_nginx_server_block(),
733 + * Cache::nginx_snippet(), and each module's own nginx_directives()
734 + * all ask independently. Threading an argument through would leave
735 + * the deeper gates still detecting, and the command would emit a
736 + * config missing its cache rewrite — worse than refusing outright.
737 + */
738 + if ( 'nginx-config' === $action ) {
739 + /*
740 + * Scoped to this one generation pass, not the request. Under
741 + * real WP-CLI the process ends here either way, but the same
742 + * callback runs over MCP, where several commands share one PHP
743 + * request — a pin left in place made the NEXT command report
744 + * this host as nginx too.
745 + */
746 + $pin = null;
747 + $assume = null;
748 +
749 + if ( isset( $assoc['server'] ) ) {
750 + $assume = strtolower( trim( (string) $assoc['server'] ) );
751 + } elseif ( \XSpeed\Server::UNKNOWN === \XSpeed\Server::type() ) {
752 + /*
753 + * Nothing to detect from, and the action names the server:
754 + * `nginx-config` is the request, so absence of evidence
755 + * defers to it. Positive evidence to the contrary still
756 + * wins — an Apache or LiteSpeed host is told it needs no
757 + * nginx block at all, which is the answer that helps.
758 + */
759 + $assume = \XSpeed\Server::NGINX;
760 +
761 + /*
762 + * Only where warnings have somewhere else to go. Real WP-CLI
763 + * sends them to STDERR, leaving the config clean on STDOUT.
764 + * The MCP shim has ONE buffer for both, so warning there
765 + * would prepend "Warning: …" to the config itself and hand
766 + * the caller a file nginx refuses. The constant is the
767 + * discriminator: real WP-CLI defines it, the shim defines
768 + * only the class.
769 + */
770 + if ( defined( 'WP_CLI' ) && \WP_CLI ) {
771 + \WP_CLI::warning(
772 + 'Could not detect the web server — no recognisable SERVER_SOFTWARE, and no web request has cached one yet. Assuming nginx, which is what this command generates. Pass --server= to state it explicitly, or load any page once to settle detection.'
773 + );
774 + }
775 + }
776 +
777 + if ( null !== $assume ) {
778 + $pinned = $assume;
779 + $pin = static function () use ( $pinned ) {
780 + return $pinned;
781 + };
782 + add_filter( 'xspeed_server_type', $pin );
783 + }
784 +
785 + $block = \XSpeed\Cache::full_nginx_server_block();
786 + $server = \XSpeed\Server::type();
787 +
788 + if ( null !== $pin ) {
789 + remove_filter( 'xspeed_server_type', $pin );
790 + }
791 +
792 + if ( ! is_string( $block ) || '' === trim( $block ) ) {
793 + /*
794 + * $server cannot be UNKNOWN here: an undetectable host was
795 + * already assumed to be nginx above, so anything left is a
796 + * server we positively identified — and telling an Apache or
797 + * LiteSpeed operator that .htaccess already covers them is
798 + * more useful than handing them a block to paste nowhere.
799 + */
800 + if ( \XSpeed\Server::NGINX !== $server ) {
801 + \WP_CLI::error(
802 + sprintf(
803 + 'No nginx server-block to print — this site is running on %s. On Apache and LiteSpeed xSpeed writes its rules to .htaccess automatically.',
804 + $server
805 + )
806 + );
807 + return;
808 + }
809 + \WP_CLI::error( 'No nginx directives to print — page caching and every module that contributes directives are currently disabled.' );
810 + return;
811 + }
812 +
813 + // STDOUT only: no WP_CLI::log() prefixing, so redirection gives a
814 + // clean file. WP_CLI::line() writes the raw string.
815 + \WP_CLI::line( rtrim( $block, "\n" ) );
816 + return;
817 + }
818 +
819 + /*
820 + * Force a fresh static-rewrite probe. The result is cached for five
821 + * minutes and nothing invalidated it, so after fixing an nginx config
822 + * there was no way to re-check — the "configure your server" banner
823 + * just stayed up. (FBS-84012)
824 + */
825 + if ( 'recheck-rewrite' === $action ) {
826 + // Qualify the raw probe against known config refusals before
827 + // reporting. The probe fetches its OWN file from the static tree,
828 + // which succeeds even when no real page is served that way — so
829 + // an unqualified `active` reported "the web server is serving
830 + // cache hits directly" on sites whose every page returned
831 + // HIT (php). See Cache::qualify_rewrite_probe().
832 + $probe = \XSpeed\Cache::qualify_rewrite_probe( \XSpeed\Cache::recheck_static_rewrite() );
833 + $blocked = '' !== (string) $probe['block_reason'];
834 +
835 + if ( $probe['active'] ) {
836 + \WP_CLI::success( 'Static rewrite is active — the web server is serving cache hits directly.' );
837 + return;
838 + }
839 + if ( $blocked ) {
840 + \WP_CLI::warning( sprintf( 'Static rewrite is not active: %s', (string) $probe['reason'] ) );
841 + return;
842 + }
843 + if ( $probe['inconclusive'] ) {
844 + \WP_CLI::warning( sprintf( 'Could not verify the static rewrite: %s', (string) $probe['reason'] ) );
845 + \WP_CLI::log( 'This is a probe failure, not proof that your server config is wrong.' );
846 + return;
847 + }
848 + \WP_CLI::warning( sprintf( 'Static rewrite is not active: %s', (string) ( $probe['reason'] ?: 'unknown' ) ) );
849 + return;
850 + }
851 +
852 + if ( 'purge-url' === $action ) {
853 + $url = isset( $args[1] ) ? trim( (string) $args[1] ) : '';
854 + if ( '' === $url ) {
855 + \WP_CLI::error( 'Usage: wp xspeed cache purge-url <url-or-path>' );
856 + return;
857 + }
858 + $cause = isset( $assoc['cause'] ) && '' !== trim( (string) $assoc['cause'] ) ? trim( (string) $assoc['cause'] ) : 'CLI';
859 + $removed = \XSpeed\Cache::purge_url( $url, $cause );
860 + if ( $removed > 0 ) {
861 + \WP_CLI::success( sprintf( 'Purged %d cache file(s) for %s', $removed, $url ) );
862 + } else {
863 + \WP_CLI::log( sprintf( 'No cache entries found for %s (already cold, or the URL never cached).', $url ) );
864 + }
865 + return;
866 + }
867 +
868 + if ( 'inventory' === $action ) {
869 + $this->cli_inventory( $limit );
870 + return;
871 + }
872 +
873 + if ( 'size' === $action ) {
874 + $this->cli_size();
875 + return;
876 + }
877 +
878 + if ( 'purge-log' === $action ) {
879 + $this->cli_purge_log( $limit );
880 + return;
881 + }
882 +
883 + if ( 'edge' === $action ) {
884 + $this->cli_edge();
885 + return;
886 + }
887 +
145 888 $opts = Settings_Manager::get( self::SLUG );
146 889 \WP_CLI::log( 'cache_expiry ' . $opts['cache_expiry'] . 'h' );
147 890 \WP_CLI::log( 'excluded_urls ' . count( $opts['excluded_urls'] ) . ' entries' );
148 891 foreach ( $opts['excluded_urls'] as $u ) {
@@ -147,11 +890,161 @@
147 890 \WP_CLI::log( 'excluded_urls ' . count( $opts['excluded_urls'] ) . ' entries' );
148 891 foreach ( $opts['excluded_urls'] as $u ) {
149 892 \WP_CLI::log( ' - ' . $u );
150 893 }
894 + $edge = \XSpeed\Edge_Provider::detect();
895 + \WP_CLI::log( 'edge ' . ( '' !== $edge['provider'] ? $edge['provider'] : $edge['confidence'] ) . ' (' . $edge['source'] . ')' );
151 896 }
152 897
153 898 /**
899 + * `wp xspeed cache edge` — what we think is in front, and what we say to it.
900 + *
901 + * Worth printing even when nothing is held back. "You are behind
902 + * Cloudflare, and a Cache Rule set to ignore origin headers overrides
903 + * anything xSpeed sends" is the answer to a support question that
904 + * otherwise costs someone a week, and it is true whether or not a hold
905 + * ever fires.
906 + */
907 + private function cli_edge(): void {
908 + $answer = \XSpeed\Edge_Provider::detect();
909 +
910 + \WP_CLI::log( 'provider ' . ( '' !== $answer['provider'] ? $answer['provider'] : '(none named)' ) );
911 + \WP_CLI::log( 'confidence ' . $answer['confidence'] );
912 + \WP_CLI::log( 'source ' . $answer['source'] );
913 +
914 + // A pin outranks detection by design, so nothing re-checks it on the
915 + // site's behalf. Saying the two disagree is the whole mechanism by
916 + // which a site that changed CDN ever finds out.
917 + $sniffed = \XSpeed\Edge_Provider::sniffed();
918 + if ( in_array( $answer['source'], array( 'setting', 'constant', 'filter' ), true )
919 + && '' !== $sniffed['provider']
920 + && $sniffed['provider'] !== $answer['provider'] ) {
921 + \WP_CLI::warning(
922 + sprintf(
923 + '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.',
924 + $sniffed['provider'],
925 + '' !== $answer['provider'] ? $answer['provider'] : 'off'
926 + )
927 + );
928 + }
929 +
930 + if ( \XSpeed\Edge_Provider::is_off( $answer ) ) {
931 + \WP_CLI::log( '' );
932 + \WP_CLI::log( 'Nothing is sent: this is switched off.' );
933 + return;
934 + }
935 +
936 + // Resolved through edge_headers_for() rather than straight off the
937 + // provider, so this prints what the serve path would ACTUALLY send —
938 + // including `X-XSpeed-Edge-Hold`, and including the evidence gate.
939 + // Listing the provider's raw set ignored that gate and told operators
940 + // a first render would be held on a site where it would not be.
941 + //
942 + // `bake`, not `request`. Two reasons, and the second one matters:
943 + // this command answers for the site rather than for one response, and
944 + // `request` fires `xspeed_edge_optimization_pending`, whose Pro
945 + // listener resolves the CSS plan — which by its own description is
946 + // what queues a build. A read-only command must not burn a build
947 + // slot, quarantine an entry or purge a page just by being run, and
948 + // under WP-CLI it would do all three against the home page.
949 + $bypass = \XSpeed\Cache::edge_headers_for( 'BYPASS', 'bake', 'logged-in' );
950 + $miss = \XSpeed\Cache::edge_headers_for( 'MISS', 'bake' );
951 +
952 + \WP_CLI::log( '' );
953 + \WP_CLI::log( 'On a page xSpeed refuses to cache (a cart, a logged-in view):' );
954 + foreach ( $bypass as $name => $value ) {
955 + \WP_CLI::log( sprintf( ' %s: %s', $name, $value ) );
956 + }
957 +
958 + \WP_CLI::log( '' );
959 + if ( array() === $miss ) {
960 + \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.' );
961 + } else {
962 + \WP_CLI::log( 'On a first render:' );
963 + foreach ( $miss as $name => $value ) {
964 + \WP_CLI::log( sprintf( ' %s: %s', $name, $value ) );
965 + }
966 + }
967 +
968 + \WP_CLI::log( '' );
969 + \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.' );
970 +
971 + if ( 'cloudflare' === $answer['provider'] ) {
972 + \WP_CLI::log( '' );
973 + \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.' );
974 + }
975 + }
976 +
977 + /** `wp xspeed cache inventory [--limit=N]` — which pages are cached, and how old. */
978 + private function cli_inventory( int $limit ): void {
979 + $data = \XSpeed\Cache_Inventory::entries( $limit );
980 +
981 + if ( empty( $data['entries'] ) ) {
982 + \WP_CLI::log( 'Cache is empty — no cached pages on disk.' );
983 + return;
984 + }
985 +
986 + \WP_CLI::log( sprintf( '%d cached page(s); showing %d.', $data['total'], count( $data['entries'] ) ) );
987 + if ( ! empty( $data['capped'] ) ) {
988 + \WP_CLI::warning( sprintf( 'Scan stopped at %d files — the list is a recent sample, not the whole cache.', \XSpeed\Cache_Inventory::SCAN_CAP ) );
989 + }
990 + foreach ( $data['entries'] as $entry ) {
991 + \WP_CLI::log(
992 + sprintf(
993 + ' %-58s %8s %s [%s]',
994 + null === $entry['url'] ? '(url unknown: ' . $entry['key'] . ')' : $entry['url'],
995 + size_format( (int) $entry['bytes'] ),
996 + $this->relative_age( (int) $entry['age'] ),
997 + implode( '+', (array) $entry['stored_in'] )
998 + )
999 + );
1000 + }
1001 + }
1002 +
1003 + /** `wp xspeed cache size` — where the cache's disk usage goes. */
1004 + private function cli_size(): void {
1005 + $data = \XSpeed\Cache_Inventory::size_breakdown();
1006 +
1007 + \WP_CLI::log( sprintf( 'Total %s across %d file(s).', size_format( (int) $data['total_bytes'] ), (int) $data['total_files'] ) );
1008 + foreach ( $data['buckets'] as $bucket ) {
1009 + if ( 0 === (int) $bucket['files'] ) {
1010 + continue;
1011 + }
1012 + \WP_CLI::log( sprintf( ' %-32s %10s %d file(s)', $bucket['label'], size_format( (int) $bucket['bytes'] ), (int) $bucket['files'] ) );
1013 + }
1014 + if ( (int) $data['compressed_bytes'] > 0 ) {
1015 + \WP_CLI::log( sprintf( 'Precompressed on disk: %s (pages without a precompressed copy are compressed by the web server at request time).', size_format( (int) $data['compressed_bytes'] ) ) );
1016 + }
1017 + }
1018 +
1019 + /** `wp xspeed cache purge-log [--limit=N]` — what cleared the cache, when, and why. */
1020 + private function cli_purge_log( int $limit ): void {
1021 + $data = \XSpeed\Cache_Inventory::purge_log( $limit );
1022 +
1023 + if ( empty( $data['events'] ) ) {
1024 + \WP_CLI::log( 'No purge events recorded yet.' );
1025 + return;
1026 + }
1027 + foreach ( $data['events'] as $event ) {
1028 + \WP_CLI::log( sprintf( ' %s %s', $this->relative_age( max( 0, time() - (int) $event['ts'] ) ), $event['message'] ) );
1029 + }
1030 + }
1031 +
1032 + /** Compact "4h ago" for CLI columns. */
1033 + private function relative_age( int $seconds ): string {
1034 + if ( $seconds < 60 ) {
1035 + return $seconds . 's ago';
1036 + }
1037 + if ( $seconds < 3600 ) {
1038 + return (int) floor( $seconds / 60 ) . 'm ago';
1039 + }
1040 + if ( $seconds < 86400 ) {
1041 + return (int) floor( $seconds / 3600 ) . 'h ago';
1042 + }
1043 + return (int) floor( $seconds / 86400 ) . 'd ago';
1044 + }
1045 +
1046 + /**
154 1047 * Static-rewrite directives for the unified nginx server-block
155 1048 * snippet. Returns null when cache is disabled — there's no rewrite
156 1049 * to install in that state. Delegates to \XSpeed\Cache::nginx_snippet()
157 1050 * which already produces nginx-detection-gated output.
@@ -161,6 +1054,32 @@
161 1054 if ( empty( $opts['cache_enabled'] ) ) {
162 1055 return null;
163 1056 }
164 1057 return \XSpeed\Cache::nginx_snippet();
1058 + }
1059 +
1060 + /**
1061 + * Page caching's master switch is `cache_enabled` in the GLOBAL
1062 + * `xspeed_options`, not a per-module `enabled` key -- Cache::toggle owns
1063 + * it because flipping it rewrites .htaccess and wp-config.php. The base
1064 + * implementation looks only at this module's own settings bag, so it
1065 + * found nothing and reported null: the plugin's headline feature was
1066 + * missing from its own "N on" count. (#363)
1067 + */
1068 + public function is_active(): ?bool {
1069 + $opts = get_option( 'xspeed_options', array() );
1070 + return ! empty( $opts['cache_enabled'] );
1071 + }
1072 +
1073 + /**
1074 + * No reason shown: page caching has a single master switch, so the pill
1075 + * already says everything an (i) would. The switch lives on the Overview
1076 + * rather than on this page, but that is a "where is the control" question
1077 + * the panel itself should answer, not a reason to explain the verdict.
1078 + *
1079 + * The (i) is reserved for modules whose on/off is genuinely non-obvious
1080 + * -- counted from several flags, or from state outside the settings.
1081 + */
1082 + public function active_reason(): ?string {
1083 + return null;
165 1084 }
166 1085 }