Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
58.10% covered (warning)
58.10%
147 / 253
31.03% covered (danger)
31.03%
9 / 29
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
58.10% covered (warning)
58.10%
147 / 253
31.03% covered (danger)
31.03%
9 / 29
488.69
0.00% covered (danger)
0.00%
0 / 1
 init
83.33% covered (warning)
83.33%
15 / 18
0.00% covered (danger)
0.00%
0 / 1
5.12
 add_menu_item
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 maybe_load_wp_build
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 load_wp_build
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 alias_screen_id_for_wp_build
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 inject_script_data
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 inject_optin_availability
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 render_fallback
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_seo_admin_request
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 is_seo_tools_module_active
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 is_sitemap_enabled
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_reachable_sitemap_url
63.64% covered (warning)
63.64%
7 / 11
0.00% covered (danger)
0.00%
0 / 1
11.08
 is_canonical_enabled
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 is_seo_surface_visible
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_optin_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_overview_data
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
3
 get_content_coverage
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 count_published_with_meta
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
2
 get_site_data
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 register_rest_settings
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 register_optin_route
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
 handle_optin
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 rest_reads
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 rest_read_paths
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 register_rest_reads
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 reads_permission_check
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_settings_data
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
9
 get_google_verify_data
80.00% covered (warning)
80.00%
8 / 10
0.00% covered (danger)
0.00%
0 / 1
3.07
 get_ai_data
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * Jetpack SEO — the visibility command center for WordPress sites.
4 *
5 * Registers the `admin.php?page=jetpack-seo` screen via Admin_Menu so it is
6 * reachable on self-hosted, Atomic/WoW, and Simple sites alike, and loads the
7 * `@wordpress/build` (wp-build) dashboard bundle that renders it.
8 *
9 * @package automattic/jetpack-seo-package
10 */
11
12namespace Automattic\Jetpack\SEO;
13
14use Automattic\Jetpack\Admin_UI\Admin_Menu;
15use Automattic\Jetpack\Modules;
16use Automattic\Jetpack\Status\Host;
17use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
18use Jetpack_SEO_Titles;
19use Jetpack_SEO_Utils;
20use Jetpack_Sitemap_Librarian;
21
22/**
23 * The main Initializer class. Registers the admin menu and loads the wp-build
24 * dashboard, bootstrapping the React app's initial state onto the page.
25 */
26class Initializer {
27
28    /**
29     * Jetpack SEO package version.
30     *
31     * @var string
32     */
33    const PACKAGE_VERSION = '0.4.0';
34
35    /**
36     * Filter name that gates the entire Jetpack SEO surface.
37     *
38     * When this filter returns true, the package registers its admin menu and
39     * loads the wp-build dashboard. Default false before release - when the
40     * filter is off the package registers no admin menu and no assets, and
41     * changes nothing about the existing Jetpack UI.
42     *
43     * @var string
44     */
45    const FEATURE_FILTER = 'rsm_jetpack_seo';
46
47    /**
48     * URL-facing menu slug (`admin.php?page=jetpack-seo`).
49     */
50    const MENU_SLUG = 'jetpack-seo';
51
52    /**
53     * Slug emitted by `@wordpress/build` (`wpPlugin.pages[0]`). wp-build's
54     * auto-generated enqueue callback only fires when `$screen->id` matches
55     * this value, so we alias the screen id to it via `current_screen` without
56     * changing the user-facing URL.
57     */
58    const WP_BUILD_SLUG = 'jetpack-seo-dashboard';
59
60    /**
61     * Render function generated by `@wordpress/build` into
62     * `build/pages/jetpack-seo-dashboard/page-wp-admin.php`. Naming convention:
63     * `{wpPlugin.name}_{page-with-underscores}_wp_admin_render_page`.
64     */
65    const WP_BUILD_RENDER_FN = 'jetpack_seo_jetpack_seo_dashboard_wp_admin_render_page';
66
67    /**
68     * Key under `window.JetpackScriptData` the React app reads its state from
69     * (`window.JetpackScriptData.seo`). Must match the JS-side reader in
70     * `_inc/data/get-overview.ts`.
71     */
72    const SCRIPT_DATA_KEY = 'seo';
73
74    /**
75     * Post-meta keys mirrored from `Jetpack_SEO_Posts` (in plugins/jetpack).
76     * Duplicated here as literals on purpose: that plugin class is NOT reliably
77     * loaded in this package's admin context (the `Jetpack_SEO_Utils`
78     * `class_exists` guard in `get_overview_data()` is there for the same
79     * reason), so referencing its constants would fatal. Content-coverage
80     * counting only needs the key strings, which are stable.
81     */
82    const META_DESCRIPTION = 'advanced_seo_description';
83    const META_SCHEMA_TYPE = 'jetpack_seo_schema_type';
84    const META_TITLE       = 'jetpack_seo_html_title';
85    const META_NOINDEX     = 'jetpack_seo_noindex';
86
87    /**
88     * Option recording whether sitemap generation is enabled.
89     *
90     * Read in place of the standalone `sitemaps` module's active state. Module-active
91     * state is filtered against the modules present on disk, so once that module is
92     * removed it would read as inactive even for sites that had it on. A one-time
93     * migration in the Jetpack plugin seeds this option from the site's existing module
94     * state and keeps it in sync while the legacy module still exists. See
95     * `Jetpack::migrate_sitemaps_module_to_seo_option()`.
96     *
97     * @var string
98     */
99    const SITEMAP_ENABLED_OPTION = 'jetpack_seo_sitemap_enabled';
100
101    /**
102     * Option recording whether canonical URLs are enabled.
103     *
104     * Read in place of the standalone `canonical-urls` module's active state. Module-active
105     * state is filtered against the modules present on disk, so once that module is
106     * removed it would read as inactive even for sites that had it on. A one-time
107     * migration in the Jetpack plugin seeds this option from the site's existing module
108     * state and keeps it in sync while the legacy module still exists. See
109     * `Jetpack::migrate_canonical_urls_module_to_seo_option()`.
110     *
111     * @var string
112     */
113    const CANONICAL_ENABLED_OPTION = 'jetpack_seo_canonical_urls_enabled';
114
115    /**
116     * Option recording whether the Jetpack SEO surface is discoverable on this site.
117     *
118     * Gates whether the SEO admin menu registers on self-hosted sites. Seeded once by the
119     * Jetpack plugin on install/upgrade: fresh installs default to visible, existing
120     * installs default to hidden and opt in via the legacy Traffic page or My Jetpack.
121     * WordPress.com (Simple + Atomic) bypasses this option entirely and is always visible.
122     * Absent until seeded, in which case self-hosted defaults to hidden (the non-disruptive
123     * default). See {@see self::is_seo_surface_visible()}.
124     *
125     * @var string
126     */
127    const VISIBILITY_OPTION = 'jetpack_seo_surface_visible';
128
129    /**
130     * Whether the package has been initialized.
131     *
132     * @var bool
133     */
134    private static $initialized = false;
135
136    /**
137     * Initialize the package.
138     *
139     * Called from the Jetpack plugin's `late_initialization()` hook.
140     *
141     * @return void
142     */
143    public static function init() {
144        if ( self::$initialized ) {
145            return;
146        }
147        self::$initialized = true;
148
149        // Gate the entire SEO surface behind the feature flag.
150        if ( ! (bool) apply_filters( self::FEATURE_FILTER, false ) ) {
151            return;
152        }
153
154        // The opt-in endpoint must be reachable even before the surface is visible, so
155        // existing self-hosted installs can switch to the new experience from the legacy
156        // Traffic page or My Jetpack (JETPACK-1700). Registered ahead of the cohort gate.
157        add_action( 'rest_api_init', array( __CLASS__, 'register_optin_route' ) );
158
159        // Expose opt-in availability to other admin surfaces (the legacy Traffic-page
160        // banner reads it via `@automattic/jetpack-script-data`). Hooked here — after the
161        // feature flag, before the cohort gate — so a still-hidden install gets the signal.
162        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_optin_availability' ) );
163
164        // Discoverability cohort gate: the SEO surface is auto-discoverable for fresh
165        // installs and all WordPress.com sites; existing self-hosted installs opt in via
166        // the legacy Traffic page or My Jetpack (JETPACK-1700). Until it's visible we
167        // register nothing else here and let those opt-in surfaces drive discovery.
168        if ( ! self::is_seo_surface_visible() ) {
169            return;
170        }
171
172        // The admin menu and app shell register whenever the surface is visible, even
173        // when the `seo-tools` module is inactive, so SEO stays discoverable and can be
174        // turned on from within the page itself (JETPACK-1700). When the module is off,
175        // the Overview renders only its "enable SEO tools" affordance.
176        //
177        // Priority 1: load the wp-build bundle (and define its render function)
178        // before `add_menu_item()` runs at the default priority and needs it.
179        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
180        add_action( 'admin_menu', array( __CLASS__, 'add_menu_item' ), 10 );
181
182        // Read-only REST routes the dashboard hydrates its initial state from. Preloaded
183        // into the page (see inject_script_data) so a normal load resolves them with no
184        // request, and fetched by the app when that preload is missing or stale — so the
185        // dashboard recovers its data instead of dead-ending. Registered whenever the
186        // surface is visible (independent of the seo-tools module, like the Overview).
187        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_reads' ) );
188
189        // The settings surface only comes online once SEO tools are active — there's
190        // nothing to configure while the module is off, so we don't register its REST
191        // endpoints until then. Expose the core `blog_public` option to the REST settings
192        // endpoint so the Settings tab can save search-engine visibility via
193        // `/wp/v2/settings` (the Jetpack settings endpoint only accepts Jetpack options).
194        // Writes are still capability-gated by the core settings controller.
195        if ( self::is_seo_tools_module_active() ) {
196            // Front-end JSON-LD schema output and author profile schema fields.
197            Schema_Builder::init();
198            Author_Schema_Node::init();
199            add_action( 'rest_api_init', array( __CLASS__, 'register_rest_settings' ) );
200            // Package-owned route for the site-level Schema settings (see the controller).
201            add_action( 'rest_api_init', array( Schema_Settings_Controller::class, 'register_routes' ) );
202        }
203
204        /**
205         * Fires after the Jetpack SEO package is initialized.
206         *
207         * @since 0.1.0
208         */
209        do_action( 'jetpack_seo_init' );
210    }
211
212    /**
213     * Register the admin menu item.
214     *
215     * Uses Admin_Menu so the page is reachable on wp-admin across all site
216     * types. The render callback is wp-build's generated render function when
217     * the bundle is loaded (i.e. on the SEO page itself, after
218     * `maybe_load_wp_build()` ran at priority 1); otherwise it falls back to a
219     * bare mount node so the page never fatals on an unbuilt checkout.
220     *
221     * @return void
222     */
223    public static function add_menu_item() {
224        $callback = function_exists( self::WP_BUILD_RENDER_FN )
225            ? self::WP_BUILD_RENDER_FN
226            : array( __CLASS__, 'render_fallback' );
227
228        Admin_Menu::add_menu(
229            'SEO',
230            'SEO',
231            'manage_options',
232            self::MENU_SLUG,
233            $callback,
234            2
235        );
236    }
237
238    /**
239     * On the SEO admin page, load the wp-build bundle, alias the screen id so
240     * wp-build enqueues its assets, and bootstrap the app's initial state.
241     *
242     * Hooked at `admin_menu` priority 1 so polyfills register and the render
243     * function is defined before `add_menu_item()` runs at priority 10.
244     *
245     * @return void
246     */
247    public static function maybe_load_wp_build() {
248        if ( ! self::is_seo_admin_request() ) {
249            return;
250        }
251
252        self::load_wp_build();
253        add_action( 'current_screen', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
254        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_script_data' ) );
255    }
256
257    /**
258     * Load wp-build's generated registration file and register the polyfills
259     * the bundle depends on. No-op on a fresh checkout before `pnpm build`, in
260     * which case `add_menu_item()` falls back to {@see self::render_fallback()}.
261     *
262     * @return void
263     */
264    private static function load_wp_build() {
265        $build_index = dirname( __DIR__ ) . '/build/build.php';
266
267        if ( ! file_exists( $build_index ) ) {
268            return;
269        }
270
271        require_once $build_index;
272
273        WP_Build_Polyfills::register(
274            'jetpack-seo',
275            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
276        );
277    }
278
279    /**
280     * Alias the current screen id to wp-build's expected slug so its
281     * auto-generated enqueue callback fires for our user-facing page.
282     *
283     * @param \WP_Screen|null $screen The current screen object (passed by WP).
284     * @return void
285     */
286    public static function alias_screen_id_for_wp_build( $screen ) {
287        if ( ! is_object( $screen ) ) {
288            return;
289        }
290
291        $screen->id = self::WP_BUILD_SLUG;
292    }
293
294    /**
295     * Bootstrap the React app's initial state onto `window.JetpackScriptData.seo`.
296     *
297     * Because wp-build pages load as ES modules, `wp_localize_script` can't
298     * attach data to them; the shared `jetpack_admin_js_script_data` filter
299     * (printed by the Script_Data package onto the `jetpack-script-data` handle
300     * the bundle already depends on) is the supported channel. The per-tab state
301     * is provided as an apiFetch *preload* (mirrors Podcast) so the app resolves
302     * it with no request on a normal load yet can re-fetch when the preload is
303     * missing or stale, rather than dead-ending on a one-shot read.
304     *
305     * @param array $data Script data being injected onto the page.
306     * @return array
307     */
308    public static function inject_script_data( $data ) {
309        if ( ! is_array( $data ) ) {
310            $data = array();
311        }
312
313        // Preload the dashboard's REST reads into the page so the app resolves them from
314        // cache on first paint with no network request — while still being able to
315        // re-fetch if that preload is ever missing or stale. This replaces injecting the
316        // raw payloads, which the app read synchronously once and couldn't recover from
317        // when momentarily absent (the load-error dead-end). See register_rest_reads() and
318        // the client readers `_inc/data/get-preloaded.ts` + `_inc/data/use-ensure-tab-data.ts`.
319        $data[ self::SCRIPT_DATA_KEY ]['preload'] = array_reduce(
320            self::rest_read_paths(),
321            'rest_preload_api_request',
322            array()
323        );
324
325        // Small synchronous reads used outside the per-tab data stores, and not part of
326        // the load-error path.
327        $data[ self::SCRIPT_DATA_KEY ]['google_verify'] = self::get_google_verify_data();
328        $data[ self::SCRIPT_DATA_KEY ]['site']          = self::get_site_data();
329
330        return $data;
331    }
332
333    /**
334     * Expose whether this install should be offered the SEO opt-in, onto
335     * `window.JetpackScriptData.seo.optin_available` for other admin surfaces (e.g. the
336     * legacy Traffic-page banner). Only hooked when the feature flag is on, so the field is
337     * simply absent otherwise.
338     *
339     * @param array $data Script data being injected onto the page.
340     * @return array
341     */
342    public static function inject_optin_availability( $data ) {
343        if ( ! is_array( $data ) ) {
344            $data = array();
345        }
346
347        $data[ self::SCRIPT_DATA_KEY ]['optin_available'] = self::is_optin_available();
348        // Read by the legacy Traffic page to hide its SEO / Sitemaps sections once the
349        // site is on the new experience (fresh install / opted-in / WordPress.com), so the
350        // two surfaces never show at once. The legacy sections stay for self-hosted installs
351        // that haven't opted in.
352        $data[ self::SCRIPT_DATA_KEY ]['surface_visible'] = self::is_seo_surface_visible();
353
354        return $data;
355    }
356
357    /**
358     * Fallback render used when the wp-build artifact is missing (unbuilt
359     * checkout). Renders a bare wrapper so the page loads without the app.
360     *
361     * @return void
362     */
363    public static function render_fallback() {
364        echo '<div class="wrap"><h1>SEO</h1></div>';
365    }
366
367    /**
368     * Whether the current request targets the SEO admin page.
369     *
370     * @return bool
371     */
372    private static function is_seo_admin_request() {
373        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
374        if ( ! is_admin() || ! isset( $_GET['page'] ) ) {
375            return false;
376        }
377
378        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
379        return self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
380    }
381
382    /**
383     * Whether the `seo-tools` Jetpack module is currently active.
384     *
385     * @return bool
386     */
387    private static function is_seo_tools_module_active() {
388        if ( ! class_exists( 'Automattic\\Jetpack\\Modules' ) ) {
389            return false;
390        }
391        return ( new Modules() )->is_active( 'seo-tools' );
392    }
393
394    /**
395     * Whether sitemap generation is enabled.
396     *
397     * Reads the durable {@see self::SITEMAP_ENABLED_OPTION} flag. The default is only
398     * used when the option is absent (for example before the Jetpack plugin's migration
399     * has run on a freshly upgraded site), in which case it falls back to the live
400     * `sitemaps` module state so behavior is unchanged in that gap.
401     *
402     * @param Modules $modules Modules instance to read live module state from.
403     * @return bool
404     */
405    private static function is_sitemap_enabled( Modules $modules ) {
406        $enabled = get_option( self::SITEMAP_ENABLED_OPTION, null );
407
408        // Only fall back to the live module state when the durable option is absent.
409        // Passing it as get_option()'s default would evaluate it on every call, since
410        // PHP resolves function arguments eagerly even when the option exists.
411        if ( null === $enabled ) {
412            $enabled = $modules->is_active( 'sitemaps' );
413        }
414
415        return (bool) $enabled;
416    }
417
418    /**
419     * The public URL of the generated XML sitemap, or an empty string when none
420     * is currently reachable.
421     *
422     * A sitemap is only reachable when generation is enabled, the site is public
423     * (Jetpack does not load the Sitemaps module on sites that discourage search
424     * engines), and the master sitemap has actually been generated — the Jetpack
425     * plugin builds it via cron 1–15 minutes after activation, so the URL 404s
426     * until then. Callers treat an empty string as "not yet reachable" and skip
427     * linking to it.
428     *
429     * {@see Jetpack_Sitemap_Librarian} and jetpack_sitemap_uri() live in the
430     * Jetpack plugin's Sitemaps module (loaded only for an active module on a
431     * public site), so both are guarded; in the package-only context they are
432     * absent and the sitemap is reported as not reachable.
433     *
434     * @param bool $sitemap_active Whether sitemap generation is enabled.
435     * @return string The sitemap URL, or '' when not reachable.
436     */
437    private static function get_reachable_sitemap_url( $sitemap_active ) {
438        // Jetpack only serves sitemaps when generation is on and the site is public.
439        if ( ! $sitemap_active || (int) get_option( 'blog_public', 1 ) !== 1 ) {
440            return '';
441        }
442
443        // The Sitemaps module (the librarian class, the `JP_MASTER_SITEMAP_TYPE`
444        // constant, and the `jp_sitemap_filename()` / `jetpack_sitemap_uri()`
445        // helpers) all live together in plugins/jetpack and load as a unit, so this
446        // single guard covers every symbol used below.
447        if (
448            ! class_exists( 'Jetpack_Sitemap_Librarian' )
449            || ! defined( 'JP_MASTER_SITEMAP_TYPE' )
450            || ! function_exists( 'jp_sitemap_filename' )
451            || ! function_exists( 'jetpack_sitemap_uri' )
452        ) {
453            return '';
454        }
455
456        // The master sitemap is stored as a post once the cron generation run
457        // completes; until then there is nothing to link to.
458        // `jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE )` is the master file name
459        // ('sitemap.xml'); inlined so this stays one (untestable-in-package) line.
460        // @phan-suppress-next-line PhanUndeclaredFunction,PhanUndeclaredClassMethod -- guarded above; symbols live in plugins/jetpack.
461        $master = ( new Jetpack_Sitemap_Librarian() )->read_sitemap_data( jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE ), JP_MASTER_SITEMAP_TYPE );
462        if ( null === $master ) {
463            return '';
464        }
465
466        // esc_url_raw (not esc_url): the value is transported via script data and
467        // rendered by React, so it must not be HTML-entity-encoded (e.g. the
468        // plain-permalink `?jetpack-sitemap=` form keeps its raw `&`).
469        // @phan-suppress-next-line PhanUndeclaredFunction -- jp_sitemap_filename()/jetpack_sitemap_uri() live in plugins/jetpack, guarded by function_exists.
470        return esc_url_raw( (string) jetpack_sitemap_uri( jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE ) ) );
471    }
472
473    /**
474     * Whether canonical URLs are enabled.
475     *
476     * Reads the durable {@see self::CANONICAL_ENABLED_OPTION} flag. The default is only
477     * used when the option is absent (for example before the Jetpack plugin's migration
478     * has run on a freshly upgraded site), in which case it falls back to the live
479     * `canonical-urls` module state so behavior is unchanged in that gap.
480     *
481     * @param Modules $modules Modules instance to read live module state from.
482     * @return bool
483     */
484    private static function is_canonical_enabled( Modules $modules ) {
485        $enabled = get_option( self::CANONICAL_ENABLED_OPTION, null );
486
487        // Only fall back to the live module state when the durable option is absent.
488        // Passing it as get_option()'s default would evaluate it on every call, since
489        // PHP resolves function arguments eagerly even when the option exists.
490        if ( null === $enabled ) {
491            $enabled = $modules->is_active( 'canonical-urls' );
492        }
493
494        return (bool) $enabled;
495    }
496
497    /**
498     * Whether the Jetpack SEO surface should be discoverable (admin menu registered).
499     *
500     * WordPress.com sites (Simple + Atomic) are always discoverable — how SEO presents
501     * there is a Dotcom decision, independent of the self-hosted rollout. On self-hosted
502     * sites the durable {@see self::VISIBILITY_OPTION} cohort flag decides: fresh installs
503     * are seeded visible, existing installs stay hidden until they opt in. Defaults to
504     * hidden when the option is absent (e.g. before the plugin's seed has run), so an
505     * existing site is never surprised by the new surface before its cohort is recorded.
506     *
507     * @return bool
508     */
509    public static function is_seo_surface_visible() {
510        if ( class_exists( 'Automattic\\Jetpack\\Status\\Host' ) && ( new Host() )->is_wpcom_platform() ) {
511            return true;
512        }
513
514        return (bool) get_option( self::VISIBILITY_OPTION, false );
515    }
516
517    /**
518     * Whether to offer an existing install the chance to opt into the new SEO experience.
519     *
520     * The single source of truth for the opt-in surfaces (legacy Traffic-page banner, My
521     * Jetpack card). True only when the SEO product is available (the {@see self::FEATURE_FILTER}
522     * flag is on) and the surface isn't visible yet — and since {@see self::is_seo_surface_visible()}
523     * already returns true for WordPress.com and for self-hosted installs that have opted in,
524     * "not visible" cleanly means "a self-hosted install that hasn't opted in".
525     *
526     * @return bool
527     */
528    public static function is_optin_available() {
529        return (bool) apply_filters( self::FEATURE_FILTER, false ) && ! self::is_seo_surface_visible();
530    }
531
532    /**
533     * Build the aggregated Overview state the dashboard renders.
534     *
535     * @return array
536     */
537    public static function get_overview_data() {
538        $modules = new Modules();
539        // @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Utils lives in plugins/jetpack and is guarded by class_exists.
540        $seo_enabled = class_exists( 'Jetpack_SEO_Utils' ) && Jetpack_SEO_Utils::is_enabled_jetpack_seo();
541
542        $codes = get_option( 'verification_services_codes', array() );
543        if ( ! is_array( $codes ) ) {
544            $codes = array();
545        }
546
547        return array(
548            'site_visibility'   => array(
549                'search_engines_visible' => (int) get_option( 'blog_public', 1 ) === 1,
550                // Read the durable SEO option (seeded/synced from the `sitemaps` module
551                // by the Jetpack plugin) so the state survives the module's removal. The
552                // reachable sitemap URL + "View" link live on the Settings tab.
553                'sitemap_active'         => self::is_sitemap_enabled( $modules ),
554                'seo_tools_active'       => $modules->is_active( 'seo-tools' ),
555            ),
556            // Per-service booleans (a code is set or not) for the Overview's
557            // Site verification card.
558            'site_verification' => array(
559                'google'    => ! empty( $codes['google'] ),
560                'bing'      => ! empty( $codes['bing'] ),
561                'pinterest' => ! empty( $codes['pinterest'] ),
562                'yandex'    => ! empty( $codes['yandex'] ),
563                'facebook'  => ! empty( $codes['facebook'] ),
564            ),
565            'content_coverage'  => self::get_content_coverage(),
566            'plan'              => array(
567                'seo_enabled_for_site' => $seo_enabled,
568            ),
569        );
570    }
571
572    /**
573     * Factual content-coverage counts for the Overview card: how many published
574     * posts/pages have each SEO field set. State, not a score — the card shows
575     * proportions + raw counts and lets the admin decide what matters.
576     *
577     * @return array{total:int,with_schema:int,with_title:int,with_description:int,with_search_visible:int}
578     */
579    private static function get_content_coverage() {
580        $post_types = array( 'post', 'page' );
581
582        $total = 0;
583        foreach ( $post_types as $post_type ) {
584            $counts = wp_count_posts( $post_type );
585            $total += isset( $counts->publish ) ? (int) $counts->publish : 0;
586        }
587
588        // Search-engine visibility is the inverse of the per-post noindex meta: a
589        // post is visible unless it's explicitly set to noindex (stored as '1'), so
590        // most posts (no meta row) count as visible.
591        $noindexed = self::count_published_with_meta( $post_types, self::META_NOINDEX, '1' );
592
593        return array(
594            'total'               => $total,
595            'with_schema'         => self::count_published_with_meta( $post_types, self::META_SCHEMA_TYPE ),
596            'with_title'          => self::count_published_with_meta( $post_types, self::META_TITLE ),
597            'with_description'    => self::count_published_with_meta( $post_types, self::META_DESCRIPTION ),
598            'with_search_visible' => max( 0, $total - $noindexed ),
599        );
600    }
601
602    /**
603     * Count published posts/pages whose meta is set. With no `$value`, counts a
604     * non-empty string meta; with a `$value`, counts an exact match.
605     *
606     * @param string[]    $post_types Post types to count across.
607     * @param string      $meta_key   Meta key to test.
608     * @param string|null $value      Exact value to match, or null for "non-empty".
609     * @return int
610     */
611    private static function count_published_with_meta( $post_types, $meta_key, $value = null ) {
612        $clause = null === $value
613            ? array(
614                'key'     => $meta_key,
615                'value'   => '',
616                'compare' => '!=',
617            )
618            : array(
619                'key'   => $meta_key,
620                'value' => $value,
621            );
622
623        $query = new \WP_Query(
624            array(
625                'post_type'              => $post_types,
626                'post_status'            => 'publish',
627                'posts_per_page'         => 1,
628                'fields'                 => 'ids',
629                'update_post_meta_cache' => false,
630                'update_post_term_cache' => false,
631                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Overview snapshot; one count query per metric on the SEO page only.
632                'meta_query'             => array( $clause ),
633            )
634        );
635
636        return (int) $query->found_posts;
637    }
638
639    /**
640     * Site identity used to render the homepage search/social previews on the
641     * Settings tab: title, URL, and representative images. The front-page
642     * description that completes the preview is read from the Settings form
643     * (it's editable there), not bootstrapped here.
644     *
645     * @return array
646     */
647    public static function get_site_data() {
648        $icon_url = (string) get_site_icon_url();
649
650        $logo_id  = (int) get_theme_mod( 'custom_logo' );
651        $logo_url = $logo_id ? (string) wp_get_attachment_image_url( $logo_id, 'full' ) : '';
652
653        return array(
654            'title' => (string) get_bloginfo( 'name' ),
655            'url'   => (string) home_url(),
656            'icon'  => $icon_url,
657            'image' => $logo_url ? $logo_url : $icon_url,
658        );
659    }
660
661    /**
662     * Expose the core `blog_public` option to the REST settings endpoint.
663     *
664     * Search-engine visibility is a WordPress core option, not a Jetpack one,
665     * so the Settings tab saves it through `/wp/v2/settings` — which only
666     * round-trips settings registered with `show_in_rest`. The core settings
667     * controller enforces the `manage_options` capability on writes.
668     *
669     * @return void
670     */
671    public static function register_rest_settings() {
672        register_setting(
673            'reading',
674            'blog_public',
675            array(
676                'show_in_rest' => true,
677                'type'         => 'integer',
678                'default'      => 1,
679            )
680        );
681    }
682
683    /**
684     * Register the opt-in REST route that switches an existing self-hosted install over to
685     * the new SEO experience.
686     *
687     * Lives on the `jetpack/v4` namespace and is registered ahead of the cohort gate, so a
688     * site whose SEO surface is still hidden can reach it from the legacy Traffic page or
689     * My Jetpack. See {@see self::handle_optin()}.
690     *
691     * @return void
692     */
693    public static function register_optin_route() {
694        register_rest_route(
695            'jetpack/v4',
696            '/seo/opt-in',
697            array(
698                'methods'             => \WP_REST_Server::CREATABLE,
699                'callback'            => array( __CLASS__, 'handle_optin' ),
700                'permission_callback' => function () {
701                    return current_user_can( 'manage_options' );
702                },
703            )
704        );
705    }
706
707    /**
708     * Opt an existing install into the new SEO experience: mark the surface visible and
709     * activate the `seo-tools` module, then hand back the dashboard URL to redirect to.
710     *
711     * Idempotent — re-opting-in is harmless. `Modules::activate()` is called with
712     * `$exit = false, $redirect = false`; the defaults would `exit()` and send a 302,
713     * which break a REST response.
714     *
715     * @return \WP_REST_Response
716     */
717    public static function handle_optin() {
718        update_option( self::VISIBILITY_OPTION, true );
719
720        if ( class_exists( 'Automattic\\Jetpack\\Modules' ) ) {
721            ( new Modules() )->activate( 'seo-tools', false, false );
722        }
723
724        return rest_ensure_response(
725            array(
726                'success'  => true,
727                'redirect' => admin_url( 'admin.php?page=' . self::MENU_SLUG ),
728            )
729        );
730    }
731
732    /**
733     * Map of read-only dashboard routes: tab slug => data-builder callable. The
734     * single source of truth for both the registered routes and the paths
735     * preloaded onto the page, so the two can't drift.
736     *
737     * @return array<string, callable>
738     */
739    private static function rest_reads() {
740        return array(
741            'overview' => array( __CLASS__, 'get_overview_data' ),
742            'settings' => array( __CLASS__, 'get_settings_data' ),
743            'ai'       => array( __CLASS__, 'get_ai_data' ),
744        );
745    }
746
747    /**
748     * REST paths the dashboard reads its initial state from, preloaded into the
749     * page (see {@see self::inject_script_data()}) and fetched by the app.
750     *
751     * @return string[]
752     */
753    private static function rest_read_paths() {
754        return array_map(
755            static function ( $slug ) {
756                return '/jetpack/v4/seo/' . $slug;
757            },
758            array_keys( self::rest_reads() )
759        );
760    }
761
762    /**
763     * Register the read-only REST routes the dashboard hydrates from — one per
764     * data-backed tab, each returning the same builder payload previously injected
765     * synchronously onto the page. Read-only and gated to the page's own
766     * `manage_options`; writes still go through their existing endpoints.
767     *
768     * @return void
769     */
770    public static function register_rest_reads() {
771        foreach ( self::rest_reads() as $slug => $builder ) {
772            register_rest_route(
773                'jetpack/v4',
774                '/seo/' . $slug,
775                array(
776                    'methods'             => \WP_REST_Server::READABLE,
777                    'callback'            => static function () use ( $builder ) {
778                        return rest_ensure_response( call_user_func( $builder ) );
779                    },
780                    'permission_callback' => array( __CLASS__, 'reads_permission_check' ),
781                )
782            );
783        }
784    }
785
786    /**
787     * Capability gate for the dashboard's read routes — the same `manage_options`
788     * the SEO admin page itself requires.
789     *
790     * @return bool
791     */
792    public static function reads_permission_check() {
793        return current_user_can( 'manage_options' );
794    }
795
796    /**
797     * Build the editable Settings state the Settings tab hydrates from.
798     *
799     * Read-only bootstrap only. Most writes go through the existing
800     * `/jetpack/v4/settings` REST endpoint, which already validates and
801     * sanitizes those flat fields. Nested Schema writes use the package's
802     * schema-settings route; bootstrapping them here keeps the Settings UI
803     * hydrated without a second request.
804     *
805     * @return array
806     */
807    public static function get_settings_data() {
808        $modules = new Modules();
809
810        // @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Titles lives in plugins/jetpack and is guarded by class_exists.
811        $title_formats = class_exists( 'Jetpack_SEO_Titles' ) ? Jetpack_SEO_Titles::get_custom_title_formats() : array();
812        // @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Utils lives in plugins/jetpack and is guarded by class_exists.
813        $front_page_desc = class_exists( 'Jetpack_SEO_Utils' ) ? Jetpack_SEO_Utils::get_front_page_meta_description() : '';
814
815        $codes = get_option( 'verification_services_codes', array() );
816        if ( ! is_array( $codes ) ) {
817            $codes = array();
818        }
819
820        $sitemap_active = self::is_sitemap_enabled( $modules );
821
822        return array(
823            'search_engines_visible' => (int) get_option( 'blog_public', 1 ) === 1,
824            // Read the durable SEO option (seeded/synced from the `sitemaps` module
825            // by the Jetpack plugin) so the state survives the module's removal.
826            'sitemap_active'         => $sitemap_active,
827            // Empty until the sitemap is genuinely reachable, so the Settings tab can
828            // link to it only once it won't 404 (it's built by cron after activation).
829            'sitemap_url'            => self::get_reachable_sitemap_url( $sitemap_active ),
830            // Read the durable SEO option (seeded/synced from the `canonical-urls` module
831            // by the Jetpack plugin) so the state survives the module's removal.
832            'canonical_active'       => self::is_canonical_enabled( $modules ),
833            // Cast to object so an empty format set serializes as `{}`, not `[]`.
834            'title_formats'          => (object) $title_formats,
835            'front_page_description' => (string) $front_page_desc,
836            'verification'           => array(
837                'google'    => isset( $codes['google'] ) ? (string) $codes['google'] : '',
838                'bing'      => isset( $codes['bing'] ) ? (string) $codes['bing'] : '',
839                'pinterest' => isset( $codes['pinterest'] ) ? (string) $codes['pinterest'] : '',
840                'yandex'    => isset( $codes['yandex'] ) ? (string) $codes['yandex'] : '',
841                'facebook'  => isset( $codes['facebook'] ) ? (string) $codes['facebook'] : '',
842            ),
843            'schema'                 => Schema_Settings::get_editable(),
844        );
845    }
846
847    /**
848     * Build the Google site-verification state for the Settings tab.
849     *
850     * The Settings verification card lets a connected user verify with Google via a
851     * WordPress.com keyring OAuth popup (in addition to pasting a meta-tag code). This
852     * bootstraps the keyring connect URL and whether the current user is connected —
853     * the live verified status is fetched client-side from `/jetpack/v4/verify-site/google`
854     * (a wpcom round-trip we don't want to make on every page load).
855     *
856     * Both `Keyring_Helper` (Publicize package) and the connection `Manager` are provided
857     * by the host Jetpack plugin, so they're guarded with `class_exists` like the
858     * `Jetpack_SEO_*` helpers. On a disconnected self-hosted site `is_connected` is false
859     * and the UI falls back to manual code entry only.
860     *
861     * @return array
862     */
863    public static function get_google_verify_data() {
864        $connect_url = '';
865        if ( class_exists( 'Automattic\\Jetpack\\Publicize\\Keyring_Helper' ) ) {
866            // @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded; Publicize package is provided by the host plugin.
867            $connect_url = (string) \Automattic\Jetpack\Publicize\Keyring_Helper::connect_url( 'google_site_verification', 'other' );
868        }
869
870        $is_connected = false;
871        if ( class_exists( 'Automattic\\Jetpack\\Connection\\Manager' ) ) {
872            // @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded; Connection package is provided by the host plugin.
873            $is_connected = ( new \Automattic\Jetpack\Connection\Manager() )->is_user_connected();
874        }
875
876        return array(
877            'connect_url'  => $connect_url,
878            'is_connected' => (bool) $is_connected,
879        );
880    }
881
882    /**
883     * Build the AI tab's initial state.
884     *
885     * The AI SEO Enhancer auto-generates SEO titles/descriptions/alt-text in the
886     * editor (the generation itself is wpcom/AI-Assistant side); this exposes only
887     * its persisted on/off toggle and whether it's available. Availability mirrors
888     * the legacy Traffic page: the `ai_seo_enhancer_enabled` feature filter must be
889     * on (it still depends on AI being available) AND the site's plan must support
890     * the `ai-seo-enhancer` feature. The toggle writes through the existing
891     * `/jetpack/v4/settings` endpoint (`ai_seo_enhancer_enabled`).
892     *
893     * @return array
894     */
895    public static function get_ai_data() {
896        $filter_on = (bool) apply_filters( 'ai_seo_enhancer_enabled', true );
897
898        // Current_Plan is provided by the host Jetpack plugin, not a package
899        // dependency — guard like the Jetpack_SEO_* helpers above.
900        $plan_supports = class_exists( 'Automattic\\Jetpack\\Current_Plan' )
901            // @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded by class_exists; host plugin provides the class.
902            && \Automattic\Jetpack\Current_Plan::supports( 'ai-seo-enhancer' );
903
904        return array(
905            'enhancer' => array(
906                'available' => $filter_on && $plan_supports,
907                'enabled'   => (bool) get_option( 'ai_seo_enhancer_enabled', false ),
908            ),
909        );
910    }
911}