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