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