Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.78% covered (warning)
88.78%
459 / 517
72.97% covered (warning)
72.97%
27 / 37
CRAP
0.00% covered (danger)
0.00%
0 / 1
Dashboard_Data
88.78% covered (warning)
88.78%
459 / 517
72.97% covered (warning)
72.97%
27 / 37
177.51
0.00% covered (danger)
0.00%
0 / 1
 rest_reads
0.00% covered (danger)
0.00%
0 / 6
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
 permission_check
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register_rest_settings
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
2
 force_setting_args
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
4
 read_boolean_setting
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 option_names
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 settings_definitions
100.00% covered (success)
100.00%
80 / 80
100.00% covered (success)
100.00%
1 / 1
1
 title_format_schemas
100.00% covered (success)
100.00%
48 / 48
100.00% covered (success)
100.00%
1 / 1
2
 front_page_description_option
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 after_setting_write
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 after_settings_request
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
8
 has_module
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 switch_module
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
4
 is_site_private
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 is_site_coming_soon
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 block_publishing_a_private_site
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
6
 sanitize_front_page_description
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 sanitize_title_formats
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
8
 save_verification_codes
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 sanitize_verification_codes
89.47% covered (warning)
89.47%
17 / 19
0.00% covered (danger)
0.00%
0 / 1
10.12
 module_settings
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 register_module_routes
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 update_modules
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 apply_module_setting
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
6
 get_overview_data
95.24% covered (success)
95.24%
20 / 21
0.00% covered (danger)
0.00%
0 / 1
2
 normalize_title_formats
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
10
 get_settings_data
97.62% covered (success)
97.62%
41 / 42
0.00% covered (danger)
0.00%
0 / 1
12
 get_google_verify_data
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
3.01
 get_geo_data
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
5
 get_content_data
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 get_output_data
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_site_fallback_image
46.88% covered (danger)
46.88%
15 / 32
0.00% covered (danger)
0.00%
0 / 1
33.59
 get_site_data
66.67% covered (warning)
66.67%
16 / 24
0.00% covered (danger)
0.00%
0 / 1
10.37
 get_default_title_separator
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 get_reachable_sitemap_url
60.00% covered (warning)
60.00%
6 / 10
0.00% covered (danger)
0.00%
0 / 1
10.14
1<?php
2/**
3 * The SEO dashboard's REST surface: the read-only routes behind each data-backed
4 * tab (preloaded onto the page so a normal load resolves them with no request),
5 * the settings the dashboard writes, and the one write that isn't a setting.
6 *
7 * Writes go through WordPress core's `/wp/v2/settings` wherever the value is an
8 * option — see {@see self::register_rest_settings()} — so the dashboard depends
9 * on nothing but core REST. Module activation is the one thing `register_setting()`
10 * can't express, and has its own small route ({@see self::register_module_routes()}).
11 *
12 * @package automattic/jetpack-seo-package
13 */
14
15namespace Automattic\Jetpack\SEO;
16
17use Automattic\Jetpack\Modules;
18use Automattic\Jetpack\Status;
19use Automattic\Jetpack\Status\Host;
20use WP_Error;
21use WP_REST_Request;
22
23/**
24 * Registers the dashboard's REST routes and settings, and builds their payloads.
25 */
26class Dashboard_Data {
27
28    /**
29     * REST namespace, shared with the package's other Jetpack routes.
30     *
31     * @var string
32     */
33    const REST_NAMESPACE = 'jetpack/v4';
34
35    /**
36     * Route, relative to the namespace, for the dashboard toggles that map to
37     * Jetpack module activation rather than to an option.
38     *
39     * @var string
40     */
41    const MODULES_REST_BASE = '/seo/modules';
42
43    /**
44     * Settings API group the package registers its options under.
45     *
46     * Only the Settings API's `options.php` form handler reads groups, and the
47     * dashboard doesn't go through it — `register_setting()` requires a group, and
48     * it's otherwise inert here.
49     *
50     * @var string
51     */
52    const SETTINGS_GROUP = 'jetpack_seo';
53
54    /**
55     * Option holding the site's verification service codes, one per service.
56     *
57     * @var string
58     */
59    const VERIFICATION_CODES_OPTION = 'verification_services_codes';
60
61    /**
62     * Option holding the SEO page title structures.
63     *
64     * @var string
65     */
66    const TITLE_FORMATS_OPTION = 'advanced_seo_title_formats';
67
68    /**
69     * Option holding the front page meta description.
70     *
71     * Doubles as the REST key for the setting, which stays
72     * stable even when the value is stored in the legacy option instead
73     * ({@see self::front_page_description_option()}).
74     *
75     * @var string
76     */
77    const FRONT_PAGE_META_OPTION = Seo_Tools::FRONT_PAGE_META_OPTION;
78
79    /**
80     * Option holding the AI SEO Enhancer's on/off state.
81     *
82     * @var string
83     */
84    const AI_SEO_ENHANCER_OPTION = 'ai_seo_enhancer_enabled';
85
86    /**
87     * Legacy option the front page meta description is stored in on WordPress.com
88     * sites that set one while SEO tools were free for every Simple site.
89     *
90     * @var string
91     */
92    const LEGACY_FRONT_PAGE_META_OPTION = Seo_Tools::LEGACY_FRONT_PAGE_META_OPTION;
93
94    /**
95     * Map of read-only dashboard routes: tab slug => data-builder callable. The
96     * single source of truth for both the registered routes and the paths
97     * preloaded onto the page, so the two can't drift.
98     *
99     * @return array<string, callable>
100     */
101    private static function rest_reads() {
102        return array(
103            'overview' => array( __CLASS__, 'get_overview_data' ),
104            'settings' => array( __CLASS__, 'get_settings_data' ),
105            'geo'      => array( __CLASS__, 'get_geo_data' ),
106            'content'  => array( __CLASS__, 'get_content_data' ),
107        );
108    }
109
110    /**
111     * REST paths the dashboard reads its initial state from, preloaded into the
112     * page (see {@see Admin_Page::inject_script_data()}) and fetched by the app.
113     *
114     * @return string[]
115     */
116    public static function rest_read_paths() {
117        return array_map(
118            static function ( $slug ) {
119                return '/' . self::REST_NAMESPACE . '/seo/' . $slug;
120            },
121            array_keys( self::rest_reads() )
122        );
123    }
124
125    /**
126     * Register the read-only REST routes the dashboard hydrates from — one per
127     * data-backed tab, each returning the same builder payload previously injected
128     * synchronously onto the page. Read-only and gated to the page's own
129     * `manage_options`; writes still go through their existing endpoints.
130     *
131     * @return void
132     */
133    public static function register_rest_reads() {
134        foreach ( self::rest_reads() as $slug => $builder ) {
135            register_rest_route(
136                self::REST_NAMESPACE,
137                '/seo/' . $slug,
138                array(
139                    'methods'             => \WP_REST_Server::READABLE,
140                    'callback'            => static function () use ( $builder ) {
141                        return rest_ensure_response( call_user_func( $builder ) );
142                    },
143                    'permission_callback' => array( __CLASS__, 'permission_check' ),
144                )
145            );
146        }
147    }
148
149    /**
150     * Capability gate for the dashboard's REST routes — the same `manage_options`
151     * the SEO admin page itself requires, and the same capability the core settings
152     * controller enforces on the settings the dashboard writes there.
153     *
154     * @return bool
155     */
156    public static function permission_check() {
157        return current_user_can( 'manage_options' );
158    }
159
160    /**
161     * Expose every option the SEO dashboard writes to WordPress core's
162     * `/wp/v2/settings` endpoint.
163     *
164     * The dashboard used to save these through the Jetpack plugin's
165     * `/jetpack/v4/settings` route, which doesn't exist everywhere the package
166     * runs — WordPress.com Simple sites boot Jetpack from a small file list that
167     * doesn't include it, so every write 404'd there. Core's settings endpoint is
168     * registered by WordPress itself, needs no new route, and enforces the same
169     * `manage_options` capability, so it works on every platform with one code path.
170     *
171     * Only settings registered with `show_in_rest` round-trip through that
172     * endpoint, and it silently ignores keys that aren't registered. These routes
173     * follow the same SEO Tools activation gate as the dashboard's editors.
174     *
175     * Hooked on `rest_api_init`, not earlier: which option the front page description is
176     * stored in depends on `jetpack_disable_seo_tools`, and a conflicting SEO plugin can
177     * add that filter from anywhere up to the end of `init`. Registering here settles the
178     * question after every one of those has had its say, and still before core builds the
179     * settings route from the registry at priority 99.
180     *
181     * @return void
182     */
183    public static function register_rest_settings() {
184        add_filter( 'rest_request_before_callbacks', array( Share_Image::class, 'validate_request' ), 10, 3 );
185
186        // Search-engine visibility is a WordPress core option, not a Jetpack one.
187        register_setting(
188            'reading',
189            'blog_public',
190            array(
191                'show_in_rest' => true,
192                'type'         => 'integer',
193                'default'      => 1,
194            )
195        );
196
197        // Refuse an indexing write that would publish a private site. Scoped to core's
198        // settings route rather than attached as `blog_public`'s sanitizer, because a
199        // `register_setting()` sanitizer applies to every writer of the option for the
200        // rest of the request — including the site's own visibility control, which must
201        // stay able to change it.
202        add_filter( 'rest_pre_update_setting', array( __CLASS__, 'block_publishing_a_private_site' ), 10, 3 );
203        add_filter( 'rest_pre_update_setting', array( __CLASS__, 'save_verification_codes' ), 10, 3 );
204
205        foreach ( self::settings_definitions() as $option => $args ) {
206            register_setting( self::SETTINGS_GROUP, $option, $args );
207        }
208
209        // `verification_services_codes` is also registered by the verification-tools
210        // module, and the last `register_setting()` for an option name replaces the
211        // registry entry — which would drop the `show_in_rest` exposure the dashboard
212        // saves through, leaving core to ignore the write and still answer 200. Rather
213        // than depend on hook order, force our own arguments back on for the options we
214        // own, whoever registers them and whenever. Added after the loop above so our
215        // own registrations don't recurse through it.
216        add_filter( 'register_setting_args', array( __CLASS__, 'force_setting_args' ), 10, 4 );
217        add_filter( 'rest_pre_get_setting', array( __CLASS__, 'read_boolean_setting' ), 10, 3 );
218
219        // The one thing that has to happen after the write rather than during it:
220        // dropping the superseded legacy front-page option. Both actions pass the
221        // option name first, and `added_option` covers a first write, which
222        // `update_option()` routes through `add_option()`.
223        add_action( 'add_option_' . self::FRONT_PAGE_META_OPTION, array( __CLASS__, 'after_setting_write' ) );
224        add_action( 'update_option_' . self::FRONT_PAGE_META_OPTION, array( __CLASS__, 'after_setting_write' ) );
225        add_filter( 'rest_request_after_callbacks', array( __CLASS__, 'after_settings_request' ), 10, 3 );
226    }
227
228    /**
229     * Keep the REST contract of the options this package owns authoritative, no matter
230     * who else registers them or in what order.
231     *
232     * Only the three arguments that decide whether and how the option round-trips
233     * through `/wp/v2/settings` are forced. Everything else is the caller's: its label
234     * and description still describe its own surface, and leaving its `sanitize_callback`
235     * in place is what keeps the verification-tools module's `jetpack_verification_validate`
236     * attached — and with it the `jetpack_site_verification_validate` action its consumers
237     * listen for. Dashboard verification normalization runs only on core REST writes, leaving
238     * the legacy module and API's own normalization intact.
239     *
240     * @param array  $args     Arguments the caller passed to `register_setting()`.
241     * @param array  $defaults Default arguments.
242     * @param string $group    Setting group (unused).
243     * @param string $option   Option name.
244     * @return array
245     */
246    public static function force_setting_args( $args, $defaults, $group, $option ) {
247        // Cheap membership test first. This filter fires for every `register_setting()`
248        // call in the request — core alone registers ~20 — and building the definitions
249        // rebuilds the title-format schemas and re-decides which description option is live.
250        if ( ! in_array( $option, self::option_names(), true ) ) {
251            return $args;
252        }
253
254        $ours = self::settings_definitions();
255        if ( ! isset( $ours[ $option ] ) ) {
256            return $args;
257        }
258
259        if ( array_key_exists( 'default', $ours[ $option ] ) ) {
260            $args['default'] = $ours[ $option ]['default'];
261        }
262
263        return array_merge(
264            $args,
265            array(
266                'type'         => $ours[ $option ]['type'],
267                'show_in_rest' => $ours[ $option ]['show_in_rest'],
268            )
269        );
270    }
271
272    /**
273     * Normalize false options stored as empty strings so core REST returns a boolean, not null.
274     *
275     * @param mixed  $value Existing filtered setting value.
276     * @param string $name REST setting name.
277     * @param array  $args REST setting registration arguments.
278     * @return mixed Filtered setting value.
279     */
280    public static function read_boolean_setting( $value, $name, $args ) {
281        if ( null !== $value || ! in_array( $name, array( self::AI_SEO_ENHANCER_OPTION, Llms_Txt::OPTION ), true ) ) {
282            return $value;
283        }
284
285        return (bool) get_option( $args['option_name'], $args['schema']['default'] );
286    }
287
288    /**
289     * Every option name this package can own, including both homes the front page
290     * description can have. A flat list so {@see self::force_setting_args()} can rule
291     * an option out without building the definitions.
292     *
293     * @return string[]
294     */
295    private static function option_names() {
296        return array(
297            Share_Image::OPTION,
298            self::AI_SEO_ENHANCER_OPTION,
299            Llms_Txt::OPTION,
300            Ai_Crawlers::OPTION,
301            self::TITLE_FORMATS_OPTION,
302            self::VERIFICATION_CODES_OPTION,
303            self::FRONT_PAGE_META_OPTION,
304            self::LEGACY_FRONT_PAGE_META_OPTION,
305        );
306    }
307
308    /**
309     * The SEO options exposed to `/wp/v2/settings`, keyed by option name.
310     *
311     * Types, defaults and sanitizers mirror what `/jetpack/v4/settings` enforces for
312     * the keys it also exposes, so a save behaves the same through either route.
313     *
314     * @return array<string, array>
315     */
316    private static function settings_definitions() {
317        return array(
318            Share_Image::OPTION                   => array(
319                'type'         => 'integer',
320                'default'      => 0,
321                'show_in_rest' => array(
322                    'schema' => array(
323                        'type'    => 'integer',
324                        'minimum' => 0,
325                    ),
326                ),
327            ),
328            self::AI_SEO_ENHANCER_OPTION          => array(
329                'type'         => 'boolean',
330                'default'      => false,
331                'show_in_rest' => true,
332            ),
333            Llms_Txt::OPTION                      => array(
334                'type'         => 'boolean',
335                'default'      => false,
336                'show_in_rest' => true,
337            ),
338            Ai_Crawlers::OPTION                   => array(
339                'type'              => 'object',
340                'default'           => array(),
341                'sanitize_callback' => array( Ai_Crawlers::class, 'sanitize_blocked' ),
342                'show_in_rest'      => array(
343                    'schema' => array(
344                        'type'       => 'object',
345                        'properties' => array_fill_keys(
346                            Ai_Crawlers::GROUPS,
347                            array(
348                                // Core needs `type` here as well as in `anyOf` (rest_default_additional_properties_to_false()).
349                                'type'  => array( 'string', 'array' ),
350                                'anyOf' => array(
351                                    array(
352                                        'type' => 'string',
353                                        'enum' => array( 'all' ),
354                                    ),
355                                    array(
356                                        'type'  => 'array',
357                                        'items' => array( 'type' => 'string' ),
358                                    ),
359                                ),
360                            )
361                        ),
362                    ),
363                ),
364            ),
365            self::TITLE_FORMATS_OPTION            => array(
366                'type'              => 'object',
367                'default'           => array(),
368                'sanitize_callback' => array( __CLASS__, 'sanitize_title_formats' ),
369                'show_in_rest'      => array(
370                    'schema' => array(
371                        'type'       => 'object',
372                        'properties' => self::title_format_schemas(),
373                    ),
374                ),
375            ),
376            self::VERIFICATION_CODES_OPTION       => array(
377                'type'         => 'object',
378                'default'      => array(),
379                'show_in_rest' => array(
380                    'schema' => array(
381                        'type'       => 'object',
382                        'properties' => array_fill_keys(
383                            array( 'google', 'bing', 'pinterest', 'yandex', 'facebook' ),
384                            array( 'type' => 'string' )
385                        ),
386                    ),
387                ),
388            ),
389            self::front_page_description_option() => array(
390                'type'              => 'string',
391                'sanitize_callback' => array( __CLASS__, 'sanitize_front_page_description' ),
392                // The REST key stays the modern option name even when the value lives in
393                // the legacy one, so the client never has to know which is in play.
394                // Keep the default in REST only: legacy writers distinguish an absent option
395                // from an empty description when the legacy backing option is in use.
396                'show_in_rest'      => array(
397                    'name'   => self::FRONT_PAGE_META_OPTION,
398                    'schema' => array( 'default' => '' ),
399                ),
400            ),
401        );
402    }
403
404    /**
405     * Per-page-type schema for a title structure, restoring the contract the Jetpack
406     * settings endpoint enforced: both keys are required (the renderer reads `type` on every public
407     * request), and a token has to be one this page type actually offers.
408     *
409     * @return array<string, array>
410     */
411    private static function title_format_schemas() {
412        // Mirrors the Jetpack plugin's title-token list, so the schema holds wherever the package runs.
413        $allowed_tokens = array(
414            'front_page' => array( 'site_name', 'tagline' ),
415            'posts'      => array( 'site_name', 'tagline', 'post_title' ),
416            'pages'      => array( 'site_name', 'tagline', 'page_title' ),
417            'groups'     => array( 'site_name', 'tagline', 'group_title' ),
418            'archives'   => array( 'site_name', 'tagline', 'date', 'archive_title' ),
419        );
420
421        $schemas = array();
422        foreach ( $allowed_tokens as $page_type => $tokens ) {
423            $schemas[ $page_type ] = array(
424                'type'  => 'array',
425                'items' => array(
426                    'type'       => 'object',
427                    // Both keys required: the front-end renderer reads `type` on every
428                    // public request, so a token missing it must never reach storage.
429                    'required'   => array( 'type', 'value' ),
430                    'properties' => array(
431                        'type'  => array(
432                            'type' => 'string',
433                            'enum' => array( 'string', 'token' ),
434                        ),
435                        'value' => array( 'type' => 'string' ),
436                    ),
437                    // Which values `value` may take depends on `type`, which one flat
438                    // object can't say. Core applies `oneOf` first and then the shape
439                    // above, so the two together are the old helper's contract.
440                    'oneOf'      => array(
441                        array(
442                            'type'       => 'object',
443                            'properties' => array(
444                                'type' => array(
445                                    'type' => 'string',
446                                    'enum' => array( 'string' ),
447                                ),
448                            ),
449                        ),
450                        array(
451                            'type'       => 'object',
452                            'properties' => array(
453                                'type'  => array(
454                                    'type' => 'string',
455                                    'enum' => array( 'token' ),
456                                ),
457                                'value' => array(
458                                    'type' => 'string',
459                                    'enum' => $tokens,
460                                ),
461                            ),
462                        ),
463                    ),
464                ),
465            );
466        }
467
468        return $schemas;
469    }
470
471    /**
472     * Select the description option that the site currently reads for output.
473     *
474     * @return string
475     */
476    private static function front_page_description_option() {
477        return Seo_Tools::has_legacy_front_page_meta()
478            ? self::LEGACY_FRONT_PAGE_META_OPTION
479            : self::FRONT_PAGE_META_OPTION;
480    }
481
482    /**
483     * Drop the superseded legacy front page description once a modern one is saved.
484     *
485     * The front end falls back to the legacy option whenever the modern value is
486     * empty, so leaving it in place would let a cleared description resurrect text the
487     * site set years ago. Matches what the Jetpack settings endpoint did on the same
488     * write, including its condition: only where Jetpack's SEO output is actually live,
489     * so a site with disabled output keeps its legacy description.
490     *
491     * Hooked to the option-scoped `add_option_*` / `update_option_*` actions rather
492     * than the site-wide ones, so it fires on a real change to this one option instead
493     * of being consulted on every option write in the request.
494     *
495     * @return void
496     */
497    public static function after_setting_write() {
498        if ( Seo_Tools::is_enabled() ) {
499            delete_option( self::LEGACY_FRONT_PAGE_META_OPTION );
500        }
501    }
502
503    /**
504     * Clear legacy text after a successful empty save, including an unchanged modern option.
505     *
506     * An unchanged option does not fire the add/update hooks, so an explicit REST clear
507     * must also remove legacy text that the front end would otherwise use as a fallback.
508     *
509     * @param mixed           $response REST response.
510     * @param array           $handler  Route handler (unused).
511     * @param WP_REST_Request $request  REST request.
512     * @return mixed
513     */
514    public static function after_settings_request( $response, $handler, WP_REST_Request $request ) {
515        if ( is_wp_error( $response ) || rest_ensure_response( $response )->get_status() >= 400
516            || ! preg_match( '#^/wp/v2/(?:sites/[^/]+/)?settings$#', $request->get_route() )
517            || ! in_array( $request->get_method(), array( 'POST', 'PUT', 'PATCH' ), true )
518            || '' !== $request->get_param( self::FRONT_PAGE_META_OPTION ) ) {
519            return $response;
520        }
521
522        $settings = get_registered_settings();
523        if ( isset( $settings[ self::FRONT_PAGE_META_OPTION ] ) && '' === get_option( self::FRONT_PAGE_META_OPTION, '' ) ) {
524            self::after_setting_write();
525        }
526
527        return $response;
528    }
529
530    /**
531     * Whether this site has the given Jetpack module at all.
532     *
533     * Deliberately not `Modules::is_module()`: that's a path-traversal check, and it
534     * passes every slug on a site whose module list is empty — which is the case this
535     * has to detect. WordPress.com Simple ships no Jetpack modules and provides the
536     * behavior itself.
537     *
538     * @param string $module Module slug.
539     * @return bool
540     */
541    private static function has_module( $module ) {
542        // Simple's platform-managed generator is not controlled by module activation.
543        if ( 'sitemaps' === $module && ( new Host() )->is_wpcom_simple() ) {
544            return false;
545        }
546
547        return in_array( $module, ( new Modules() )->get_available(), true );
548    }
549
550    /**
551     * Switch a module without persisting wpcomsh's temporary private-site suppression.
552     *
553     * `Modules::is_active()` reads through `jetpack_active_modules`, where wpcomsh
554     * hides `sitemaps` and `verification-tools` on private and coming-soon sites.
555     * That filtered state cannot tell whether a saved preference is already off:
556     * it reports false even when the module remains in the site's stored list.
557     * Deactivation also reads that list through the filter, so lifting the callback
558     * only for the initial check or final read-back would still leave the switch broken.
559     *
560     * Lift only wpcomsh's callback for the entire read-modify-write. Other filters
561     * still count, so a module genuinely held off remains an error. An isolated hook
562     * copy and the finally block restore the original suppression even after a failure;
563     * saving a module preference does not change the site's visibility.
564     *
565     * @param string $module  Module slug.
566     * @param bool   $enabled Whether the setting is on.
567     * @return bool Whether the module now matches the setting.
568     */
569    private static function switch_module( $module, $enabled ) {
570        global $wp_filter;
571
572        $modules  = new Modules();
573        $hook     = 'jetpack_active_modules';
574        $callback = '\Private_Site\filter_jetpack_active_modules';
575        $priority = has_filter( $hook, $callback );
576        $original = null;
577
578        if ( false !== $priority ) {
579            $original = $wp_filter[ $hook ];
580
581            // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Restore the original hook after the switch.
582            $wp_filter[ $hook ] = clone $original;
583            remove_filter( $hook, $callback, $priority );
584        }
585
586        try {
587            if ( $modules->is_active( $module ) === $enabled ) {
588                return true;
589            }
590
591            $modules->update_status( $module, $enabled, false, false );
592
593            return $modules->is_active( $module ) === $enabled;
594        } finally {
595            if ( null !== $original ) {
596                // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Restore the untouched original hook.
597                $wp_filter[ $hook ] = $original;
598            }
599        }
600    }
601
602    /**
603     * Whether a WordPress.com site is unpublished: private (a negative `blog_public`)
604     * or Coming Soon. Always false on self-hosted, where the option is a plain 0/1.
605     *
606     * @return bool
607     */
608    private static function is_site_private() {
609        return (int) get_option( 'blog_public', 1 ) < 0 || self::is_site_coming_soon();
610    }
611
612    /**
613     * Whether the site is in WordPress.com's Coming Soon mode, which normally keeps
614     * `blog_public` at 0, so only the platform's own flag tells it from a discouraged site.
615     *
616     * @return bool
617     */
618    private static function is_site_coming_soon() {
619        return ( new Host() )->is_wpcom_platform() && (bool) ( new Status() )->is_coming_soon();
620    }
621
622    /**
623     * Refuse an indexing write that would publish a private WordPress.com site or launch a Coming Soon one.
624     *
625     * Needed because jetpack-mu-wpcom ends Coming Soon on any `blog_public` move away from 0. Hooked on
626     * core's settings route, not the option's sanitizer, so the site's own visibility control still works.
627     *
628     * @param bool   $handled Whether another handler already wrote the setting.
629     * @param string $name    Setting name.
630     * @param mixed  $value   Submitted value.
631     * @return bool True to report the write as handled, which skips it.
632     */
633    public static function block_publishing_a_private_site( $handled, $name, $value ) {
634        if ( $handled || 'blog_public' !== $name ) {
635            return $handled;
636        }
637
638        if ( (int) get_option( 'blog_public', 1 ) < 0 ) {
639            return (int) $value >= 0;
640        }
641
642        // A null write deletes the option, which reads back as the registered default of 1.
643        return self::is_site_coming_soon() && ( null === $value || (int) $value > 0 );
644    }
645
646    /**
647     * Clamp the front page meta description to plain text of a bounded length.
648     *
649     * @param string $value Submitted description.
650     * @return string
651     */
652    public static function sanitize_front_page_description( $value ) {
653        $value = wp_strip_all_tags( (string) $value );
654
655        /** This filter is documented in projects/plugins/jetpack/modules/seo-tools/class-jetpack-seo-utils.php */
656        $max_length = (int) apply_filters( 'jetpack_seo_front_page_description_max_length', 300 );
657
658        return function_exists( 'mb_substr' )
659            ? mb_substr( $value, 0, $max_length )
660            : substr( $value, 0, $max_length );
661    }
662
663    /**
664     * Strip markup out of the literal text a title structure joins its tokens with.
665     *
666     * Deliberately not `wp_strip_all_tags()`: that trims, and the spacing around a
667     * separator ("Post Title | Site Name") is exactly what the user typed and has to
668     * survive. Token values are left alone — the schema already limits a token to a
669     * string, and an unrecognized one simply renders as itself.
670     *
671     * @param array $value Submitted title structures, keyed by page type.
672     * @return array
673     */
674    public static function sanitize_title_formats( $value ) {
675        if ( ! is_array( $value ) ) {
676            return array();
677        }
678
679        foreach ( $value as $page_type => $tokens ) {
680            if ( ! is_array( $tokens ) ) {
681                unset( $value[ $page_type ] );
682                continue;
683            }
684
685            foreach ( $tokens as $index => $token ) {
686                if ( ! isset( $token['value'] ) || ! isset( $token['type'] ) || 'string' !== $token['type'] ) {
687                    continue;
688                }
689
690                $text = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', (string) $token['value'] );
691                $text = strip_tags( $text ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- wp_strip_all_tags() trims, and leading/trailing spacing is meaningful here.
692
693                $value[ $page_type ][ $index ]['value'] = preg_replace( '/[\r\n\t ]+/', ' ', $text );
694            }
695        }
696
697        return $value;
698    }
699
700    /**
701     * Normalize dashboard verification writes without changing legacy option writers.
702     *
703     * A register_setting sanitizer would also intercept the legacy API and Sync.
704     * Core has already validated the REST shape here; leave null resets to core.
705     * Existing module sanitizers and their notification hooks still run on the write.
706     *
707     * @param bool   $updated Whether another filter handled the setting.
708     * @param string $name    REST setting name.
709     * @param mixed  $value   Validated submitted value.
710     * @return bool
711     */
712    public static function save_verification_codes( $updated, $name, $value ) {
713        if ( $updated || self::VERIFICATION_CODES_OPTION !== $name || null === $value ) {
714            return $updated;
715        }
716
717        update_option( self::VERIFICATION_CODES_OPTION, self::sanitize_verification_codes( $value ) );
718        return true;
719    }
720
721    /**
722     * Reduce each submitted verification entry to the bare code, merged over the
723     * codes already stored.
724     *
725     * Services hand out a whole `<meta name="…" content="…">` tag and site owners
726     * paste it verbatim, so keep only the content attribute — the same thing the
727     * verification-tools module does when it renders the tag. Merging rather than
728     * replacing keeps any service the dashboard doesn't offer intact.
729     *
730     * @param array $value Submitted codes, keyed by service.
731     * @return array
732     */
733    public static function sanitize_verification_codes( $value ) {
734        $stored = get_option( self::VERIFICATION_CODES_OPTION, array() );
735        if ( ! is_array( $stored ) ) {
736            $stored = array();
737        }
738
739        if ( ! is_array( $value ) ) {
740            return $stored;
741        }
742
743        foreach ( $value as $service => $code ) {
744            if ( ! is_scalar( $code ) ) {
745                continue;
746            }
747            $service = sanitize_key( $service );
748            $code    = trim( (string) $code );
749
750            // Match Jetpack's verification-tools validator, including punctuation in
751            // real provider tokens. Preserve literal plus signs when decoding a meta tag.
752            $pattern = '/^(?!.*[<>"\'])[!-~]+$/';
753            if ( '' !== $code && ! preg_match( $pattern, $code ) ) {
754                if ( ! preg_match( '/content=["\']?([^"\' ]*)["\' ]/is', $code, $matches ) ) {
755                    continue;
756                }
757                $code = trim( rawurldecode( $matches[1] ) );
758                if ( '' === $code || ! preg_match( $pattern, $code ) ) {
759                    continue;
760                }
761            }
762
763            $stored[ $service ] = substr( $code, 0, 100 );
764        }
765
766        return $stored;
767    }
768
769    /**
770     * Map the dashboard's module-backed fields to module slugs.
771     *
772     * These are the settings core's `/wp/v2/settings` cannot own. Switching a module
773     * can fail, and that failure must reach the user rather than return a successful
774     * response with an unchanged stored value. A `register_setting()` sanitizer is
775     * also the wrong place for the switch: it runs before the write and can run on
776     * paths where nothing is persisted. The module route switches the module, checks
777     * the result, and returns a real error when the requested state was not reached.
778     *
779     * @return array<string, string>
780     */
781    private static function module_settings() {
782        return array(
783            'sitemap_active'            => 'sitemaps',
784            'canonical_active'          => 'canonical-urls',
785            'verification_tools_active' => 'verification-tools',
786        );
787    }
788
789    /**
790     * Register the write route for the dashboard settings that switch a Jetpack module.
791     *
792     * Write-only: the current state is already served by `/jetpack/v4/seo/settings`,
793     * which the dashboard reads on load.
794     *
795     * @return void
796     */
797    public static function register_module_routes() {
798        $args = array();
799        foreach ( array_keys( self::module_settings() ) as $field ) {
800            // All optional: the dashboard sends only what changed.
801            $args[ $field ] = array( 'type' => 'boolean' );
802        }
803
804        register_rest_route(
805            self::REST_NAMESPACE,
806            self::MODULES_REST_BASE,
807            array(
808                'methods'             => \WP_REST_Server::EDITABLE,
809                'callback'            => array( __CLASS__, 'update_modules' ),
810                'permission_callback' => array( __CLASS__, 'permission_check' ),
811                'args'                => $args,
812            )
813        );
814    }
815
816    /**
817     * Apply the submitted module-backed settings, and report what was applied.
818     *
819     * @param WP_REST_Request $request The REST request.
820     * @return \WP_REST_Response|WP_Error
821     */
822    public static function update_modules( WP_REST_Request $request ) {
823        $applied = array();
824
825        foreach ( self::module_settings() as $field => $module ) {
826            if ( null === $request[ $field ] ) {
827                continue;
828            }
829
830            $enabled = (bool) $request[ $field ];
831
832            $error = self::apply_module_setting( $module, $enabled );
833            if ( is_wp_error( $error ) ) {
834                // No rollback across fields — module activation fires hooks that other
835                // code has already reacted to, and undoing those is riskier than the
836                // inconsistency. Report which field failed and what did land instead, so
837                // the client can be specific about it.
838                $error->add_data(
839                    array_merge(
840                        (array) $error->get_error_data(),
841                        array(
842                            'field'   => $field,
843                            'applied' => $applied,
844                        )
845                    )
846                );
847                return $error;
848            }
849
850            $applied[ $field ] = $enabled;
851        }
852
853        return rest_ensure_response( $applied );
854    }
855
856    /**
857     * Switch a module and report a failure instead of saving a duplicate option.
858     *
859     * Module state is the source of truth; there is no second option to write or roll
860     * back. Simple has no modules, so its canonical switch is {@see Canonical_Urls::OPTION}.
861     *
862     * @param string $module  Module slug.
863     * @param bool   $enabled Requested state.
864     * @return true|WP_Error
865     */
866    private static function apply_module_setting( $module, $enabled ) {
867        if ( 'canonical-urls' === $module && ( new Host() )->is_wpcom_simple() ) {
868            update_option( Canonical_Urls::OPTION, $enabled ? 1 : 0 );
869            return true;
870        }
871
872        if ( ! self::has_module( $module ) ) {
873            return new WP_Error(
874                'jetpack_seo_module_unavailable',
875                /* translators: %s: name of a Jetpack module, e.g. "sitemaps". */
876                sprintf( __( 'This site has no %s module to switch.', 'jetpack-seo' ), $module ),
877                array( 'status' => 400 )
878            );
879        }
880
881        if ( self::switch_module( $module, $enabled ) ) {
882            return true;
883        }
884
885        return new WP_Error(
886            'jetpack_seo_module_toggle_failed',
887            /* translators: %s: name of a Jetpack module, e.g. "sitemaps". */
888            sprintf( __( 'The %s module could not be switched.', 'jetpack-seo' ), $module ),
889            array( 'status' => 500 )
890        );
891    }
892
893    /**
894     * Build the aggregated Overview state the dashboard renders.
895     *
896     * @return array
897     */
898    public static function get_overview_data() {
899        $modules = new Modules();
900
901        $codes = get_option( 'verification_services_codes', array() );
902        if ( ! is_array( $codes ) ) {
903            $codes = array();
904        }
905
906        return array(
907            'site_visibility'         => array(
908                'search_engines_visible' => (int) get_option( 'blog_public', 1 ) === 1,
909                'site_is_private'        => self::is_site_private(),
910                'sitemap_active'         => $modules->is_active( 'sitemaps' ),
911                'seo_tools_active'       => $modules->is_active( 'seo-tools' ),
912            ),
913            // Per-service booleans (a code is set or not) for the Overview's
914            // Site verification card.
915            'site_verification'       => array(
916                'google'    => ! empty( $codes['google'] ),
917                'bing'      => ! empty( $codes['bing'] ),
918                'pinterest' => ! empty( $codes['pinterest'] ),
919                'yandex'    => ! empty( $codes['yandex'] ),
920                'facebook'  => ! empty( $codes['facebook'] ),
921            ),
922            'content_coverage'        => Content_Coverage::get(),
923            // Whether the site-verification toggle can do anything here. False where
924            // that module isn't present — WordPress.com Simple ships no Jetpack modules
925            // and reports every one of them active — so the dashboard hides the control
926            // rather than offering a toggle the route would refuse.
927            'verification_switchable' => self::has_module( 'verification-tools' ),
928        );
929    }
930
931    /**
932     * Coerce the stored title formats into one `{ type, value }` token list per page type.
933     *
934     * The site-settings API stores a cleared page type as `''` (see JETPACK-2284), so the
935     * option is looser than the Settings tab's type; anything not a token list becomes `array()`.
936     *
937     * @since 0.9.5
938     *
939     * @param mixed $stored Raw option value.
940     * @return array<string, array<int, array{type: string, value: string}>>
941     */
942    public static function normalize_title_formats( $stored ) {
943        if ( ! is_array( $stored ) ) {
944            return array();
945        }
946
947        $normalized = array();
948        foreach ( $stored as $page_type => $format ) {
949            $tokens = array();
950            if ( is_array( $format ) ) {
951                foreach ( $format as $item ) {
952                    if ( is_array( $item ) && isset( $item['type'] ) && isset( $item['value'] ) && is_string( $item['type'] ) && is_string( $item['value'] ) ) {
953                        $tokens[] = array(
954                            'type'  => $item['type'],
955                            'value' => $item['value'],
956                        );
957                    }
958                }
959            }
960            $normalized[ (string) $page_type ] = $tokens;
961        }
962
963        return $normalized;
964    }
965
966    /**
967     * Build the editable Settings state the Settings tab hydrates from.
968     *
969     * Read-only bootstrap only. Writes go to core's `/wp/v2/settings` for every field
970     * backed by an option alone ({@see self::register_rest_settings()}), and to the
971     * package's own routes for the three settings whose write switches a Jetpack module
972     * — sitemap, canonical URLs and site verification ({@see self::module_settings()})
973     * — and for the nested Schema container; bootstrapping them all here keeps the
974     * Settings UI hydrated without a second request.
975     *
976     * @return array
977     */
978    public static function get_settings_data() {
979        $modules = new Modules();
980
981        // Read the stored values directly: the Jetpack plugin's title helper
982        // intentionally hides them while another SEO plugin controls output, but the
983        // dashboard must still show the saved values without allowing edits.
984        $title_formats          = self::normalize_title_formats( get_option( 'advanced_seo_title_formats', array() ) );
985        $title_formats_editable = Seo_Tools::is_enabled();
986        $front_page_desc        = Seo_Tools::get_front_page_meta_description();
987
988        if ( Seo_Tools::is_disabled() ) {
989            // Same for the description, which the helper swaps for the legacy fallback while
990            // another plugin owns the output. Show the one Jetpack resumes with; it's locked.
991            $modern          = get_option( self::FRONT_PAGE_META_OPTION );
992            $front_page_desc = $modern ? $modern : get_option( self::LEGACY_FRONT_PAGE_META_OPTION, '' );
993        }
994
995        // Keep the description source consistent with the option selected for saves.
996        $has_legacy_front_page_meta = Seo_Tools::has_legacy_front_page_meta();
997
998        $codes = get_option( 'verification_services_codes', array() );
999        if ( ! is_array( $codes ) ) {
1000            $codes = array();
1001        }
1002
1003        $sitemap_active = $modules->is_active( 'sitemaps' );
1004        $simple         = ( new Host() )->is_wpcom_simple();
1005
1006        // Ask the conflict check, not the disable filter: anyone can hook that filter just to turn the tags off.
1007        // @phan-suppress-next-line PhanUndeclaredFunction -- guarded by function_exists; lives in plugins/jetpack.
1008        $canonical_conflicted = function_exists( 'jetpack_canonical_urls_check_conflicts' ) && jetpack_canonical_urls_check_conflicts( false );
1009
1010        return array(
1011            'search_engines_visible'     => (int) get_option( 'blog_public', 1 ) === 1,
1012            // A private or Coming Soon WordPress.com site isn't hidden from search by an
1013            // SEO setting and can't be unhidden by one — see {@see self::block_publishing_a_private_site()}.
1014            'site_is_private'            => self::is_site_private(),
1015            'site_is_coming_soon'        => self::is_site_coming_soon(),
1016            'site_visibility_url'        => Ai_Crawlers::privacy_settings_url(),
1017            'sitemap_active'             => $sitemap_active,
1018            'sitemap_switchable'         => self::has_module( 'sitemaps' ),
1019            // The reachable sitemap URL (Jetpack serves a valid sitemap here as soon as
1020            // it's on + the site is public), or '' when sitemaps are off, so the Settings
1021            // tab shows the "View sitemap" link exactly when there's a sitemap to view.
1022            'sitemap_url'                => self::get_reachable_sitemap_url( $sitemap_active ),
1023            // Simple reports every module active, so read its own switch ({@see Canonical_Urls}).
1024            'canonical_active'           => $simple ? Canonical_Urls::is_enabled() : $modules->is_active( 'canonical-urls' ),
1025            'canonical_switchable'       => $simple || self::has_module( 'canonical-urls' ),
1026            'canonical_conflicted'       => $canonical_conflicted,
1027            // Cast to object so an empty format set serializes as `{}`, not `[]`.
1028            'title_formats'              => (object) $title_formats,
1029            // Separator WordPress joins default document-title parts with. A page type
1030            // with no stored format keeps the default title: `get_custom_title()` returns
1031            // the incoming value untouched, so core composes the title itself and the
1032            // Settings tab replays that composition to preview it.
1033            'title_separator'            => self::get_default_title_separator(),
1034            'title_formats_editable'     => $title_formats_editable,
1035            'default_share_image'        => Share_Image::image( (int) get_option( Share_Image::OPTION, 0 ) ),
1036            'share_image_preview'        => self::get_site_fallback_image(),
1037            'front_page_description'     => (string) $front_page_desc,
1038            'has_legacy_front_page_meta' => $has_legacy_front_page_meta,
1039            'verification_tools_active'  => $modules->is_active( 'verification-tools' ),
1040            'verification'               => array(
1041                'google'    => isset( $codes['google'] ) ? (string) $codes['google'] : '',
1042                'bing'      => isset( $codes['bing'] ) ? (string) $codes['bing'] : '',
1043                'pinterest' => isset( $codes['pinterest'] ) ? (string) $codes['pinterest'] : '',
1044                'yandex'    => isset( $codes['yandex'] ) ? (string) $codes['yandex'] : '',
1045                'facebook'  => isset( $codes['facebook'] ) ? (string) $codes['facebook'] : '',
1046            ),
1047            'schema'                     => Schema_Settings::get_editable(),
1048        );
1049    }
1050
1051    /**
1052     * Build the Google site-verification state for the Settings tab.
1053     *
1054     * The Settings verification card lets a connected user verify with Google via a
1055     * WordPress.com keyring OAuth popup (in addition to pasting a meta-tag code). This
1056     * bootstraps the keyring connect URL and whether the current user is connected —
1057     * the live verified status is fetched client-side from `/jetpack/v4/verify-site/google`
1058     * (a wpcom round-trip we don't want to make on every page load).
1059     *
1060     * Both `Keyring_Helper` (Publicize package) and the connection `Manager` are provided
1061     * by the host Jetpack plugin, so they're guarded with `class_exists`. On a disconnected self-hosted site `is_connected` is false
1062     * and the UI falls back to manual code entry only.
1063     *
1064     * @return array
1065     */
1066    public static function get_google_verify_data() {
1067        $connect_url = '';
1068        if ( class_exists( 'Automattic\\Jetpack\\Publicize\\Keyring_Helper' ) ) {
1069            // @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded; Publicize package is provided by the host plugin.
1070            $connect_url = (string) \Automattic\Jetpack\Publicize\Keyring_Helper::connect_url( 'google_site_verification', 'other' );
1071        }
1072
1073        $is_connected = false;
1074        if ( class_exists( 'Automattic\\Jetpack\\Connection\\Manager' ) ) {
1075            $is_connected = ( new \Automattic\Jetpack\Connection\Manager() )->is_user_connected();
1076        }
1077
1078        return array(
1079            'connect_url'  => $connect_url,
1080            'is_connected' => (bool) $is_connected,
1081        );
1082    }
1083
1084    /**
1085     * Build the GEO tab's initial state.
1086     *
1087     * The AI SEO Enhancer auto-generates SEO titles/descriptions/alt-text in the
1088     * editor (the generation itself is wpcom/AI-Assistant side); this exposes only
1089     * its persisted on/off toggle, whether it's available, and whether the AI SEO
1090     * control it sits under is on. Availability mirrors the legacy Traffic page:
1091     * the `ai_seo_enhancer_enabled` feature filter must be on (it still depends on
1092     * AI being available) AND the site's plan must support the `ai-seo-enhancer`
1093     * feature. The toggle writes the `ai_seo_enhancer_enabled` option through core's
1094     * `/wp/v2/settings` endpoint.
1095     *
1096     * `aiSeoEnabled` is reported separately rather than folded into availability:
1097     * with the control off the card is disabled, not hidden, so the saved choice
1098     * stays visible — the same treatment the Traffic page gives it. `aiEnabled`
1099     * reports the site-wide Jetpack AI switch so the tab can name which one is off.
1100     *
1101     * @return array
1102     */
1103    public static function get_geo_data() {
1104        $filter_on = (bool) apply_filters( 'ai_seo_enhancer_enabled', true );
1105
1106        // Jetpack_AI_Settings lives in plugins/jetpack, which bundles this package; guarded
1107        // like the other host-plugin classes here. Without the method the AI SEO control
1108        // does not exist, so the enhancer keeps its pre-control behavior.
1109        // @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_AI_Settings lives in plugins/jetpack and is guarded by is_callable.
1110        $ai_seo_on = ! is_callable( array( 'Jetpack_AI_Settings', 'is_ai_seo_enabled' ) ) || \Jetpack_AI_Settings::is_ai_seo_enabled();
1111        // @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_AI_Settings lives in plugins/jetpack and is guarded by is_callable.
1112        $ai_on = ! is_callable( array( 'Jetpack_AI_Settings', 'is_ai_enabled' ) ) || \Jetpack_AI_Settings::is_ai_enabled();
1113
1114        // Current_Plan comes from the jetpack-plans package (a dependency of this
1115        // package since the plan-gating work), so it's always available here; the
1116        // class_exists guard is kept as belt-and-suspenders for older bundled snapshots.
1117        $plan_supports = class_exists( 'Automattic\\Jetpack\\Current_Plan' )
1118            && \Automattic\Jetpack\Current_Plan::supports( 'ai-seo-enhancer' );
1119
1120        return array(
1121            'enhancer' => array(
1122                'available'    => $filter_on && $plan_supports,
1123                'enabled'      => (bool) get_option( 'ai_seo_enhancer_enabled', false ),
1124                'aiSeoEnabled' => $ai_seo_on,
1125                'aiEnabled'    => $ai_on,
1126            ),
1127            'llmsTxt'  => array(
1128                'enabled'  => Llms_Txt::is_enabled(),
1129                'url'      => home_url( '/llms.txt' ),
1130                'canServe' => Llms_Txt::can_serve(),
1131            ),
1132            'crawlers' => Ai_Crawlers::get_bootstrap_data(),
1133        );
1134    }
1135
1136    /**
1137     * Build the supported post type options for the Content tab.
1138     *
1139     * @return array{post_types:array<int,array{slug:string,label:string}>}
1140     */
1141    public static function get_content_data() {
1142        return array(
1143            'post_types' => Post_Types::get_supported_content_type_options(),
1144        );
1145    }
1146
1147    /**
1148     * Whether Jetpack's SEO output is paused, and the plugin that owns it when one does.
1149     * Every tab reads this one bootstrap for its banner and locked cards.
1150     *
1151     * @since 0.11.0
1152     *
1153     * @return array{paused: bool, conflicting_plugin: string}
1154     */
1155    public static function get_output_data() {
1156        return array(
1157            'paused'             => Seo_Tools::is_disabled(),
1158            'conflicting_plugin' => Seo_Tools::get_conflicting_plugin() ?? '',
1159        );
1160    }
1161
1162    /**
1163     * Resolve the fallback with the same filters used by public sharing metadata.
1164     *
1165     * @param bool $include_default Whether to include the configured default.
1166     * @return string|null Null when the host cannot resolve its automatic fallback here.
1167     */
1168    private static function get_site_fallback_image( $include_default = true ) {
1169        $icon_url        = (string) get_site_icon_url();
1170        $logo_id         = (int) get_theme_mod( 'custom_logo' );
1171        $logo            = $logo_id ? wp_get_attachment_image_src( $logo_id, 'full' ) : false;
1172        $image_url       = $logo ? (string) $logo[0] : $icon_url;
1173        $option_hook     = 'pre_option_' . Share_Image::OPTION;
1174        $without_default = static function () {
1175            return 0;
1176        };
1177        if ( ! $include_default ) {
1178            add_filter( $option_hook, $without_default, PHP_INT_MAX );
1179        }
1180        try {
1181            if ( class_exists( 'Jetpack_Redux_State_Helper' ) ) {
1182                // @phan-suppress-next-line PhanUndeclaredClassMethod -- Optional host helper, guarded by class_exists.
1183                $image_url = (string) \Jetpack_Redux_State_Helper::get_site_image();
1184            } else {
1185                $media = $logo ? $logo : wp_get_attachment_image_src( (int) get_option( 'site_icon' ), 'full' );
1186                $image = apply_filters(
1187                    'jetpack_og_default_site_image',
1188                    array(),
1189                    array(
1190                        'src'    => $image_url,
1191                        'width'  => $media[1] ?? 0,
1192                        'height' => $media[2] ?? 0,
1193                        'type'   => $logo ? 'site_logo' : 'site_icon',
1194                    )
1195                );
1196                if ( ! empty( $image['src'] ) ) {
1197                    $image_url = (string) $image['src'];
1198                } elseif ( $include_default ) {
1199                    // Keep the bootstrapped host fallback when a REST request lacks its image helper.
1200                    return null;
1201                }
1202            }
1203        } finally {
1204            if ( ! $include_default ) {
1205                remove_filter( $option_hook, $without_default, PHP_INT_MAX );
1206            }
1207        }
1208        if ( preg_match( '/\.svg(?:[?#]|$)/i', $image_url ) || 'https://s0.wp.com/i/blank.jpg' === $image_url ) {
1209            $image_url = '';
1210        }
1211        return $image_url;
1212    }
1213
1214    /**
1215     * Site identity used to render the homepage search/social previews on the
1216     * Settings tab: title, tagline, URL, and representative images. The front-page
1217     * description that completes the preview is read from the Settings form
1218     * (it's editable there), not bootstrapped here.
1219     *
1220     * @return array
1221     */
1222    public static function get_site_data() {
1223        $icon_url      = (string) get_site_icon_url();
1224        $image_url     = self::get_site_fallback_image( false );
1225        $content_image = '';
1226        $front_page_id = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_on_front' ) : 0;
1227        $front_page    = $front_page_id ? get_post( $front_page_id ) : null;
1228        // Social crawlers do not have the site owner's post password cookie.
1229        $protected = $front_page && '' !== $front_page->post_password;
1230        if ( $front_page && ! $protected && class_exists( '\Automattic\Jetpack\Post_Media\Images' ) ) {
1231            $args = array(
1232                'width'  => 200,
1233                'height' => 200,
1234            );
1235            if ( Content_Gate::is_gated( $front_page ) ) {
1236                $args += array_fill_keys( array( 'from_slideshow', 'from_gallery', 'from_attachment', 'from_blocks', 'from_html' ), false );
1237            }
1238            // @phan-suppress-next-line PhanUndeclaredClassMethod -- Optional host package, guarded above.
1239            $image         = \Automattic\Jetpack\Post_Media\Images::get_image( $front_page->ID, $args );
1240            $content_image = $image['src'] ?? '';
1241        }
1242
1243        return array(
1244            'content_image'        => $content_image,
1245            'front_page_protected' => $protected,
1246            'title'                => (string) get_bloginfo( 'name' ),
1247            'tagline'              => (string) get_bloginfo( 'description' ),
1248            'url'                  => (string) home_url(),
1249            'icon'                 => $icon_url,
1250            'image'                => $image_url,
1251        );
1252    }
1253
1254    /**
1255     * The separator, as rendered, that WordPress joins default document-title parts
1256     * with — for previewing the title a page type with no stored format produces.
1257     *
1258     * `document_title_separator` alone is not what a visitor sees. `wp_get_document_title()`
1259     * composes the parts, then passes the whole title through the `document_title`
1260     * filter, which WordPress texturizes by default — turning the default spaced
1261     * hyphen into an en dash. Previewing the raw filter value would show `-` on a site
1262     * that renders `–`, which is every site running core's defaults.
1263     *
1264     * This applies only to the default title. A stored format short-circuits
1265     * `pre_get_document_title`, which returns before the `document_title` filter, so a
1266     * custom format keeps the separator the user typed verbatim — the front end renders
1267     * `Site - MARKER - Page` for a custom format while producing `Page – Site` for the
1268     * default one.
1269     *
1270     * @return string The rendered separator.
1271     */
1272    private static function get_default_title_separator() {
1273        $separator = (string) apply_filters( 'document_title_separator', '-' );
1274
1275        // Only texturize when the title itself would be: a site that unhooks
1276        // `wptexturize` renders the raw separator, and the preview should match.
1277        if ( has_filter( 'document_title', 'wptexturize' ) ) {
1278            $separator = trim(
1279                html_entity_decode( wptexturize( ' ' . $separator . ' ' ), ENT_QUOTES, 'UTF-8' )
1280            );
1281        }
1282
1283        return $separator;
1284    }
1285
1286    /**
1287     * The public URL of the XML sitemap, or an empty string when none is reachable.
1288     *
1289     * A sitemap is reachable as soon as generation is enabled and the site is public:
1290     * Jetpack serves a valid (empty-until-built) sitemap at a stable URL — never a 404 —
1291     * so the link is safe to surface immediately, without waiting on (or gating against)
1292     * the cron build. A prior gate looked the master sitemap up by a mis-built filename
1293     * and so never matched, which is what left the Settings tab stuck on "Generating…".
1294     *
1295     * `jetpack_sitemap_uri()` / `jp_sitemap_filename()` and the JP_MASTER_SITEMAP_TYPE
1296     * constant live in the Jetpack plugin's Sitemaps module (loaded only for an active
1297     * module on a public site), so they are guarded; in the package-only context they
1298     * are absent and the sitemap is reported as not reachable.
1299     *
1300     * @param bool $sitemap_active Whether sitemap generation is enabled.
1301     * @return string The sitemap URL, or '' when not reachable.
1302     */
1303    private static function get_reachable_sitemap_url( $sitemap_active ) {
1304        // Jetpack only serves sitemaps when generation is on and the site is public.
1305        if ( ! $sitemap_active || (int) get_option( 'blog_public', 1 ) !== 1 ) {
1306            return '';
1307        }
1308
1309        // The `JP_MASTER_SITEMAP_TYPE` constant and the `jp_sitemap_filename()` /
1310        // `jetpack_sitemap_uri()` helpers all live together in plugins/jetpack and load
1311        // as a unit, so this single guard covers every symbol used below.
1312        if (
1313            ! defined( 'JP_MASTER_SITEMAP_TYPE' )
1314            || ! function_exists( 'jp_sitemap_filename' )
1315            || ! function_exists( 'jetpack_sitemap_uri' )
1316        ) {
1317            return '';
1318        }
1319
1320        // `jp_sitemap_filename()` returns an error string ("error-not-int-…") unless a
1321        // non-null number is passed; the master ignores the number, so pass 0 (matching
1322        // Jetpack's own call sites). Fail safe: the master file is always 'sitemap.xml',
1323        // so if a bundled Jetpack ever returns something else, report not-reachable
1324        // rather than surface a broken URL — the exact failure this method shipped with
1325        // before (the missing number silently produced an "error-not-int-…" link).
1326        // @phan-suppress-next-line PhanUndeclaredFunction -- guarded above; symbols live in plugins/jetpack.
1327        $filename = (string) jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE, 0 );
1328        if ( 'sitemap.xml' !== $filename ) {
1329            return '';
1330        }
1331
1332        // esc_url_raw (not esc_url): transported via script data and rendered by React,
1333        // so it must not be HTML-entity-encoded (e.g. the plain-permalink
1334        // `?jetpack-sitemap=` form keeps its raw `&`).
1335        // @phan-suppress-next-line PhanUndeclaredFunction -- guarded above; symbols live in plugins/jetpack.
1336        return esc_url_raw( (string) jetpack_sitemap_uri( $filename ) );
1337    }
1338}