Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.88% covered (success)
96.88%
62 / 64
80.00% covered (warning)
80.00%
8 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
96.88% covered (success)
96.88%
62 / 64
80.00% covered (warning)
80.00%
8 / 10
24
0.00% covered (danger)
0.00%
0 / 1
 init
97.06% covered (success)
97.06%
33 / 34
0.00% covered (danger)
0.00%
0 / 1
9
 register_write_hooks
100.00% covered (success)
100.00%
3 / 3
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_gated
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_upsell_url
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
5
 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\Current_Plan;
12use Automattic\Jetpack\Modules;
13use Automattic\Jetpack\Status;
14use Automattic\Jetpack\Status\Host;
15
16/**
17 * Boots the package and carries its cross-plugin contract:
18 * the script-data key, and the option names / visibility reads other plugins consume.
19 */
20class Initializer {
21
22    /**
23     * Jetpack SEO package version.
24     *
25     * @var string
26     */
27    const PACKAGE_VERSION = '0.12.0';
28
29    /**
30     * Key under `window.JetpackScriptData` the React app reads its state from
31     * (`window.JetpackScriptData.seo`). Must match the JS-side reader in
32     * `_inc/data/get-overview.ts`.
33     */
34    const SCRIPT_DATA_KEY = 'seo';
35
36    /**
37     * Option recording that the user has deliberately turned the site's sitemap OFF,
38     * so WordPress core's own sitemap should be suppressed too ("off" means no sitemap
39     * at all, not a fallback to `/wp-sitemap.xml`).
40     *
41     * Set when the sitemaps module is switched off and cleared when it's switched on
42     * (see {@see self::flag_sitemap_user_disabled()} / {@see self::clear_sitemap_user_disabled()}),
43     * so it captures a deliberate off — a *transition* — rather than the ambient
44     * off-state. A site that simply never enabled the sitemap never fires the toggle,
45     * so the flag stays absent and its existing (e.g. WordPress-native) sitemap is left
46     * untouched.
47     *
48     * @var string
49     */
50    const SUPPRESS_WP_SITEMAP_OPTION = 'jetpack_seo_suppress_wp_sitemap';
51
52    /**
53     * Option recording whether the Jetpack SEO surface is discoverable on this site.
54     *
55     * Gates whether the SEO admin menu registers on self-hosted sites. Seeded once by the
56     * Jetpack plugin on install/upgrade: fresh installs default to visible, existing
57     * installs default to hidden and opt in via the legacy Traffic page or My Jetpack.
58     * WordPress.com (Simple + Atomic) bypasses this option entirely and is always visible.
59     * Absent until seeded, in which case self-hosted defaults to hidden (the non-disruptive
60     * default). See {@see Surface_Visibility::is_visible()}.
61     *
62     * Replaces `jetpack_seo_surface_visible`, which was seeded before the self-hosted rollout and
63     * marked every install since as fresh; a new key makes every site re-seed once on upgrade.
64     *
65     * @var string
66     */
67    const VISIBILITY_OPTION = 'jetpack_seo_surface_visible_v2';
68
69    /**
70     * Whether the package has been initialized.
71     *
72     * @var bool
73     */
74    private static $initialized = false;
75
76    /**
77     * Initialize the package.
78     *
79     * Called from the Jetpack plugin's `late_initialization()` hook.
80     *
81     * @return void
82     */
83    public static function init() {
84        if ( self::$initialized ) {
85            return;
86        }
87        self::$initialized = true;
88
89        if ( ! self::is_available() ) {
90            return;
91        }
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        // The settings surface only comes online once SEO tools are active — there's
168        // nothing to configure while the module is off, so we don't register its REST
169        // endpoints until then. Everything the dashboard saves is exposed to WordPress
170        // core's `/wp/v2/settings` endpoint, which exists on every platform the package
171        // runs on and capability-gates writes itself; module activation, the one thing
172        // `register_setting()` can't express, has its own package-owned route.
173        if ( self::is_seo_tools_module_active() ) {
174            // Front-end JSON-LD schema output and author profile schema fields.
175            // Intentionally NOT gated: every site keeps emitting its structured data —
176            // a plan-gated site loses the schema *settings* card (a paid control), but
177            // stripping the schema its pages already carry would hurt SEO it has today.
178            // (Finer per-type gating — e.g. sitewide LocalBusiness to paid plans on
179            // self-hosted — is a separate follow-up, tracked in the schema project.)
180            Share_Image::init();
181            Schema_Builder::init();
182            Author_Schema_Node::init();
183
184            // Paid front-end output. A plan-gated WordPress.com site has these controls
185            // hidden from its dashboard, so it must not keep emitting their output either —
186            // otherwise it would still serve /llms.txt, AI-crawler robots.txt directives and
187            // Simple's archive canonical tags it doesn't qualify for. Self-hosted is never gated.
188            if ( ! self::is_gated() ) {
189                Canonical_Urls::init();
190                // The /llms.txt handler. Self-hooks a front-end action, so it no-ops off
191                // the front end and stays behind the same gates as the schema above.
192                Llms_Txt::init();
193                // robots.txt directives for blocked AI crawlers. Self-hooks the
194                // `robots_txt` filter, so it stays inert off the front end.
195                Ai_Crawlers::init();
196            }
197
198            // On `rest_api_init` rather than here: which option the front page description
199            // is stored in depends on `jetpack_disable_seo_tools`, which a conflicting SEO
200            // plugin can add from anywhere up to the end of `init`. Priority 5 is after all
201            // of those and before core builds the settings route at 99.
202            add_action( 'rest_api_init', array( Dashboard_Data::class, 'register_rest_settings' ), 5 );
203            // Package-owned route for the three settings whose write switches a Jetpack module.
204            add_action( 'rest_api_init', array( Dashboard_Data::class, 'register_module_routes' ) );
205            // Package-owned route for the site-level Schema settings (see the controller).
206            add_action( 'rest_api_init', array( Schema_Settings_Controller::class, 'register_routes' ) );
207        }
208
209        /**
210         * Fires after the Jetpack SEO package is initialized.
211         *
212         * @since 0.1.0
213         */
214        do_action( 'jetpack_seo_init' );
215    }
216
217    /**
218     * Hook what any request that saves content needs: the page fields the SEO page saves, and
219     * clearing the Overview counts and the stored llms.txt. WordPress.com calls this on its API
220     * requests, which skip init().
221     *
222     * @return void
223     */
224    public static function register_write_hooks() {
225        Content_Coverage::register_invalidation();
226        Llms_Txt::register_always_include();
227        Llms_Txt::register_invalidation();
228    }
229
230    /**
231     * Whether the Jetpack SEO product is available on this site.
232     *
233     * Availability is independent of plan refreshes and connection state.
234     *
235     * @return bool
236     */
237    public static function is_available() {
238        return ! ( new Host() )->is_vip_site();
239    }
240
241    /**
242     * Whether the Jetpack SEO surface should be discoverable (admin menu registered).
243     *
244     * @return bool
245     */
246    public static function is_seo_surface_visible() {
247        return Surface_Visibility::is_visible();
248    }
249
250    /**
251     * Whether to offer an existing install the chance to opt into the new SEO experience.
252     *
253     * @return bool
254     */
255    public static function is_optin_available() {
256        return Surface_Visibility::is_optin_available();
257    }
258
259    /**
260     * Whether the SEO dashboard is plan-gated for this site.
261     *
262     * Gating applies only on WordPress.com (Simple + Atomic): `advanced-seo` is in the
263     * FREE plan's supports list, so `Current_Plan::supports( 'advanced-seo' )` returns
264     * true on self-hosted (never gated) and hijacks to `wpcom_site_has_feature()` on
265     * WordPress.com, where it's false below the Premium plan. Mirrors the AI SEO
266     * Enhancer's plan check in {@see Dashboard_Data::get_geo_data()}.
267     *
268     * Public because {@see Admin_Page::inject_script_data()} reads it to build the
269     * dashboard's gating payload, and {@see self::init()} uses it to decide whether the
270     * paid front-end output registers at all.
271     *
272     * @return bool
273     */
274    public static function is_gated() {
275        return ( new Host() )->is_wpcom_platform()
276            && ! Current_Plan::supports( 'advanced-seo' );
277    }
278
279    /**
280     * Return the Premium checkout URL, or an empty string when upgrades are unavailable.
281     *
282     * @return string
283     */
284    public static function get_upsell_url() {
285        $host = new Host();
286        if ( $host->is_p2_site() ) {
287            return '';
288        }
289
290        $plan       = $host->is_wpcom_simple() && class_exists( '\WPCOM_Store_API' )
291            ? \WPCOM_Store_API::get_current_plan( get_current_blog_id() )
292            : Current_Plan::get();
293        $term       = substr( $plan['product_slug'] ?? '', -3 );
294        $product    = in_array( $term, array( '-2y', '-3y' ), true ) ? 'value_bundle' . $term : 'value_bundle';
295        $site_slug  = ( new Status() )->get_site_suffix();
296        $return_url = rawurlencode( Admin_Page::get_url() );
297
298        return add_query_arg(
299            array(
300                'redirect_to'     => $return_url,
301                'checkoutBackUrl' => $return_url,
302            ),
303            sprintf( 'https://wordpress.com/checkout/%s/%s', $site_slug, $product )
304        );
305    }
306
307    /**
308     * Whether the `seo-tools` Jetpack module is currently active.
309     *
310     * @return bool
311     */
312    private static function is_seo_tools_module_active() {
313        if ( ! class_exists( 'Automattic\\Jetpack\\Modules' ) ) {
314            return false;
315        }
316        return ( new Modules() )->is_active( 'seo-tools' );
317    }
318
319    /**
320     * Record that the user has turned the sitemap off, so WordPress core's own sitemap
321     * is suppressed too. Hooked to the sitemaps module's deactivation, which fires only
322     * on a real toggle from a surface (the SEO Settings tab, the legacy Traffic page, or
323     * WP-CLI) — not wpcomsh's private-site suppression, which is a filter on the
324     * active-modules read rather than a deactivation.
325     *
326     * @return void
327     */
328    public static function flag_sitemap_user_disabled() {
329        update_option( self::SUPPRESS_WP_SITEMAP_OPTION, true );
330    }
331
332    /**
333     * Clear the deliberate-off flag when the sitemap is turned back on — the Jetpack
334     * sitemaps module then serves `/sitemap.xml` and suppresses core's duplicate itself.
335     *
336     * @return void
337     */
338    public static function clear_sitemap_user_disabled() {
339        delete_option( self::SUPPRESS_WP_SITEMAP_OPTION );
340    }
341}