PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.0
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.0
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 1.2.0 All 28 releases
xspeed / includes / class-plugin.php

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

486 lines 21.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Main plugin bootstrap.
4 *
5 * @package XSpeed
6 */
7
8 namespace XSpeed;
9
10 defined( 'ABSPATH' ) || exit;
11
12 class Plugin {
13
14 /**
15 * Data-schema version for one-time migrations, independent of the
16 * plugin version header. Bump when adding a step to maybe_upgrade().
17 */
18 public const DATA_VERSION = '1.1.6';
19
20 private static $instance = null;
21
22 /** @var Usage_Tracker|null */
23 private $usage_tracker = null;
24
25 public static function instance() {
26 if ( null === self::$instance ) {
27 self::$instance = new self();
28 }
29 return self::$instance;
30 }
31
32 public function init() {
33 // v1 services that are NOT yet wrapped as Modules (Admin, Rest_Api,
34 // Cache, Onboarding) are instantiated directly. Minifier is now
35 // instantiated by MinifyModule::boot(); Gzip is purely static.
36 new Admin();
37 new Rest_Api();
38 new Cache();
39 new Rest_Cache();
40 new Onboarding();
41
42 // Optional deactivation feedback survey on the Plugins screen. Admin
43 // context only (its hooks are admin_enqueue_scripts / admin_footer /
44 // wp_ajax). Sends nothing unless the user clicks "Submit & Deactivate".
45 if ( is_admin() ) {
46 new Deactivation_Feedback();
47 }
48
49 // Opt-in usage analytics. Instantiating + init() only registers the
50 // cron callback; NOTHING is collected or sent until the admin opts in
51 // from the setup wizard (Onboarding wires the consent toggle to
52 // Usage_Tracker::opt_in()). See class-usage-tracker.php privacy contract.
53 $this->start_plugin_tracking();
54
55 // Auto-heal the cache drop-in + WP_CACHE constant when state
56 // drifts. Scoped to admin_init only: filesystem writes belong in
57 // an authenticated admin context, never on anonymous front-end
58 // requests. The user already opted in (cache_enabled=true) —
59 // this is a consistency check, not a new install path. First
60 // admin page load after a plugin upgrade restores the state;
61 // front-end then serves from cache on the next request.
62 add_action( 'admin_init', array( Cache::class, 'auto_heal' ) );
63 // Cheap: returns immediately unless the stored schema version is
64 // behind. Covers updates and multisite, where activate() never runs.
65 add_action( 'admin_init', array( Score_Store::class, 'maybe_install' ) );
66
67 // Secondary net: restore as soon as an update completes, for the
68 // cases where activate() does not re-run (bulk updates, auto-updates,
69 // some host updaters). Best-effort by nature — this callback is only
70 // registered when we were loaded in the request performing the
71 // update, which is not guaranteed while WE are the plugin being
72 // replaced. The restore in activate() is the primary guarantee;
73 // auto_heal() on admin_init remains the backstop.
74 add_action( 'upgrader_process_complete', array( $this, 'maybe_restore_after_update' ), 10, 2 );
75
76 // Per-post cache rules (Phase 3.4) — registers postmeta with
77 // REST + meta box on edit screens.
78 Cache_Meta_Box::boot();
79
80 // Single-URL purge entry points — row actions, the edit-screen
81 // button and the admin-post handler the admin-bar item also uses.
82 Purge_Ui::boot();
83
84 // Phase 0 architecture — managers + Free modules. v1 services
85 // (Cache/Minifier/Gzip) are NOT yet Modules; they'll be refactored
86 // in a follow-up PR with parity tests.
87 Conflict_Registry::boot();
88
89 // Read-only page-cache ownership evidence, behind the same
90 // activation/deactivation invalidation as the conflict matrix.
91 Page_Cache_Detector::boot();
92
93 // Integrations that clear OTHER plugins' caches of rendered output
94 // (Elementor's element cache + generated CSS). Registers a listener
95 // only; nothing runs until Cache::purge_render_caches() asks.
96 Render_Caches::boot();
97
98 // Register Free modules via the same action xspeed-pro uses, so
99 // the bootstrap path is symmetric across tiers.
100 add_action( 'xspeed_register_modules', array( $this, 'register_free_modules' ) );
101
102 // Fire the registration action + boot the registry at a LATER
103 // plugins_loaded priority so add-on plugins (xspeed-pro, in
104 // alphabetical order so it runs at default priority 10 AFTER
105 // us, but any add-on loaded at plugins_loaded(< 20)) have a
106 // chance to register their `xspeed_register_modules` callback
107 // before we fire the action.
108 //
109 // Bug history: previously this fired inline from init() at
110 // priority 10. xspeed-pro's plugins_loaded(15) hook then added
111 // its register_pro_modules callback AFTER the action had
112 // already fired — Pro modules never appeared in the registry.
113 // Caught by the ProStatus sentinel module's integration test.
114 add_action( 'plugins_loaded', array( $this, 'fire_module_lifecycle' ), 20 );
115
116 // One-time data migrations keyed on the stored version. Runs in
117 // admin only — nothing here needs to touch a front-end request.
118 if ( is_admin() ) {
119 add_action( 'plugins_loaded', array( $this, 'maybe_upgrade' ), 21 );
120 }
121 }
122
123 /**
124 * Run version-gated data migrations exactly once per upgrade.
125 *
126 * Keyed on `xspeed_data_version` rather than the plugin version header
127 * so a migration can be added without forcing a release bump.
128 */
129 public function maybe_upgrade(): void {
130 $current = (string) get_option( 'xspeed_data_version', '0' );
131 if ( version_compare( $current, self::DATA_VERSION, '>=' ) ) {
132 return;
133 }
134
135 // 1.1.2 — strip credential values recorded by earlier versions'
136 // settings change annotations (they're served by the trend endpoints).
137 Activity_Log::redact_legacy_secrets();
138
139 // 1.1.4 — earlier versions cached a failed loopback as "gzip is not
140 // active" for an hour, which showed up as a bogus server-config
141 // warning. Drop the stale answer so the fixed probe re-runs instead
142 // of the wrong verdict living on past the update (issue #18).
143 delete_transient( 'xspeed_gzip_active' );
144
145 // 1.1.6 — a `/?s=<term>` request used to write its results page into
146 // the static tree under the *searched-from* path, which for the usual
147 // query-form search is `/`. The web server then served that results
148 // page as the homepage to every visitor. The write is fixed in
149 // Cache::store_static(), but an entry poisoned before the update
150 // outlives it: nothing purges on upgrade, and the static serve path
151 // never revalidates. Clear the tree once. The flat cache is keyed
152 // correctly and is deliberately left alone. (issue #191)
153 Cache::purge_static_tree();
154
155 update_option( 'xspeed_data_version', self::DATA_VERSION, false );
156 }
157
158 /**
159 * Phase 2 of plugin init: fire the registration action (collecting
160 * Free + Pro + any third-party modules hooked into
161 * `xspeed_register_modules`) and boot the registry.
162 *
163 * Runs at plugins_loaded(20) so every add-on that hooks at any
164 * priority < 20 has time to register first.
165 */
166 public function fire_module_lifecycle(): void {
167 $this->ensure_modules_registered();
168
169 Module_Registry::boot_all();
170 }
171
172 /**
173 * Fire `xspeed_register_modules` if this request has not yet, hooking
174 * Free's own registration first when init() never got the chance.
175 *
176 * The activation request is the case that matters. activate_plugin()
177 * includes the plugin file long after `plugins_loaded` has fired, so the
178 * `plugins_loaded` callback init() would have added never runs, and
179 * neither does the add_action() inside it that puts register_free_modules
180 * on the action. Firing the action from activate() then registered
181 * nothing: Settings::conflict_safe_profile() composed from an empty
182 * registry, and a site with WP Super Cache came up with lazy-load,
183 * resource hints, font swapping and preloading switched on — only the
184 * four settings the registry-independent fallback names were held down
185 * (PR #295 review). Module_Registry::activate_all() has been a no-op on
186 * the same request for the same reason.
187 *
188 * On the activation request that means Free only: an add-on cannot have
189 * hooked yet, because xspeed-pro bails when Free's classes are absent and
190 * only hooks the action (at priority 20, from plugins_loaded(15)) once
191 * Free is active. On an ordinary request fire_module_lifecycle() reaches
192 * this at plugins_loaded(20) with every add-on already hooked. Do not
193 * call this from anything that can run in between: the action fires
194 * once, and an add-on that has not hooked yet stays unregistered for the
195 * whole request.
196 * did_action() keeps the action to one firing per request, so an
197 * activation that ran first does not make plugins_loaded(20) register
198 * every module a second time.
199 */
200 public function ensure_modules_registered(): void {
201 if ( did_action( 'xspeed_register_modules' ) ) {
202 return;
203 }
204
205 /*
206 * register_free_modules() does an unconditional `new` on every module
207 * class. On an ordinary request xspeed.php's integrity check refuses
208 * to boot before that can fatal and explains itself in an admin
209 * notice; the activation hook is registered outside that check, so
210 * an install missing a module file (truncated zip, a security
211 * plugin's quarantine, a half-applied update) would fatal here with
212 * no notice and no active plugin. Same answer as boot: do nothing.
213 */
214 if ( function_exists( 'xspeed_missing_core_classes' ) && ! empty( xspeed_missing_core_classes() ) ) {
215 return;
216 }
217
218 if ( ! has_action( 'xspeed_register_modules', array( $this, 'register_free_modules' ) ) ) {
219 add_action( 'xspeed_register_modules', array( $this, 'register_free_modules' ) );
220 }
221
222 /**
223 * Action: xspeed_register_modules
224 *
225 * Free modules register at priority 10; xspeed-pro at priority
226 * 20; site code can hook in between to inject custom modules.
227 * Fires exactly once per request.
228 */
229 do_action( 'xspeed_register_modules' );
230 }
231
232 /**
233 * Register the Free Modules shipped in this plugin. Add new module
234 * registrations here. Pro plugin hooks the same action separately.
235 */
236 public function register_free_modules(): void {
237 Module_Registry::register( new \XSpeed\Modules\Cache\CacheModule() );
238 Module_Registry::register( new \XSpeed\Modules\Health\HealthModule() );
239 // Settings — owns no settings itself; it's the CLI/MCP surface over
240 // Settings_Manager. Registering it is what makes `xspeed settings`
241 // exist, which is what keeps the curated get_settings/update_settings
242 // tools in the MCP catalog. (#149/#153)
243 Module_Registry::register( new \XSpeed\Modules\Settings\SettingsModule() );
244 // External performance scores (PSI / GTmetrix) — Free, off by
245 // default. Rendered inside the Health host page's PageSpeed tab, so
246 // it has no sidebar row of its own.
247 Module_Registry::register( new \XSpeed\Modules\Score\ScoreModule() );
248 Module_Registry::register( new \XSpeed\Modules\Preloader\PreloaderModule() );
249 Module_Registry::register( new \XSpeed\Modules\Heartbeat\HeartbeatModule() );
250 Module_Registry::register( new \XSpeed\Modules\Minify\MinifyModule() );
251 Module_Registry::register( new \XSpeed\Modules\Gzip\GzipModule() );
252 Module_Registry::register( new \XSpeed\Modules\Lazy\LazyModule() );
253 Module_Registry::register( new \XSpeed\Modules\Bloat\BloatModule() );
254 Module_Registry::register( new \XSpeed\Modules\Database\DatabaseModule() );
255 Module_Registry::register( new \XSpeed\Modules\Cdn\CdnModule() );
256 Module_Registry::register( new \XSpeed\Modules\Cloudflare\CloudflareModule() );
257 Module_Registry::register( new \XSpeed\Modules\ObjectCache\ObjectCacheModule() );
258 Module_Registry::register( new \XSpeed\Modules\BrowserCache\BrowserCacheModule() );
259 // Advanced Cache — a Free container row that gathers the Pro
260 // cache-coverage features (404 / search / feed / REST / rules /
261 // maintenance) into one sidebar sub-item (FBS-83633).
262 Module_Registry::register( new \XSpeed\Modules\CacheCoverage\CacheCoverageModule() );
263 Module_Registry::register( new \XSpeed\Modules\Fonts\FontsModule() );
264 Module_Registry::register( new \XSpeed\Modules\ResourceHints\ResourceHintsModule() );
265 // AI Privacy (GDPR off-switch) ships in Free even though every AI
266 // *feature* is Pro — privacy is a right, not a paid tier. FEATURES.md
267 // §AI row 6 mandates it. Without this registration the module was dead
268 // code: no REST/settings surface, the promised off-switch unreachable
269 // (FBS-83633 Bug 1). It carries its own cli_commands() so it satisfies
270 // the CLI/MCP coverage guard once registered.
271 Module_Registry::register( new \XSpeed\Modules\AIPrivacy\AIPrivacyModule() );
272 // Migration moved Pro → Free: it's an acquisition/onboarding feature
273 // (detect a competing caching plugin, import its settings, switch over),
274 // so it must work without a Pro license. Agency-scale extras (profiles,
275 // bulk multisite, host presets) remain Pro.
276 Module_Registry::register( new \XSpeed\Modules\Migration\MigrationModule() );
277 // Help & Support moved Pro → Free: a ticket link + read-only system
278 // snapshot is onboarding/diagnostics, not a paid value-add, so every
279 // user gets it. The snapshot degrades gracefully without Pro (Pro
280 // version/license fields fall back to defaults via defined()/get_option).
281 Module_Registry::register( new \XSpeed\Modules\Support\SupportModule() );
282 // MCP remote control (AI assistants) — Free. The plugin serves the
283 // MCP protocol at the site's own /xspeed/mcp URL; the only gate is
284 // the per-site connection token an admin mints via Connect. No
285 // license, no hosted infra. See IMPLEMENTATION.md §17.
286 Module_Registry::register( new \XSpeed\Modules\Mcp\McpModule() );
287 }
288
289 /**
290 * Boot the opt-in usage tracker. Registers the cron sender only; the send
291 * itself is consent-gated inside Usage_Tracker. The instance is held so the
292 * onboarding REST handler can flip consent via usage_tracker()->opt_in().
293 */
294 public function start_plugin_tracking(): void {
295 $this->usage_tracker = Usage_Tracker::get_instance(
296 XSPEED_FILE,
297 array(
298 'opt_in' => true,
299 'item_id' => defined( 'XSPEED_INSIGHTS_ITEM_ID' ) ? XSPEED_INSIGHTS_ITEM_ID : false,
300 )
301 );
302 $this->usage_tracker->init();
303 }
304
305 /**
306 * The shared Usage_Tracker singleton (or null if tracking wasn't booted,
307 * e.g. on the activation hook before init() runs).
308 */
309 public function usage_tracker(): ?Usage_Tracker {
310 return $this->usage_tracker;
311 }
312
313 public static function activate() {
314 // Nothing below can see a module the registry does not hold — the
315 // conflict-safe profile Settings::set_defaults() may pick is composed
316 // from it, and activate_all() walks it. See ensure_modules_registered()
317 // for why the registry is empty on this request without this call.
318 self::instance()->ensure_modules_registered();
319
320 $profile = Settings::set_defaults();
321
322 // Score history table. Also called on admin_init (see init()) because
323 // activation does not fire for a site added to a multisite network
324 // later, nor after an update that ships a new schema version.
325 Score_Store::maybe_install();
326
327 if ( ! file_exists( XSPEED_CACHE_DIR ) ) {
328 wp_mkdir_p( XSPEED_CACHE_DIR );
329 }
330 Cache::write_silence( XSPEED_CACHE_DIR );
331
332 /*
333 * One exception to "caching is only ever enabled from the admin UI":
334 * a fresh install another plugin performed on the user's behalf.
335 *
336 * That plugin asked the user for site performance and installed us to
337 * provide it; making them go and find a second switch afterwards is
338 * a step nobody wants. It is also what the copy-vendored Setup::finish()
339 * did, so hosts migrating off it keep the behaviour they have.
340 *
341 * PROFILE_HOST_PAGE_CACHE is the whole condition, and it means three
342 * things at once: the install was genuinely fresh, nothing else owns
343 * the page cache, and another plugin claimed the install. Every other
344 * fresh install — including a user's own on a clear site — waits for
345 * the wizard. Every OTHER feature is off in this profile; the cache is
346 * the one thing a host may assume, because it is what it installed us
347 * for. And toggle() runs its own ownership transaction, so a
348 * competitor appearing between the two checks loses the race rather
349 * than being overwritten.
350 */
351 if ( Settings::PROFILE_HOST_PAGE_CACHE === $profile ) {
352 $state = Cache::toggle( true );
353 if ( ! empty( $state['blocked'] ) ) {
354 /*
355 * Refused after all — a competitor that appeared between the
356 * profile decision and the write, or a drop-in we could not
357 * install. The settings are identical either way (everything
358 * off), so the honest record is the one that does not claim a
359 * cache: conflict-safe is what the site actually got.
360 */
361 $profile = Settings::PROFILE_CONFLICT_SAFE;
362 update_option( 'xspeed_install_profile', $profile, false );
363 }
364 }
365
366 /*
367 * Read the claim BEFORE spending it. consume_installed_by() records
368 * the installer only for a FRESH install — on a re-activation over
369 * settings that are already there it deletes the arming option and
370 * keeps nothing — so asking again afterwards answered "the user did
371 * it" about an install a host had just claimed, and the wizard opened
372 * over the host's own flow. The claim decides who to tell and whether
373 * to open the wizard; whether it is worth RECORDING is a separate
374 * question, and only the recording depends on the install being fresh.
375 */
376 $installed_by = Settings::installed_by();
377
378 // Spend the arming option now the profile is settled. It changes what
379 // activation does, so it may not survive into the next one.
380 Settings::consume_installed_by( $profile );
381
382 // Caching is otherwise only ENABLED from the admin UI — see
383 // Cache::toggle() and Rest_Api::toggle_cache(). A fresh install
384 // therefore gets no drop-in and no wp-config.php edit here:
385 // cache_enabled is unset, so the call below is a no-op.
386 //
387 // It is NOT a no-op during an upgrade. WordPress runs an update as
388 // deactivate → wipe files → install → activate, which deletes
389 // advanced-cache.php while cache_enabled stays true. Restoring it
390 // here closes the window in which the site silently serves uncached
391 // (auto_heal() alone only fires on the next wp-admin page load).
392 Cache::restore_dropin_if_enabled();
393
394 /*
395 * First-run wizard: flag a one-time redirect for the activating user.
396 * Suppressed for bulk activations / already-completed sites in
397 * Onboarding::maybe_redirect() — and here for an install another plugin
398 * performed, which has an onboarding flow of its own. The install runs
399 * over AJAX, so our redirect would fire on that admin's NEXT page load
400 * and pull them out of the middle of the host's wizard; finishing ours
401 * would then overwrite the deliberately all-off profile they never
402 * asked to change.
403 */
404 if ( '' === $installed_by ) {
405 Onboarding::flag_redirect();
406 }
407
408 // Propagate activation to every registered Module — registered by
409 // ensure_modules_registered() at the top, not by plugins_loaded,
410 // which fired before this file was even included.
411 Module_Registry::activate_all();
412
413 /**
414 * Fires at the end of activation, once the settings profile is decided.
415 *
416 * The other half of the host-plugin contract: a plugin that installed
417 * xSpeed for the user writes `xspeed_installed_by` before activating
418 * and listens here to find out how it came up. It carries no return
419 * value and nothing branches on it — a host that ignores it changes
420 * nothing about the install.
421 *
422 * @param string $installed_by Host slug, or '' when the user did it.
423 * @param string $profile Settings::PROFILE_* — which profile a fresh
424 * install came up with, '' if not fresh.
425 */
426 do_action( 'xspeed_activated', $installed_by, $profile );
427 }
428
429 /**
430 * Restore the cache drop-in right after THIS plugin is updated.
431 *
432 * Bound to upgrader_process_complete. Bulk updates, auto-updates and
433 * host-level updaters finish without re-running activate(), so this is
434 * the only hook that repairs the drop-in before the next wp-admin page
435 * load. Narrow by design: bails unless the completed action was a
436 * plugin update whose payload actually includes xspeed.
437 *
438 * @param \WP_Upgrader $upgrader Upgrader instance (unused).
439 * @param array $hook_extra Contextual data about the update.
440 * @return void
441 */
442 public function maybe_restore_after_update( $upgrader, $hook_extra ) {
443 unset( $upgrader );
444
445 if ( ! is_array( $hook_extra ) ) {
446 return;
447 }
448 if ( ! isset( $hook_extra['type'], $hook_extra['action'] ) ) {
449 return;
450 }
451 if ( 'plugin' !== $hook_extra['type'] || 'update' !== $hook_extra['action'] ) {
452 return;
453 }
454
455 // Single update uses 'plugin'; bulk uses 'plugins'.
456 $updated = array();
457 if ( isset( $hook_extra['plugins'] ) && is_array( $hook_extra['plugins'] ) ) {
458 $updated = $hook_extra['plugins'];
459 } elseif ( isset( $hook_extra['plugin'] ) && is_string( $hook_extra['plugin'] ) ) {
460 $updated = array( $hook_extra['plugin'] );
461 }
462
463 $ours = plugin_basename( XSPEED_FILE );
464 if ( ! in_array( $ours, $updated, true ) ) {
465 return;
466 }
467
468 Cache::restore_dropin_if_enabled();
469 }
470
471 public static function deactivate() {
472 // Drop-in + WP_CACHE constant are NOT touched here. WordPress
473 // upgrades run as deactivate → wipe files → install → activate,
474 // so removing those artifacts on every deactivate would silently
475 // disable caching after each plugin update. uninstall.php
476 // handles full teardown when the user actually removes the
477 // plugin; auto_heal() restores state on the next admin_init if
478 // the drop-in or WP_CACHE went missing for any other reason.
479 Cache::purge_all();
480 Minifier::purge_minified();
481 Gzip::apply( false );
482
483 Module_Registry::deactivate_all();
484 }
485 }
486