Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.00% covered (success)
96.00%
48 / 50
75.00% covered (warning)
75.00%
6 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
96.00% covered (success)
96.00%
48 / 50
75.00% covered (warning)
75.00%
6 / 8
16
0.00% covered (danger)
0.00%
0 / 1
 init
97.30% covered (success)
97.30%
36 / 37
0.00% covered (danger)
0.00%
0 / 1
8
 register_write_hooks
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 is_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_seo_surface_visible
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_optin_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_seo_tools_module_active
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 flag_sitemap_user_disabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 clear_sitemap_user_disabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Bootstrap the Jetpack SEO dashboard and its discoverability cohort.
4 *
5 * @package automattic/jetpack-seo-package
6 */
7
8namespace Automattic\Jetpack\SEO;
9
10use Automattic\Jetpack\Admin_UI\Admin_Shell;
11use Automattic\Jetpack\Modules;
12use Automattic\Jetpack\Status\Host;
13
14/**
15 * Boots the package and carries its cross-plugin contract:
16 * the script-data key, and the option names / visibility reads other plugins consume.
17 */
18class Initializer {
19
20    /**
21     * Jetpack SEO package version.
22     *
23     * @var string
24     */
25    const PACKAGE_VERSION = '0.12.0';
26
27    /**
28     * Key under `window.JetpackScriptData` the React app reads its state from
29     * (`window.JetpackScriptData.seo`). Must match the JS-side reader in
30     * `_inc/data/get-overview.ts`.
31     */
32    const SCRIPT_DATA_KEY = 'seo';
33
34    /**
35     * Option recording that the user has deliberately turned the site's sitemap OFF,
36     * so WordPress core's own sitemap should be suppressed too ("off" means no sitemap
37     * at all, not a fallback to `/wp-sitemap.xml`).
38     *
39     * Set when the sitemaps module is switched off and cleared when it's switched on
40     * (see {@see self::flag_sitemap_user_disabled()} / {@see self::clear_sitemap_user_disabled()}),
41     * so it captures a deliberate off — a *transition* — rather than the ambient
42     * off-state. A site that simply never enabled the sitemap never fires the toggle,
43     * so the flag stays absent and its existing (e.g. WordPress-native) sitemap is left
44     * untouched.
45     *
46     * @var string
47     */
48    const SUPPRESS_WP_SITEMAP_OPTION = 'jetpack_seo_suppress_wp_sitemap';
49
50    /**
51     * Option recording whether the Jetpack SEO surface is discoverable on this site.
52     *
53     * Gates whether the SEO admin menu registers on self-hosted sites. Seeded once by the
54     * Jetpack plugin on install/upgrade: fresh installs default to visible, existing
55     * installs default to hidden and opt in via the legacy Traffic page or My Jetpack.
56     * WordPress.com (Simple + Atomic) bypasses this option entirely and is always visible.
57     * Absent until seeded, in which case self-hosted defaults to hidden (the non-disruptive
58     * default). See {@see Surface_Visibility::is_visible()}.
59     *
60     * Replaces `jetpack_seo_surface_visible`, which was seeded before the self-hosted rollout and
61     * marked every install since as fresh; a new key makes every site re-seed once on upgrade.
62     *
63     * @var string
64     */
65    const VISIBILITY_OPTION = 'jetpack_seo_surface_visible_v2';
66
67    /**
68     * Whether the package has been initialized.
69     *
70     * @var bool
71     */
72    private static $initialized = false;
73
74    /**
75     * Initialize the package.
76     *
77     * Called from the Jetpack plugin's `late_initialization()` hook.
78     *
79     * @return void
80     */
81    public static function init() {
82        if ( self::$initialized ) {
83            return;
84        }
85        self::$initialized = true;
86
87        if ( ! self::is_available() ) {
88            return;
89        }
90
91        Llms_Txt::register_redirect_filters();
92
93        // Before anything can read the AI crawler choices.
94        Ai_Crawlers::register_legacy_migration();
95
96        // The opt-in endpoint must be reachable even before the surface is visible, so
97        // existing self-hosted installs can switch to the new experience from the legacy
98        // Traffic page or My Jetpack (JETPACK-1700). Registered ahead of the cohort gate.
99        add_action( 'rest_api_init', array( Surface_Visibility::class, 'register_optin_route' ) );
100
101        // Hidden self-hosted installs need the opt-in signal before the cohort gate.
102        add_filter( 'jetpack_admin_js_script_data', array( Surface_Visibility::class, 'inject_optin_availability' ) );
103
104        // Sitemap output is a front-end concern tied to the SEO feature itself, not to
105        // whether the admin dashboard is visible — so register it here, ahead of the
106        // cohort gate. This keeps the deliberate-off behavior consistent in the two
107        // edges the surface gate would otherwise break: a site that turns the sitemap
108        // off while the dashboard is still hidden (an existing self-hosted install that
109        // hasn't opted in), and a flag set while the dashboard was visible that must
110        // stay honored if the dashboard is later hidden.
111        //
112        // Maintain the deliberate-off flag as the sitemap is toggled: these fire only on
113        // a genuine module toggle (not wpcomsh's private-site suppression, which is a
114        // filter, not a deactivation), and are registered before the toggle's REST write.
115        add_action( 'jetpack_deactivate_module_sitemaps', array( __CLASS__, 'flag_sitemap_user_disabled' ) );
116        add_action( 'jetpack_activate_module_sitemaps', array( __CLASS__, 'clear_sitemap_user_disabled' ) );
117
118        // When the user has deliberately turned the sitemap off, suppress WordPress
119        // core's own sitemap too — otherwise "off" silently falls back to core's
120        // `/wp-sitemap.xml` (and its `/sitemap.xml` → `/wp-sitemap.xml` redirect). Keyed
121        // on the deliberate-off flag, NOT the ambient off-state, so a site that never
122        // enabled the sitemap keeps whatever sitemap it already had. Runs on
123        // `plugins_loaded`, before core registers its sitemap server on `init`, so the
124        // filter is in place; with core sitemaps disabled, `/sitemap.xml` and
125        // `/wp-sitemap.xml` both return a proper 404. (When the sitemap is ON, the
126        // Jetpack sitemaps module already disables core's duplicate.)
127        if ( get_option( self::SUPPRESS_WP_SITEMAP_OPTION, false ) ) {
128            add_filter( 'wp_sitemaps_enabled', '__return_false' );
129        }
130
131        // Discoverability cohort gate: the SEO surface is auto-discoverable for fresh
132        // installs and all WordPress.com sites; existing self-hosted installs opt in via
133        // the legacy Traffic page or My Jetpack (JETPACK-1700). Until it's visible we
134        // register nothing else here and let those opt-in surfaces drive discovery.
135        if ( ! self::is_seo_surface_visible() ) {
136            return;
137        }
138
139        // Each SEO module's configure URL defaults to Jetpack › Settings filtered to the
140        // module. Once the surface is visible that view only points here, so link here.
141        foreach ( array( 'seo-tools', 'verification-tools', 'sitemaps' ) as $module ) {
142            add_filter( 'jetpack_module_configuration_url_' . $module, array( Admin_Page::class, 'get_url' ) );
143        }
144
145        // The page registers whenever the surface is visible, even with `seo-tools` off, so
146        // a saved link still offers "Enable SEO tools"; the menu item hides with the module.
147        //
148        // Priority 1: load the wp-build bundle (and define its render function)
149        // before `add_menu_item()` runs at the default priority and needs it.
150        add_action( 'admin_menu', array( Admin_Page::class, 'maybe_load_wp_build' ), 1 );
151        add_action( 'admin_menu', array( Admin_Page::class, 'add_menu_item' ), 10 );
152
153        if ( class_exists( Admin_Shell::class ) ) {
154            add_filter( 'jetpack_admin_shell_members', array( Admin_Page::class, 'add_admin_shell_member' ) );
155        }
156
157        // Read-only REST routes the dashboard hydrates its initial state from. Preloaded
158        // into the page (see Admin_Page::inject_script_data) so a normal load resolves
159        // them with no request, and fetched by the app when that preload is missing or
160        // stale — so the dashboard recovers its data instead of dead-ending. Registered
161        // whenever the surface is visible (independent of the seo-tools module, like the
162        // Overview).
163        add_action( 'rest_api_init', array( Dashboard_Data::class, 'register_rest_reads' ) );
164
165        self::register_write_hooks();
166
167        Indexnow::init();
168
169        Indexnow_Client::init();
170        add_action( 'rest_api_init', array( Data_Sharing::class, 'register_routes' ) );
171
172        // The settings surface only comes online once SEO tools are active — there's
173        // nothing to configure while the module is off, so we don't register its REST
174        // endpoints until then. Everything the dashboard saves is exposed to WordPress
175        // core's `/wp/v2/settings` endpoint, which exists on every platform the package
176        // runs on and capability-gates writes itself; module activation, the one thing
177        // `register_setting()` can't express, has its own package-owned route.
178        if ( self::is_seo_tools_module_active() ) {
179            Share_Image::init();
180            Schema_Builder::init();
181            Author_Schema_Node::init();
182            Canonical_Urls::init();
183            Llms_Txt::init();
184            Ai_Crawlers::init();
185
186            // On `rest_api_init` rather than here: which option the front page description
187            // is stored in depends on `jetpack_disable_seo_tools`, which a conflicting SEO
188            // plugin can add from anywhere up to the end of `init`. Priority 5 is after all
189            // of those and before core builds the settings route at 99.
190            add_action( 'rest_api_init', array( Dashboard_Data::class, 'register_rest_settings' ), 5 );
191            // Package-owned route for the three settings whose write switches a Jetpack module.
192            add_action( 'rest_api_init', array( Dashboard_Data::class, 'register_module_routes' ) );
193            // Package-owned route for the site-level Schema settings (see the controller).
194            add_action( 'rest_api_init', array( Schema_Settings_Controller::class, 'register_routes' ) );
195        }
196
197        /**
198         * Fires after the Jetpack SEO package is initialized.
199         *
200         * @since 0.1.0
201         */
202        do_action( 'jetpack_seo_init' );
203    }
204
205    /**
206     * Register content-write hooks for ordinary and centralized API requests.
207     * Centralized API requests select their site after plugins_loaded and skip init().
208     *
209     * @return void
210     */
211    public static function register_write_hooks() {
212        Indexnow_Events::init();
213        Indexnow_Queue::init();
214        Content_Coverage::register_invalidation();
215        Llms_Txt::register_always_include();
216        Llms_Txt::register_invalidation();
217    }
218
219    /**
220     * Whether the Jetpack SEO product is available on this site.
221     *
222     * Availability is independent of plan refreshes and connection state.
223     *
224     * @return bool
225     */
226    public static function is_available() {
227        return ! ( new Host() )->is_vip_site();
228    }
229
230    /**
231     * Whether the Jetpack SEO surface should be discoverable (admin menu registered).
232     *
233     * @return bool
234     */
235    public static function is_seo_surface_visible() {
236        return Surface_Visibility::is_visible();
237    }
238
239    /**
240     * Whether to offer an existing install the chance to opt into the new SEO experience.
241     *
242     * @return bool
243     */
244    public static function is_optin_available() {
245        return Surface_Visibility::is_optin_available();
246    }
247
248    /**
249     * Whether the `seo-tools` Jetpack module is currently active.
250     *
251     * @return bool
252     */
253    private static function is_seo_tools_module_active() {
254        if ( ! class_exists( 'Automattic\\Jetpack\\Modules' ) ) {
255            return false;
256        }
257        return ( new Modules() )->is_active( 'seo-tools' );
258    }
259
260    /**
261     * Record that the user has turned the sitemap off, so WordPress core's own sitemap
262     * is suppressed too. Hooked to the sitemaps module's deactivation, which fires only
263     * on a real toggle from a surface (the SEO Settings tab, the legacy Traffic page, or
264     * WP-CLI) — not wpcomsh's private-site suppression, which is a filter on the
265     * active-modules read rather than a deactivation.
266     *
267     * @return void
268     */
269    public static function flag_sitemap_user_disabled() {
270        update_option( self::SUPPRESS_WP_SITEMAP_OPTION, true );
271    }
272
273    /**
274     * Clear the deliberate-off flag when the sitemap is turned back on — the Jetpack
275     * sitemaps module then serves `/sitemap.xml` and suppresses core's duplicate itself.
276     *
277     * @return void
278     */
279    public static function clear_sitemap_user_disabled() {
280        delete_option( self::SUPPRESS_WP_SITEMAP_OPTION );
281    }
282}