PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.1.3
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.1.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
xspeed / includes / class-health.php

class-health.php in xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN 1.1.3, at includes/class-health.php

468 lines 19.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Health — shared diagnostic checks consumed by both Onboarding's
4 * environment surface and the Health module's dashboard panel.
5 *
6 * Each check returns:
7 * [
8 * 'id' => 'wp_version',
9 * 'tone' => 'ok' | 'warn' | 'fail' | 'info',
10 * 'label' => 'WordPress 6.6',
11 * 'detail' => 'Meets the 6.0+ minimum.',
12 * ]
13 *
14 * Pure reads — never writes to disk, never makes outbound HTTP calls.
15 * Safe to call from any request including the loading dashboard.
16 *
17 * @package XSpeed
18 */
19
20 declare(strict_types=1);
21
22 namespace XSpeed;
23
24 defined( 'ABSPATH' ) || exit;
25
26 final class Health {
27
28 public const OK = 'ok';
29 public const WARN = 'warn';
30 public const FAIL = 'fail';
31 public const INFO = 'info';
32
33 private const SERVER_LABELS = array(
34 'apache' => 'Apache',
35 'litespeed' => 'LiteSpeed',
36 'nginx' => 'nginx',
37 'iis' => 'IIS',
38 'unknown' => 'Unknown',
39 );
40
41 /**
42 * Full check list used by the Health module's dashboard panel.
43 *
44 * @return array<int,array{id:string,tone:string,label:string,detail:string}>
45 */
46 public static function checks(): array {
47 global $wp_version;
48
49 $server_type = Server::type();
50 $gzip_mode = Server::gzip_mode();
51 $conflicts = Server::conflicts();
52 $cache_dir = defined( 'XSPEED_CACHE_DIR' ) ? XSPEED_CACHE_DIR : ( WP_CONTENT_DIR . '/cache/xspeed' );
53
54 $out = array();
55
56 // WordPress version
57 $wp_ok = version_compare( (string) $wp_version, '6.0', '>=' );
58 $out[] = array(
59 'id' => 'wp_version',
60 'tone' => $wp_ok ? self::OK : self::FAIL,
61 'label' => sprintf( 'WordPress %s', (string) $wp_version ),
62 'detail' => $wp_ok ? 'Meets the 6.0+ minimum.' : 'Upgrade to WordPress 6.0 or higher.',
63 );
64
65 // PHP version
66 $php_ok = version_compare( PHP_VERSION, '7.4', '>=' );
67 $php_modern = version_compare( PHP_VERSION, '8.1', '>=' );
68 $out[] = array(
69 'id' => 'php_version',
70 'tone' => $php_modern ? self::OK : ( $php_ok ? self::WARN : self::FAIL ),
71 'label' => sprintf( 'PHP %s', PHP_VERSION ),
72 'detail' => $php_modern
73 ? 'Modern PHP — full speed.'
74 : ( $php_ok
75 ? 'Works, but 8.1+ is recommended for best performance.'
76 : 'Upgrade to PHP 7.4 or higher.' ),
77 );
78
79 // Server
80 $out[] = array(
81 'id' => 'server',
82 'tone' => self::INFO,
83 'label' => sprintf( 'Server: %s', self::SERVER_LABELS[ $server_type ] ?? 'Unknown' ),
84 'detail' => 'auto' === $gzip_mode
85 ? 'GZIP can be auto-configured via .htaccess.'
86 : 'GZIP requires a manual server-config snippet (shown in the GZIP module).',
87 );
88
89 // Cache directory writable
90 $dir_writable = wp_mkdir_p( $cache_dir ) && wp_is_writable( $cache_dir );
91 $out[] = array(
92 'id' => 'cache_dir',
93 'tone' => $dir_writable ? self::OK : self::FAIL,
94 'label' => 'Cache directory writable',
95 'detail' => $dir_writable
96 ? $cache_dir
97 : sprintf( 'Cannot write to %s. Adjust file permissions before enabling cache.', $cache_dir ),
98 );
99
100 // Drop-in installed (only when cache is enabled — otherwise N/A)
101 $cache_enabled = (bool) Settings::get()['cache_enabled'];
102 if ( $cache_enabled ) {
103 $dropin_path = WP_CONTENT_DIR . '/advanced-cache.php';
104 $dropin_match = file_exists( $dropin_path ) && false !== strpos( (string) file_get_contents( $dropin_path ), 'xspeed' );
105 $out[] = array(
106 'id' => 'dropin',
107 'tone' => $dropin_match ? self::OK : self::FAIL,
108 'label' => 'advanced-cache.php drop-in',
109 'detail' => $dropin_match
110 ? 'Installed and owned by xSpeed.'
111 : 'Drop-in missing or owned by another plugin. Toggle Enable Cache off and on to reinstall.',
112 );
113 }
114
115 // WP_CACHE constant
116 $wp_cache_const = defined( 'WP_CACHE' ) && WP_CACHE;
117 if ( $cache_enabled ) {
118 $out[] = array(
119 'id' => 'wp_cache_constant',
120 'tone' => $wp_cache_const ? self::OK : self::WARN,
121 'label' => 'WP_CACHE constant',
122 'detail' => $wp_cache_const
123 ? 'Defined and truthy in wp-config.php.'
124 : 'Not set. Cache is configured but WordPress will not load the drop-in until WP_CACHE = true is added to wp-config.php.',
125 );
126 }
127
128 // Static-rewrite probe. Active end-to-end check: writes a probe
129 // file under the static-cache dir, fetches it over HTTP, and
130 // confirms the web server (nginx OR Apache/LiteSpeed) served
131 // the raw file. Result is throttled to a 5-minute transient
132 // inside Cache::probe_static_rewrite so we never hit the
133 // network per-paint.
134 if ( $cache_enabled ) {
135 $server_type = Server::type();
136 // The live loopback probe only matters where a server-level static
137 // rewrite is actually used (nginx snippet / Apache .htaccess).
138 // LiteSpeed serves hits via the drop-in (see below), so skip the
139 // probe there entirely — no needless self-request. Health is the
140 // right place to pay for the probe when we DO run it (the admin
141 // bootstrap reads cache-only so it never blocks); the 5-minute
142 // transient still throttles repeat runs. (FBS-82142)
143 $probe = ( Server::LITESPEED === $server_type )
144 ? array( 'active' => false )
145 : Cache::probe_static_rewrite( true );
146 $is_active = (bool) ( $probe['active'] ?? false );
147 // An inconclusive probe (blocked loopback, TLS failure, timeout, a
148 // CDN/WAF answering instead of the origin) proves nothing about the
149 // rewrite. Reporting it as "not yet routing to the cache" told users
150 // with a correct nginx config that their config was broken, and
151 // pointed them at a snippet they had already pasted. (FBS-84012)
152 $inconclusive = (bool) ( $probe['inconclusive'] ?? false );
153 $probe_reason = (string) ( $probe['reason'] ?? '' );
154
155 $block_reason = Cache::static_rewrite_block_reason();
156 $mobile_block = ( 'mobile_separate' === $block_reason )
157 ? ' Note: Separate Mobile Cache is on, which disables the device-blind static rewrite — if your site serves the same HTML to all devices, turn it off (Cache settings) for much faster cache hits.'
158 : '';
159
160 // A known refusal OUTRANKS the probe. probe_static_rewrite() writes
161 // its own file under the static-cache dir and fetches that — which
162 // succeeds whenever the server can serve a static file at all, even
163 // when static_rewrite_allowed() is false and no real page is being
164 // served that way. Checking $is_active first therefore reported
165 // "PHP bypassed" on a site whose pages were all returning
166 // HIT (php): the panel answered "why isn't static serving active?"
167 // with the opposite of the truth. When we already know why the
168 // rewrite is off, say that and ignore the probe. (FBS-83145)
169 $refused = ( '' !== $block_reason );
170 $is_active = $is_active && ! $refused;
171 // A refusal is a definite finding, so it also outranks
172 // "inconclusive" — otherwise a blocked rewrite whose probe merely
173 // failed to complete would be reported as INFO ("nothing to warn
174 // about") instead of the WARN the block deserves.
175 $inconclusive = $inconclusive && ! $refused;
176
177 if ( Server::NGINX === $server_type ) {
178 if ( $is_active ) {
179 $nginx_detail = 'nginx is serving cache hits directly — PHP bypassed (~5-15ms TTFB).';
180 } elseif ( 'mobile_separate' === $block_reason ) {
181 $nginx_detail = 'nginx detected, but the static rewrite is disabled because Separate Mobile Cache is on.' . $mobile_block;
182 } elseif ( $inconclusive ) {
183 $nginx_detail = sprintf(
184 'Could not verify the static rewrite — the check itself did not complete, so this is not evidence that your config is wrong. If you have already pasted the snippet, it may well be working. Reason: %s',
185 $probe_reason
186 );
187 } else {
188 $nginx_detail = 'nginx detected but not yet routing to the cache. Paste the snippet below into your site\'s server { } block, then reload nginx.';
189 }
190
191 $out[] = array(
192 'id' => 'static_rewrite_nginx',
193 // Inconclusive is INFO, not WARN — we have no finding to warn about.
194 'tone' => $is_active ? self::OK : ( $inconclusive ? self::INFO : self::WARN ),
195 'label' => 'Static-file rewrite (nginx server config)',
196 'detail' => $nginx_detail,
197 // Always ship the snippet — even when active, so the
198 // admin has it handy for re-pasting after a server
199 // rebuild without having to find it elsewhere. Mirror
200 // the SAME unified block the "Server config" panel
201 // renders (cache + gzip + browser-cache directives),
202 // not the cache-only snippet — otherwise Health and
203 // the Cache panel disagree on what to paste.
204 'snippet' => Cache::full_nginx_server_block(),
205 );
206 } elseif ( Server::LITESPEED === $server_type ) {
207 // LiteSpeed intentionally does NOT use the .htaccess static
208 // rewrite: OpenLiteSpeed's .htaccess engine ignores
209 // mod_headers (so we can't stamp X-XSpeed-Cache: HIT) and has
210 // no per-rule access_log (so a static hit can't be counted).
211 // We route LiteSpeed hits through the PHP drop-in instead, so
212 // every hit is both visible (X-XSpeed-Cache: HIT) and counted
213 // in the hit-ratio — see Cache::static_rewrite_allowed(). This
214 // is the healthy, expected state on LiteSpeed, not a fallback.
215 $out[] = array(
216 'id' => 'static_rewrite_litespeed',
217 'tone' => self::OK,
218 'label' => 'Cache serving (LiteSpeed)',
219 'detail' => 'Cache hits are served by xSpeed\'s drop-in and tagged X-XSpeed-Cache: HIT — so every hit is visible and counted in your hit-ratio. (LiteSpeed\'s .htaccess can\'t add that header or log static hits, so xSpeed serves them itself for accurate reporting.)',
220 );
221 } elseif ( Server::APACHE === $server_type ) {
222 $installed = Cache::rewrite_installed();
223 if ( $is_active ) {
224 $tone = self::OK;
225 $detail = 'Block installed and serving cache hits directly — PHP bypassed.';
226 } elseif ( 'mobile_separate' === $block_reason ) {
227 $tone = self::WARN;
228 $detail = 'Static rewrite disabled because Separate Mobile Cache is on.' . $mobile_block;
229 } elseif ( 'no_mod_headers' === $block_reason ) {
230 // Not "missing" — deliberately not installed, because
231 // Apache can't stamp X-XSpeed-Cache without mod_headers
232 // and the hit would be invisible and uncountable. Caching
233 // still works via the drop-in; say so, and give the one
234 // step that actually changes the outcome.
235 $tone = self::INFO;
236 $detail = 'Cache hits are served by xSpeed\'s drop-in and tagged X-XSpeed-Cache: HIT (php), so every hit is visible and counted. The faster .htaccess fast path is off because Apache\'s mod_headers module is not loaded — without it a static hit could not be tagged or counted. Enable mod_headers (`a2enmod headers` on Debian/Ubuntu, then restart Apache) to shave roughly 20-30ms off each cache hit.';
237 } elseif ( ! $installed ) {
238 $tone = self::WARN;
239 $detail = 'Block missing from .htaccess. Toggle Enable Cache off and on to reinstall it.';
240 } elseif ( $inconclusive ) {
241 // Same distinction as the nginx branch: the probe never
242 // reached a verdict, so telling the user to go re-check
243 // AllowOverride blames a config that may be perfectly
244 // fine. Report the failure honestly instead. (FBS-84012)
245 $tone = self::INFO;
246 $detail = sprintf(
247 'Block is installed, but the check could not complete (%s), so this is not evidence that anything is misconfigured. Re-run it with `wp xspeed cache recheck-rewrite` once the site can reach itself over HTTP.',
248 $probe_reason
249 );
250 } else {
251 $tone = self::WARN;
252 $detail = sprintf( 'Block installed but probe failed (%s). Confirm the .htaccess block is at the TOP of the file, and that AllowOverride is enabled for your site so mod_rewrite reads it.', $probe_reason );
253 }
254 $out[] = array(
255 'id' => 'static_rewrite',
256 'tone' => $tone,
257 'label' => 'Static-file rewrite (.htaccess)',
258 'detail' => $detail,
259 );
260 }
261 }
262
263 // Cache expiry vs preloader schedule (deterministic rule, issue #31):
264 // pages that expire faster than the preloader re-warms them leave the
265 // cache cold for most real traffic — the classic "24.8% hit ratio with
266 // everything on" misconfiguration. Pure logic in
267 // expiry_preload_check() so it's unit-testable.
268 if ( $cache_enabled ) {
269 $cache_opts = Settings_Manager::get( 'cache' );
270 $pre_opts = Settings_Manager::get( 'preloader' );
271 $schedule = (string) ( $pre_opts['schedule'] ?? 'manual' );
272 $mismatch = self::expiry_preload_check(
273 (int) ( $cache_opts['cache_expiry'] ?? 24 ),
274 $schedule,
275 ! empty( $pre_opts['enabled'] ),
276 self::schedule_interval_hours( $schedule )
277 );
278 if ( null !== $mismatch ) {
279 $out[] = $mismatch;
280 }
281 }
282
283 // Permalinks
284 $permalinks_ok = (bool) get_option( 'permalink_structure' );
285 $out[] = array(
286 'id' => 'permalinks',
287 'tone' => $permalinks_ok ? self::OK : self::WARN,
288 'label' => 'Permalinks',
289 'detail' => $permalinks_ok
290 ? 'Pretty permalinks active.'
291 : 'Set permalinks to anything other than "Plain" — page caching needs URL paths to key on.',
292 );
293
294 // Cache-poisoning Set-Cookie detection (issue #33): a plugin emitting
295 // Set-Cookie on anonymous pageviews forces CDN/edge BYPASS for all
296 // HTML (Cloudflare never caches a response carrying Set-Cookie). Probe
297 // is transient-throttled inside Cookie_Inspector, same pattern as the
298 // static-rewrite probe above — Health is the right place to pay for it.
299 // Cached-only: Health runs inside the dashboard REST request and the
300 // MCP get_health tool, so this must never block on an HTTP call.
301 // A cold verdict schedules a background refresh and reports nothing
302 // this paint. See Cookie_Inspector::probe_cached().
303 $cookie_probe = Cookie_Inspector::probe_cached();
304 if ( $cookie_probe['checked'] ) {
305 $offenders = $cookie_probe['cookies'];
306 if ( empty( $offenders ) ) {
307 $out[] = array(
308 'id' => 'set_cookie_poisoning',
309 'tone' => self::OK,
310 'label' => 'No cache-poisoning cookies',
311 'detail' => 'Anonymous pages are served without Set-Cookie, so CDN/edge caches can store them.',
312 );
313 } else {
314 $named = array();
315 foreach ( $offenders as $c ) {
316 $named[] = null !== $c['plugin']
317 ? sprintf( '%s is setting %s', $c['plugin'], $c['name'] )
318 : sprintf( 'an unidentified plugin is setting %s', $c['name'] );
319 }
320 $out[] = array(
321 'id' => 'set_cookie_poisoning',
322 'tone' => self::WARN,
323 'label' => 'Set-Cookie on cacheable pages',
324 'detail' => sprintf(
325 '%s — this prevents CDN edge caching (Cloudflare returns BYPASS for any response with Set-Cookie). Configure the plugin to set its cookie via JavaScript instead, or exclude it from anonymous pageviews.',
326 implode( '; ', $named )
327 ),
328 );
329 }
330 }
331
332 // Conflicting plugins
333 $out[] = array(
334 'id' => 'conflicts',
335 'tone' => empty( $conflicts ) ? self::OK : self::WARN,
336 'label' => 'Caching plugin conflicts',
337 'detail' => empty( $conflicts )
338 ? 'No other caching plugins detected.'
339 : sprintf( 'Active: %s. Deactivate before enabling xSpeed cache to avoid double-caching.', implode( ', ', $conflicts ) ),
340 );
341
342 return $out;
343 }
344
345 /**
346 * Hours between recurring preloader crawls, per schedule option.
347 * `twicedaily` is a WordPress core schedule — omitting it meant a site
348 * using it got no check at all, not even a pass.
349 */
350 public const PRELOAD_INTERVALS = array(
351 'hourly' => 1,
352 'twicedaily' => 12,
353 'daily' => 24,
354 'weekly' => 168,
355 );
356
357 /**
358 * Interval in hours for a cron schedule slug, or null when it isn't a
359 * recurring schedule (`manual`) or can't be resolved.
360 *
361 * Falls back to `wp_get_schedules()` so custom crons registered by a
362 * theme or another plugin are covered too, rather than silently
363 * skipping the check.
364 */
365 public static function schedule_interval_hours( string $schedule ): ?int {
366 if ( isset( self::PRELOAD_INTERVALS[ $schedule ] ) ) {
367 return self::PRELOAD_INTERVALS[ $schedule ];
368 }
369 if ( '' === $schedule || 'manual' === $schedule || ! function_exists( 'wp_get_schedules' ) ) {
370 return null;
371 }
372 $schedules = wp_get_schedules();
373 if ( ! isset( $schedules[ $schedule ]['interval'] ) ) {
374 return null;
375 }
376 $hours = (int) round( (int) $schedules[ $schedule ]['interval'] / HOUR_IN_SECONDS );
377 return $hours > 0 ? $hours : 1;
378 }
379
380 /**
381 * Deterministic rule: warn when cache_expiry is shorter than the
382 * preloader's recurring interval (pages go cold between crawls).
383 *
384 * Pure — no WP calls — so it can be unit-tested directly.
385 *
386 * @param int $expiry_hours Cache expiry in hours.
387 * @param string $schedule Preloader schedule (manual|hourly|twicedaily|daily|weekly|custom).
388 * @param bool $preloader_enabled Whether the preloader module is on.
389 * @param int|null $interval_hours Pre-resolved interval, for schedules
390 * outside PRELOAD_INTERVALS. Keeps this
391 * function pure — the caller does the
392 * wp_get_schedules() lookup.
393 * @return array{id:string,tone:string,label:string,detail:string}|null Check
394 * row, or null when the rule doesn't apply (preloader off/manual).
395 */
396 public static function expiry_preload_check( int $expiry_hours, string $schedule, bool $preloader_enabled, ?int $interval_hours = null ): ?array {
397 if ( ! $preloader_enabled ) {
398 return null;
399 }
400 $interval = $interval_hours ?? ( self::PRELOAD_INTERVALS[ $schedule ] ?? null );
401 if ( null === $interval || $interval < 1 ) {
402 return null;
403 }
404 if ( $expiry_hours < $interval ) {
405 return array(
406 'id' => 'expiry_preload_mismatch',
407 'tone' => self::WARN,
408 'label' => 'Cache expiry shorter than the preload schedule',
409 'detail' => sprintf(
410 'Pages expire after %dh but the preloader only re-warms them every %dh (%s), so most visits hit a cold cache. Raise Cache Expiry to at least %dh (Cache settings), or preload more often (Preloader settings).',
411 $expiry_hours,
412 $interval,
413 $schedule,
414 $interval
415 ),
416 );
417 }
418 return array(
419 'id' => 'expiry_preload_mismatch',
420 'tone' => self::OK,
421 'label' => 'Cache expiry covers the preload schedule',
422 'detail' => sprintf( 'Expiry %dh ≥ preload interval %dh (%s) — preloaded pages stay warm between crawls.', $expiry_hours, $interval, $schedule ),
423 );
424 }
425
426 /**
427 * Lightweight environment payload for the onboarding wizard. Keeps
428 * the legacy shape Onboarding::env_payload returned so the Welcome
429 * step's HealthRow rendering doesn't change.
430 */
431 public static function env_payload(): array {
432 global $wp_version;
433 $cache_dir = defined( 'XSPEED_CACHE_DIR' ) ? XSPEED_CACHE_DIR : ( WP_CONTENT_DIR . '/cache/xspeed' );
434 return array(
435 'wp' => array(
436 'version' => (string) $wp_version,
437 'ok' => version_compare( (string) $wp_version, '6.0', '>=' ),
438 ),
439 'php' => array(
440 'version' => PHP_VERSION,
441 'ok' => version_compare( PHP_VERSION, '7.4', '>=' ),
442 'modern' => version_compare( PHP_VERSION, '8.1', '>=' ),
443 ),
444 'server' => array(
445 'type' => Server::type(),
446 'gzip_mode' => Server::gzip_mode(),
447 ),
448 'cache_dir' => array(
449 'path' => $cache_dir,
450 'writable' => wp_mkdir_p( $cache_dir ) && wp_is_writable( $cache_dir ),
451 ),
452 'wp_config' => array(
453 'writable' => self::wp_config_writable(),
454 ),
455 'permalinks_ok' => (bool) get_option( 'permalink_structure' ),
456 'conflicts' => Server::conflicts(),
457 );
458 }
459
460 private static function wp_config_writable(): bool {
461 $path = ABSPATH . 'wp-config.php';
462 if ( ! file_exists( $path ) ) {
463 $path = dirname( ABSPATH ) . '/wp-config.php';
464 }
465 return file_exists( $path ) && wp_is_writable( $path );
466 }
467 }
468