| 1 |
<?php |
| 2 |
/** |
| 3 |
* Pro_Audit — scans the current Free configuration + cache stats and |
| 4 |
* surfaces Pro features that would specifically help THIS site. |
| 5 |
* |
| 6 |
* Powers the dashboard's "Run Pro audit" button. The point isn't to |
| 7 |
* list every Pro feature; it's to make each suggestion personal |
| 8 |
* ("Cache hit ratio is 38% → Pro Recommendations would tell you why") |
| 9 |
* so the user converts because Pro solves a problem they actually |
| 10 |
* see, not because we shouted "BUY NOW." |
| 11 |
* |
| 12 |
* Pure read-only. Returns an ordered list of suggestions: |
| 13 |
* |
| 14 |
* [ id, severity ('high'|'med'|'low'), reason, fact ] |
| 15 |
* |
| 16 |
* - id → matches a key in PRO_FEATURES (the React catalog), |
| 17 |
* so the panel renders title/body without duplicating |
| 18 |
* copy here. |
| 19 |
* - severity controls sort order + visual tone. |
| 20 |
* - reason → one-sentence explanation specific to this site's |
| 21 |
* state. Already-baked numbers/percentages so the |
| 22 |
* React side just prints it. |
| 23 |
* - fact → optional shorter inline stat (e.g. "38%") for the |
| 24 |
* result card's chip. |
| 25 |
* |
| 26 |
* Adding a rule: drop another `if (…) $out[] = …` block in run(). |
| 27 |
* Rules are independent — keep them small + concrete + factual. |
| 28 |
* |
| 29 |
* If the suggestion maps to a single Pro module, add it to |
| 30 |
* BACKING_MODULE and guard the rule with `! self::already_active($id)`. |
| 31 |
* A rule that fires on site state alone keeps nagging a customer who |
| 32 |
* already bought and enabled the feature — and any consumer rendering |
| 33 |
* the audit as a call-to-action (the Hub's "Enable" button) then shows |
| 34 |
* a control that can never clear. (#187) |
| 35 |
* |
| 36 |
* @package XSpeed |
| 37 |
*/ |
| 38 |
|
| 39 |
declare(strict_types=1); |
| 40 |
|
| 41 |
namespace XSpeed; |
| 42 |
|
| 43 |
defined( 'ABSPATH' ) || exit; |
| 44 |
|
| 45 |
final class Pro_Audit { |
| 46 |
|
| 47 |
public const SEVERITY_HIGH = 'high'; |
| 48 |
public const SEVERITY_MED = 'med'; |
| 49 |
public const SEVERITY_LOW = 'low'; |
| 50 |
|
| 51 |
/** |
| 52 |
* Snapshot of state every rule needs. Computed once per audit run |
| 53 |
* so we don't read the same option 8 times. |
| 54 |
* |
| 55 |
* @param array|null $totals_override Test injection — Brain Monkey |
| 56 |
* can't mock static class methods, |
| 57 |
* so tests synthesize the 24h |
| 58 |
* counter shape here directly. |
| 59 |
* Production callers leave null. |
| 60 |
* |
| 61 |
* @return array<string,mixed> |
| 62 |
*/ |
| 63 |
private static function snapshot( ?array $totals_override = null ): array { |
| 64 |
$opts = static function ( string $slug ): array { |
| 65 |
return (array) get_option( 'xspeed_module_' . $slug, array() ); |
| 66 |
}; |
| 67 |
if ( null !== $totals_override ) { |
| 68 |
$totals = $totals_override; |
| 69 |
} elseif ( class_exists( '\\XSpeed\\Hit_Counter' ) ) { |
| 70 |
$totals = Hit_Counter::totals_24h(); |
| 71 |
} else { |
| 72 |
$totals = array( 'hits' => 0, 'misses' => 0, 'excluded' => 0, 'ratio' => 0.0 ); |
| 73 |
} |
| 74 |
$cloudflare = $opts( 'cloudflare' ); |
| 75 |
return array( |
| 76 |
'cache' => $opts( 'cache' ), |
| 77 |
'minify' => $opts( 'minify' ), |
| 78 |
'lazy' => $opts( 'lazy' ), |
| 79 |
'gzip' => $opts( 'gzip' ), |
| 80 |
'browser_cache' => $opts( 'browser-cache' ), |
| 81 |
'cloudflare' => $cloudflare, |
| 82 |
'cdn' => $opts( 'cdn' ), |
| 83 |
'database' => $opts( 'database' ), |
| 84 |
'preloader' => $opts( 'preloader' ), |
| 85 |
'heartbeat' => $opts( 'heartbeat' ), |
| 86 |
'cache_enabled' => class_exists( '\\XSpeed\\Settings' ) |
| 87 |
? ! empty( Settings::get()['cache_enabled'] ) |
| 88 |
: false, |
| 89 |
// An edge cache (Cloudflare) in front means the origin hit ratio is |
| 90 |
// only the origin layer — hits served at the edge never reach PHP — |
| 91 |
// so a low number is an attribution artefact, not a cache problem. |
| 92 |
// Rule 2 must not fire an upsell off it. (#118) |
| 93 |
'edge_cache' => ! empty( $cloudflare['enabled'] ), |
| 94 |
'totals_24h' => array( |
| 95 |
'hits' => (int) ( $totals['hits'] ?? 0 ), |
| 96 |
'misses' => (int) ( $totals['misses'] ?? 0 ), |
| 97 |
// 404s + bots, kept out of the ratio denominator. (#118) |
| 98 |
'excluded' => (int) ( $totals['excluded'] ?? 0 ), |
| 99 |
'total' => (int) ( $totals['hits'] ?? 0 ) + (int) ( $totals['misses'] ?? 0 ), |
| 100 |
'ratio' => (float) ( $totals['ratio'] ?? 0.0 ), |
| 101 |
), |
| 102 |
); |
| 103 |
} |
| 104 |
|
| 105 |
/** |
| 106 |
* Which Pro module backs each suggestion id. A suggestion whose module |
| 107 |
* is installed AND switched on is not an upsell any more — the site |
| 108 |
* already has the thing we'd be selling. (#187) |
| 109 |
* |
| 110 |
* Ids without an entry (analytics fallback, white-label, …) are always |
| 111 |
* eligible; absence here means "no single module answers this". |
| 112 |
*/ |
| 113 |
private const BACKING_MODULE = array( |
| 114 |
'webp-avif' => 'images', |
| 115 |
'rum' => 'rum', |
| 116 |
'critical-css' => 'critical-css', |
| 117 |
); |
| 118 |
|
| 119 |
/* |
| 120 |
* `cloudflare-apo` is deliberately NOT here. |
| 121 |
* |
| 122 |
* APO's on/off state lives at Cloudflare — `Cloudflare_Apo::status()` |
| 123 |
* is a live GET against their API, and our own options carry only the |
| 124 |
* values we PUSH to it (cache_level, browser_ttl). Nothing local |
| 125 |
* records whether it is on. The audit runs on every dashboard load and |
| 126 |
* on Free installs with no credentials, so it must not make a network |
| 127 |
* call to find out. |
| 128 |
* |
| 129 |
* The first cut mapped it to an `enabled` key that the module never |
| 130 |
* writes, which read as "always eligible" — the right OUTCOME by |
| 131 |
* accident, via a check that could never fire. Stating the limitation |
| 132 |
* is better than a guard that looks like it works. If a cached |
| 133 |
* APO-state option is added later, give it a probe below and restore |
| 134 |
* the mapping. (#187 review) |
| 135 |
*/ |
| 136 |
|
| 137 |
/** |
| 138 |
* Ids whose module records its on/off state somewhere other than a |
| 139 |
* plain `enabled` flag. |
| 140 |
* |
| 141 |
* The first cut of this guard read `enabled` for all of them. Only |
| 142 |
* `rum` and `critical-css` have that key — `images` is switched on PER |
| 143 |
* FORMAT (`webp` / `avif`), so a site with conversion fully on was |
| 144 |
* still told to buy image conversion, and the Hub kept drawing an |
| 145 |
* Enable button that could never clear. (#187 review) |
| 146 |
* |
| 147 |
* A closure per id, receiving that module's EFFECTIVE options — schema |
| 148 |
* defaults merged over the stored row, which is what the module actually |
| 149 |
* runs on. Reading the raw row instead missed every setting still at its |
| 150 |
* default, and Images defaults `webp` to true. (#187 QA round 2) |
| 151 |
* |
| 152 |
* @return array<string, callable(array):bool> |
| 153 |
*/ |
| 154 |
private static function activity_probes(): array { |
| 155 |
return array( |
| 156 |
// Conversion is per format — either one means new uploads are |
| 157 |
// being converted, which is the thing the suggestion sells. |
| 158 |
'webp-avif' => static function ( array $o ): bool { |
| 159 |
return ! empty( $o['webp'] ) || ! empty( $o['avif'] ); |
| 160 |
}, |
| 161 |
); |
| 162 |
} |
| 163 |
|
| 164 |
/** |
| 165 |
* Is the Pro module backing this suggestion already active? |
| 166 |
* |
| 167 |
* Resolved by module SLUG, never by referencing a Pro class: the audit |
| 168 |
* runs on Free installs where those classes do not exist, and Free never |
| 169 |
* names Pro. Settings_Manager returns an empty array for a slug that is |
| 170 |
* not registered, so Free resolves to "not active" and keeps suggesting. |
| 171 |
*/ |
| 172 |
private static function already_active( string $id ): bool { |
| 173 |
$slug = self::BACKING_MODULE[ $id ] ?? ''; |
| 174 |
if ( '' === $slug ) { |
| 175 |
return false; |
| 176 |
} |
| 177 |
|
| 178 |
/* |
| 179 |
* Suppression is only honest while Pro is installed AND licensed. |
| 180 |
* |
| 181 |
* Deactivating Pro leaves its settings rows behind, and nothing |
| 182 |
* clears them — Pro has no uninstall routine for them, so deleting |
| 183 |
* the plugin does not help either. Reading those rows directly meant |
| 184 |
* a Free-only site with the same history was silently never shown |
| 185 |
* the RUM and Critical CSS suggestions again. An expired licence is |
| 186 |
* the same shape with a sharper edge: the feature is gated OFF and |
| 187 |
* genuinely not running, which is exactly the moment a renewal |
| 188 |
* prompt is most useful. (#187 review) |
| 189 |
* |
| 190 |
* `xspeed_pro_state` is the signal Pro already reports to Free for |
| 191 |
* the gated UI; it needs no Pro class reference here. |
| 192 |
*/ |
| 193 |
if ( 'active' !== self::pro_state() ) { |
| 194 |
return false; |
| 195 |
} |
| 196 |
|
| 197 |
/* |
| 198 |
* Read the module's EFFECTIVE settings, not its stored row. |
| 199 |
* |
| 200 |
* A raw get_option() sees only what someone has explicitly saved. A |
| 201 |
* module's schema defaults are what it actually runs on until then — |
| 202 |
* Pro's Images module defaults `webp` to true, so a site that bought |
| 203 |
* Pro and never opened the Images panel is converting images while |
| 204 |
* its option row has no `webp` key at all. The probe read false and |
| 205 |
* the audit told that customer to buy image conversion: the exact |
| 206 |
* complaint in #187, reproduced on a different feature. Opening the |
| 207 |
* panel and pressing Save with no changes made the suggestion vanish, |
| 208 |
* which is the tell that the check was reading the wrong thing rather |
| 209 |
* than a genuine "off". (#187 QA round 2) |
| 210 |
* |
| 211 |
* Settings_Manager::get() merges schema defaults over the stored row. |
| 212 |
* It returns array() for a module that is not registered, so on Free — |
| 213 |
* where the Pro module does not exist — this still resolves to "not |
| 214 |
* active" and every suggestion keeps firing. Safe to call here because |
| 215 |
* the pro_state() gate above means Pro is loaded by this point. |
| 216 |
*/ |
| 217 |
$opts = Settings_Manager::get( $slug ); |
| 218 |
$probes = self::activity_probes(); |
| 219 |
if ( isset( $probes[ $id ] ) ) { |
| 220 |
return (bool) $probes[ $id ]( $opts ); |
| 221 |
} |
| 222 |
|
| 223 |
return ! empty( $opts['enabled'] ); |
| 224 |
} |
| 225 |
|
| 226 |
/** |
| 227 |
* Pro's own report of its licence state: 'not_installed' | 'unlicensed' |
| 228 |
* | 'active'. Mirrors Admin::pro_state(), which is private to that |
| 229 |
* class; only 'active' means Pro's features are actually running. |
| 230 |
*/ |
| 231 |
private static function pro_state(): string { |
| 232 |
$present = class_exists( '\\XSpeed\\Tier_Registry' ) && Tier_Registry::pro_active(); |
| 233 |
$default = $present ? 'active' : 'not_installed'; |
| 234 |
|
| 235 |
/** This filter is documented in includes/class-admin.php */ |
| 236 |
$state = (string) apply_filters( 'xspeed_pro_state', $default ); |
| 237 |
|
| 238 |
return in_array( $state, array( 'not_installed', 'unlicensed', 'active' ), true ) ? $state : $default; |
| 239 |
} |
| 240 |
|
| 241 |
/** |
| 242 |
* @param array|null $totals_override See snapshot(). Production |
| 243 |
* callers pass nothing. |
| 244 |
* |
| 245 |
* @return array<int,array{id:string,severity:string,reason:string,fact?:string}> |
| 246 |
*/ |
| 247 |
public static function run( ?array $totals_override = null ): array { |
| 248 |
$s = self::snapshot( $totals_override ); |
| 249 |
$out = array(); |
| 250 |
|
| 251 |
// Rule 1 — Cloudflare connected but APO not in use. |
| 252 |
// High signal: user already pays the Cloudflare overhead, APO |
| 253 |
// is the highest-leverage Pro feature they can flip on next. |
| 254 |
// |
| 255 |
// Deliberately NOT guarded by already_active(): APO's real state |
| 256 |
// lives at Cloudflare, not in an option here, and finding out means |
| 257 |
// a live API call — which this audit runs on every dashboard load, |
| 258 |
// including Free installs with no credentials. The guard used to be |
| 259 |
// called here anyway; it could never fire (no BACKING_MODULE entry), |
| 260 |
// so it produced the right outcome by accident while reading as |
| 261 |
// though the case were handled. See the note beside BACKING_MODULE. |
| 262 |
// (#187 QA round 2) |
| 263 |
if ( ! empty( $s['cloudflare']['enabled'] ) ) { |
| 264 |
$out[] = array( |
| 265 |
'id' => 'cloudflare-apo', |
| 266 |
'severity' => self::SEVERITY_HIGH, |
| 267 |
'reason' => 'Cloudflare is already connected. Pro adds Automatic Platform Optimization, which edge-caches your HTML — typically cuts TTFB in half.', |
| 268 |
'fact' => 'Cloudflare on', |
| 269 |
); |
| 270 |
} |
| 271 |
|
| 272 |
// Rule 2 — Low cache hit ratio with meaningful traffic. |
| 273 |
// "Meaningful" = > 50 hits over 24h; below that the ratio is |
| 274 |
// statistical noise and we'd suggest based on bad data. The ratio is |
| 275 |
// now computed over real traffic only (404s + bots excluded, #118), and |
| 276 |
// we skip it entirely when an edge cache fronts the origin — behind |
| 277 |
// Cloudflare a low origin ratio means hits are served at the edge, not |
| 278 |
// that the cache is failing, so firing a "your cache is bad" upsell off |
| 279 |
// it is selling against a measurement artefact. |
| 280 |
if ( empty( $s['edge_cache'] ) |
| 281 |
&& $s['totals_24h']['total'] >= 50 |
| 282 |
&& $s['totals_24h']['ratio'] < 0.5 ) { |
| 283 |
$pct = (int) round( $s['totals_24h']['ratio'] * 100 ); |
| 284 |
$out[] = array( |
| 285 |
'id' => 'recommendations', |
| 286 |
'severity' => self::SEVERITY_HIGH, |
| 287 |
'reason' => sprintf( |
| 288 |
'Cache hit ratio is %d%% over the last 24h. Pro Recommendations identifies which URLs miss the cache and why, with one-click fixes.', |
| 289 |
$pct |
| 290 |
), |
| 291 |
'fact' => $pct . '% hit', |
| 292 |
); |
| 293 |
} |
| 294 |
|
| 295 |
// Rule 3 — Lazy-load enabled but no auto WebP/AVIF. |
| 296 |
// User cares about images (lazy on) → next gain is format. |
| 297 |
if ( ! empty( $s['lazy']['lazy_images'] ) && ! self::already_active( 'webp-avif' ) ) { |
| 298 |
$out[] = array( |
| 299 |
'id' => 'webp-avif', |
| 300 |
'severity' => self::SEVERITY_MED, |
| 301 |
'reason' => 'Images are lazy-loaded. Pro auto-converts new JPEG/PNG uploads to WebP and AVIF — typically 25-35% smaller at the same visual quality.', |
| 302 |
); |
| 303 |
} |
| 304 |
|
| 305 |
// Rule 4 — High traffic without RUM data. |
| 306 |
// Real-user metrics matter more than synthetic Lighthouse when |
| 307 |
// the site has actual visitors. |
| 308 |
if ( $s['totals_24h']['total'] >= 100 && ! self::already_active( 'rum' ) ) { |
| 309 |
$views = number_format( $s['totals_24h']['total'] ); |
| 310 |
$out[] = array( |
| 311 |
'id' => 'rum', |
| 312 |
'severity' => self::SEVERITY_MED, |
| 313 |
'reason' => sprintf( |
| 314 |
'You served %s requests in 24h. Pro RUM samples actual LCP, CLS and INP from those visitors — Lighthouse only simulates one device, one connection.', |
| 315 |
$views |
| 316 |
), |
| 317 |
'fact' => $views . ' / 24h', |
| 318 |
); |
| 319 |
} |
| 320 |
|
| 321 |
// Rule 5 — HTML minify on but JS minify off (theme-safe stance). |
| 322 |
// Suggest Critical CSS as the next gain that doesn't touch JS. |
| 323 |
if ( ! empty( $s['minify']['minify_html'] ) && empty( $s['minify']['minify_js'] ) |
| 324 |
&& ! self::already_active( 'critical-css' ) ) { |
| 325 |
$out[] = array( |
| 326 |
'id' => 'critical-css', |
| 327 |
'severity' => self::SEVERITY_MED, |
| 328 |
'reason' => 'JS minify is off (good — high theme-conflict risk). Pro Critical CSS delivers similar first-paint gains without touching JavaScript.', |
| 329 |
); |
| 330 |
} |
| 331 |
|
| 332 |
// Rule 6 — Database cleanup on manual schedule. |
| 333 |
// Only fire when the user has actually configured the Database |
| 334 |
// module (has saved options). Empty option = user hasn't |
| 335 |
// touched it; don't suggest scheduling something they might |
| 336 |
// never use. |
| 337 |
if ( ! empty( $s['database'] ) && 'manual' === ( $s['database']['schedule'] ?? 'manual' ) ) { |
| 338 |
$out[] = array( |
| 339 |
'id' => 'recommendations', |
| 340 |
'severity' => self::SEVERITY_LOW, |
| 341 |
'reason' => 'Database cleanup is set to manual. Pro Recommendations engine auto-schedules cleanups based on smart triggers (after publish, before backup).', |
| 342 |
); |
| 343 |
} |
| 344 |
|
| 345 |
// Rule 7 — Agency / professional usage signal. |
| 346 |
// >= 5 enabled modules suggests serious use → white-label is |
| 347 |
// what they'd actually want next. |
| 348 |
$enabled = 0; |
| 349 |
foreach ( array( 'minify', 'gzip', 'lazy', 'browser_cache', 'cloudflare', 'cdn', 'preloader' ) as $k ) { |
| 350 |
if ( ! empty( $s[ $k ]['enabled'] ) ) { |
| 351 |
$enabled++; |
| 352 |
} |
| 353 |
} |
| 354 |
if ( $s['cache_enabled'] ) { |
| 355 |
$enabled++; |
| 356 |
} |
| 357 |
if ( $enabled >= 5 ) { |
| 358 |
$out[] = array( |
| 359 |
'id' => 'white-label', |
| 360 |
'severity' => self::SEVERITY_LOW, |
| 361 |
'reason' => sprintf( |
| 362 |
'You\'ve configured %d modules — looks like agency work. Pro White-Label rebrands the dashboard chrome for client handoff.', |
| 363 |
$enabled |
| 364 |
), |
| 365 |
'fact' => $enabled . ' modules', |
| 366 |
); |
| 367 |
} |
| 368 |
|
| 369 |
// Fallback — never return an empty audit. Analytics is the |
| 370 |
// safe always-relevant suggestion (every site has cache |
| 371 |
// activity to chart). |
| 372 |
if ( empty( $out ) ) { |
| 373 |
$out[] = array( |
| 374 |
'id' => 'analytics', |
| 375 |
'severity' => self::SEVERITY_LOW, |
| 376 |
'reason' => 'See which pages benefit most from caching, where your slow URLs are, and your hit-ratio over time.', |
| 377 |
); |
| 378 |
} |
| 379 |
|
| 380 |
// Dedupe by id, keeping the highest-severity rule per feature. |
| 381 |
// Rules independently suggest the same feature for different |
| 382 |
// reasons; pick the strongest reason to show. |
| 383 |
$by_id = array(); |
| 384 |
$order = array( self::SEVERITY_HIGH => 0, self::SEVERITY_MED => 1, self::SEVERITY_LOW => 2 ); |
| 385 |
foreach ( $out as $row ) { |
| 386 |
$id = $row['id']; |
| 387 |
if ( ! isset( $by_id[ $id ] ) ) { |
| 388 |
$by_id[ $id ] = $row; |
| 389 |
continue; |
| 390 |
} |
| 391 |
$existing_rank = $order[ $by_id[ $id ]['severity'] ] ?? 9; |
| 392 |
$new_rank = $order[ $row['severity'] ] ?? 9; |
| 393 |
if ( $new_rank < $existing_rank ) { |
| 394 |
$by_id[ $id ] = $row; |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
$out = array_values( $by_id ); |
| 399 |
usort( $out, static function ( $a, $b ) use ( $order ) { |
| 400 |
return ( $order[ $a['severity'] ] ?? 9 ) <=> ( $order[ $b['severity'] ] ?? 9 ); |
| 401 |
} ); |
| 402 |
return $out; |
| 403 |
} |
| 404 |
} |
| 405 |
|