HEX
Server: nginx
System: Linux pool195-106-36.bur.atomicsites.net 6.12.57+deb12-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.12.57-1~bpo12+1 (2025-11-17) x86_64
User: (0)
PHP: 8.3.32
Disabled: pcntl_fork
Upload Files
File: //wordpress/plugins/jetpack/latest/jetpack_vendor/automattic/jetpack-seo/src/class-initializer.php
<?php
/**
 * Jetpack SEO — the visibility command center for WordPress sites.
 *
 * Registers the `admin.php?page=jetpack-seo` screen via Admin_Menu so it is
 * reachable on self-hosted, Atomic/WoW, and Simple sites alike, and loads the
 * `@wordpress/build` (wp-build) dashboard bundle that renders it.
 *
 * @package automattic/jetpack-seo-package
 */

namespace Automattic\Jetpack\SEO;

use Automattic\Jetpack\Admin_UI\Admin_Menu;
use Automattic\Jetpack\Modules;
use Automattic\Jetpack\Status\Host;
use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
use Jetpack_SEO_Titles;
use Jetpack_SEO_Utils;
use Jetpack_Sitemap_Librarian;

/**
 * The main Initializer class. Registers the admin menu and loads the wp-build
 * dashboard, bootstrapping the React app's initial state onto the page.
 */
class Initializer {

	/**
	 * Jetpack SEO package version.
	 *
	 * @var string
	 */
	const PACKAGE_VERSION = '0.6.0';

	/**
	 * Filter name that gates the entire Jetpack SEO surface.
	 *
	 * When this filter returns true, the package registers its admin menu and
	 * loads the wp-build dashboard. Default false before release - when the
	 * filter is off the package registers no admin menu and no assets, and
	 * changes nothing about the existing Jetpack UI.
	 *
	 * @var string
	 */
	const FEATURE_FILTER = 'rsm_jetpack_seo';

	/**
	 * URL-facing menu slug (`admin.php?page=jetpack-seo`).
	 */
	const MENU_SLUG = 'jetpack-seo';

	/**
	 * Slug emitted by `@wordpress/build` (`wpPlugin.pages[0]`). wp-build's
	 * auto-generated enqueue callback only fires when `$screen->id` matches
	 * this value, so we alias the screen id to it via `current_screen` without
	 * changing the user-facing URL.
	 */
	const WP_BUILD_SLUG = 'jetpack-seo-dashboard';

	/**
	 * Render function generated by `@wordpress/build` into
	 * `build/pages/jetpack-seo-dashboard/page-wp-admin.php`. Naming convention:
	 * `{wpPlugin.name}_{page-with-underscores}_wp_admin_render_page`.
	 */
	const WP_BUILD_RENDER_FN = 'jetpack_seo_jetpack_seo_dashboard_wp_admin_render_page';

	/**
	 * Key under `window.JetpackScriptData` the React app reads its state from
	 * (`window.JetpackScriptData.seo`). Must match the JS-side reader in
	 * `_inc/data/get-overview.ts`.
	 */
	const SCRIPT_DATA_KEY = 'seo';

	/**
	 * Post-meta keys mirrored from `Jetpack_SEO_Posts` (in plugins/jetpack).
	 * Duplicated here as literals on purpose: that plugin class is NOT reliably
	 * loaded in this package's admin context (the `Jetpack_SEO_Utils`
	 * `class_exists` guard in `get_overview_data()` is there for the same
	 * reason), so referencing its constants would fatal. Content-coverage
	 * counting only needs the key strings, which are stable.
	 */
	const META_DESCRIPTION = 'advanced_seo_description';
	const META_SCHEMA_TYPE = 'jetpack_seo_schema_type';
	const META_TITLE       = 'jetpack_seo_html_title';
	const META_NOINDEX     = 'jetpack_seo_noindex';

	/**
	 * Option recording whether sitemap generation is enabled.
	 *
	 * Read in place of the standalone `sitemaps` module's active state. Module-active
	 * state is filtered against the modules present on disk, so once that module is
	 * removed it would read as inactive even for sites that had it on. A one-time
	 * migration in the Jetpack plugin seeds this option from the site's existing module
	 * state and keeps it in sync while the legacy module still exists. See
	 * `Jetpack::migrate_sitemaps_module_to_seo_option()`.
	 *
	 * @var string
	 */
	const SITEMAP_ENABLED_OPTION = 'jetpack_seo_sitemap_enabled';

	/**
	 * Option recording whether canonical URLs are enabled.
	 *
	 * Read in place of the standalone `canonical-urls` module's active state. Module-active
	 * state is filtered against the modules present on disk, so once that module is
	 * removed it would read as inactive even for sites that had it on. A one-time
	 * migration in the Jetpack plugin seeds this option from the site's existing module
	 * state and keeps it in sync while the legacy module still exists. See
	 * `Jetpack::migrate_canonical_urls_module_to_seo_option()`.
	 *
	 * @var string
	 */
	const CANONICAL_ENABLED_OPTION = 'jetpack_seo_canonical_urls_enabled';

	/**
	 * Option recording whether the Jetpack SEO surface is discoverable on this site.
	 *
	 * Gates whether the SEO admin menu registers on self-hosted sites. Seeded once by the
	 * Jetpack plugin on install/upgrade: fresh installs default to visible, existing
	 * installs default to hidden and opt in via the legacy Traffic page or My Jetpack.
	 * WordPress.com (Simple + Atomic) bypasses this option entirely and is always visible.
	 * Absent until seeded, in which case self-hosted defaults to hidden (the non-disruptive
	 * default). See {@see self::is_seo_surface_visible()}.
	 *
	 * @var string
	 */
	const VISIBILITY_OPTION = 'jetpack_seo_surface_visible';

	/**
	 * Transient holding the Overview's content-coverage counts.
	 *
	 * Versioned, so a future change to the payload's shape can't read a stale array
	 * written by an older version of this code.
	 *
	 * @var string
	 */
	const COVERAGE_COUNTS_TRANSIENT = 'jetpack_seo_content_coverage_counts_v1';

	/**
	 * How long the content-coverage counts survive without being invalidated.
	 *
	 * @var int
	 */
	const COVERAGE_COUNTS_TTL = HOUR_IN_SECONDS;

	/**
	 * Whether the package has been initialized.
	 *
	 * @var bool
	 */
	private static $initialized = false;

	/**
	 * Initialize the package.
	 *
	 * Called from the Jetpack plugin's `late_initialization()` hook.
	 *
	 * @return void
	 */
	public static function init() {
		if ( self::$initialized ) {
			return;
		}
		self::$initialized = true;

		// Gate the entire SEO surface behind the feature flag.
		if ( ! (bool) apply_filters( self::FEATURE_FILTER, false ) ) {
			return;
		}

		// The opt-in endpoint must be reachable even before the surface is visible, so
		// existing self-hosted installs can switch to the new experience from the legacy
		// Traffic page or My Jetpack (JETPACK-1700). Registered ahead of the cohort gate.
		add_action( 'rest_api_init', array( __CLASS__, 'register_optin_route' ) );

		// Expose opt-in availability to other admin surfaces (the legacy Traffic-page
		// banner reads it via `@automattic/jetpack-script-data`). Hooked here — after the
		// feature flag, before the cohort gate — so a still-hidden install gets the signal.
		add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_optin_availability' ) );

		// Discoverability cohort gate: the SEO surface is auto-discoverable for fresh
		// installs and all WordPress.com sites; existing self-hosted installs opt in via
		// the legacy Traffic page or My Jetpack (JETPACK-1700). Until it's visible we
		// register nothing else here and let those opt-in surfaces drive discovery.
		if ( ! self::is_seo_surface_visible() ) {
			return;
		}

		// The admin menu and app shell register whenever the surface is visible, even
		// when the `seo-tools` module is inactive, so SEO stays discoverable and can be
		// turned on from within the page itself (JETPACK-1700). When the module is off,
		// the Overview renders only its "enable SEO tools" affordance.
		//
		// Priority 1: load the wp-build bundle (and define its render function)
		// before `add_menu_item()` runs at the default priority and needs it.
		add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
		add_action( 'admin_menu', array( __CLASS__, 'add_menu_item' ), 10 );

		// Read-only REST routes the dashboard hydrates its initial state from. Preloaded
		// into the page (see inject_script_data) so a normal load resolves them with no
		// request, and fetched by the app when that preload is missing or stale — so the
		// dashboard recovers its data instead of dead-ending. Registered whenever the
		// surface is visible (independent of the seo-tools module, like the Overview).
		add_action( 'rest_api_init', array( __CLASS__, 'register_rest_reads' ) );

		// Keep the Overview's cached content-coverage counts honest. Hooked here rather than
		// alongside the admin surface above because posts are written from everywhere — the
		// block editor (REST), the classic editor, wp-cli, cron, other plugins — and the
		// cache has to be dropped wherever that happens, not just where it's read.
		self::register_coverage_invalidation();

		// The settings surface only comes online once SEO tools are active — there's
		// nothing to configure while the module is off, so we don't register its REST
		// endpoints until then. Expose the core `blog_public` option to the REST settings
		// endpoint so the Settings tab can save search-engine visibility via
		// `/wp/v2/settings` (the Jetpack settings endpoint only accepts Jetpack options).
		// Writes are still capability-gated by the core settings controller.
		if ( self::is_seo_tools_module_active() ) {
			// Front-end JSON-LD schema output and author profile schema fields.
			Schema_Builder::init();
			Author_Schema_Node::init();
			add_action( 'rest_api_init', array( __CLASS__, 'register_rest_settings' ) );
			// Package-owned route for the site-level Schema settings (see the controller).
			add_action( 'rest_api_init', array( Schema_Settings_Controller::class, 'register_routes' ) );
		}

		/**
		 * Fires after the Jetpack SEO package is initialized.
		 *
		 * @since 0.1.0
		 */
		do_action( 'jetpack_seo_init' );
	}

	/**
	 * Register the admin menu item.
	 *
	 * Uses Admin_Menu so the page is reachable on wp-admin across all site
	 * types. The render callback is wp-build's generated render function when
	 * the bundle is loaded (i.e. on the SEO page itself, after
	 * `maybe_load_wp_build()` ran at priority 1); otherwise it falls back to a
	 * bare mount node so the page never fatals on an unbuilt checkout.
	 *
	 * @return void
	 */
	public static function add_menu_item() {
		$callback = function_exists( self::WP_BUILD_RENDER_FN )
			? self::WP_BUILD_RENDER_FN
			: array( __CLASS__, 'render_fallback' );

		Admin_Menu::add_menu(
			'SEO',
			'SEO',
			'manage_options',
			self::MENU_SLUG,
			$callback,
			2
		);
	}

	/**
	 * On the SEO admin page, load the wp-build bundle, alias the screen id so
	 * wp-build enqueues its assets, and bootstrap the app's initial state.
	 *
	 * Hooked at `admin_menu` priority 1 so polyfills register and the render
	 * function is defined before `add_menu_item()` runs at priority 10.
	 *
	 * @return void
	 */
	public static function maybe_load_wp_build() {
		if ( ! self::is_seo_admin_request() ) {
			return;
		}

		self::load_wp_build();
		add_action( 'current_screen', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
		add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_script_data' ) );
	}

	/**
	 * Load wp-build's generated registration file and register the polyfills
	 * the bundle depends on. No-op on a fresh checkout before `pnpm build`, in
	 * which case `add_menu_item()` falls back to {@see self::render_fallback()}.
	 *
	 * @return void
	 */
	private static function load_wp_build() {
		$build_index = dirname( __DIR__ ) . '/build/build.php';

		if ( ! file_exists( $build_index ) ) {
			return;
		}

		require_once $build_index;

		WP_Build_Polyfills::register(
			'jetpack-seo',
			array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
		);
	}

	/**
	 * Alias the current screen id to wp-build's expected slug so its
	 * auto-generated enqueue callback fires for our user-facing page.
	 *
	 * @param \WP_Screen|null $screen The current screen object (passed by WP).
	 * @return void
	 */
	public static function alias_screen_id_for_wp_build( $screen ) {
		if ( ! is_object( $screen ) ) {
			return;
		}

		$screen->id = self::WP_BUILD_SLUG;
	}

	/**
	 * Bootstrap the React app's initial state onto `window.JetpackScriptData.seo`.
	 *
	 * Because wp-build pages load as ES modules, `wp_localize_script` can't
	 * attach data to them; the shared `jetpack_admin_js_script_data` filter
	 * (printed by the Script_Data package onto the `jetpack-script-data` handle
	 * the bundle already depends on) is the supported channel. The per-tab state
	 * is provided as an apiFetch *preload* (mirrors Podcast) so the app resolves
	 * it with no request on a normal load yet can re-fetch when the preload is
	 * missing or stale, rather than dead-ending on a one-shot read.
	 *
	 * @param array $data Script data being injected onto the page.
	 * @return array
	 */
	public static function inject_script_data( $data ) {
		if ( ! is_array( $data ) ) {
			$data = array();
		}

		// Preload the dashboard's REST reads into the page so the app resolves them from
		// cache on first paint with no network request — while still being able to
		// re-fetch if that preload is ever missing or stale. This replaces injecting the
		// raw payloads, which the app read synchronously once and couldn't recover from
		// when momentarily absent (the load-error dead-end). See register_rest_reads() and
		// the client readers `_inc/data/get-preloaded.ts` + `_inc/data/use-ensure-tab-data.ts`.
		$data[ self::SCRIPT_DATA_KEY ]['preload'] = array_reduce(
			self::rest_read_paths(),
			'rest_preload_api_request',
			array()
		);

		// Small synchronous reads used outside the per-tab data stores, and not part of
		// the load-error path.
		$data[ self::SCRIPT_DATA_KEY ]['google_verify'] = self::get_google_verify_data();
		$data[ self::SCRIPT_DATA_KEY ]['site']          = self::get_site_data();

		return $data;
	}

	/**
	 * Expose whether this install should be offered the SEO opt-in, onto
	 * `window.JetpackScriptData.seo.optin_available` for other admin surfaces (e.g. the
	 * legacy Traffic-page banner). Only hooked when the feature flag is on, so the field is
	 * simply absent otherwise.
	 *
	 * @param array $data Script data being injected onto the page.
	 * @return array
	 */
	public static function inject_optin_availability( $data ) {
		if ( ! is_array( $data ) ) {
			$data = array();
		}

		$data[ self::SCRIPT_DATA_KEY ]['optin_available'] = self::is_optin_available();
		// Read by the legacy Traffic page to hide its SEO / Sitemaps sections once the
		// site is on the new experience (fresh install / opted-in / WordPress.com), so the
		// two surfaces never show at once. The legacy sections stay for self-hosted installs
		// that haven't opted in.
		$data[ self::SCRIPT_DATA_KEY ]['surface_visible'] = self::is_seo_surface_visible();

		return $data;
	}

	/**
	 * Fallback render used when the wp-build artifact is missing (unbuilt
	 * checkout). Renders a bare wrapper so the page loads without the app.
	 *
	 * @return void
	 */
	public static function render_fallback() {
		echo '<div class="wrap"><h1>SEO</h1></div>';
	}

	/**
	 * Whether the current request targets the SEO admin page.
	 *
	 * @return bool
	 */
	private static function is_seo_admin_request() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! is_admin() || ! isset( $_GET['page'] ) ) {
			return false;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
	}

	/**
	 * Whether the `seo-tools` Jetpack module is currently active.
	 *
	 * @return bool
	 */
	private static function is_seo_tools_module_active() {
		if ( ! class_exists( 'Automattic\\Jetpack\\Modules' ) ) {
			return false;
		}
		return ( new Modules() )->is_active( 'seo-tools' );
	}

	/**
	 * Whether sitemap generation is enabled.
	 *
	 * Reads the durable {@see self::SITEMAP_ENABLED_OPTION} flag. The default is only
	 * used when the option is absent (for example before the Jetpack plugin's migration
	 * has run on a freshly upgraded site), in which case it falls back to the live
	 * `sitemaps` module state so behavior is unchanged in that gap.
	 *
	 * @param Modules $modules Modules instance to read live module state from.
	 * @return bool
	 */
	private static function is_sitemap_enabled( Modules $modules ) {
		$enabled = get_option( self::SITEMAP_ENABLED_OPTION, null );

		// Only fall back to the live module state when the durable option is absent.
		// Passing it as get_option()'s default would evaluate it on every call, since
		// PHP resolves function arguments eagerly even when the option exists.
		if ( null === $enabled ) {
			$enabled = $modules->is_active( 'sitemaps' );
		}

		return (bool) $enabled;
	}

	/**
	 * The public URL of the generated XML sitemap, or an empty string when none
	 * is currently reachable.
	 *
	 * A sitemap is only reachable when generation is enabled, the site is public
	 * (Jetpack does not load the Sitemaps module on sites that discourage search
	 * engines), and the master sitemap has actually been generated — the Jetpack
	 * plugin builds it via cron 1–15 minutes after activation, so the URL 404s
	 * until then. Callers treat an empty string as "not yet reachable" and skip
	 * linking to it.
	 *
	 * {@see Jetpack_Sitemap_Librarian} and jetpack_sitemap_uri() live in the
	 * Jetpack plugin's Sitemaps module (loaded only for an active module on a
	 * public site), so both are guarded; in the package-only context they are
	 * absent and the sitemap is reported as not reachable.
	 *
	 * @param bool $sitemap_active Whether sitemap generation is enabled.
	 * @return string The sitemap URL, or '' when not reachable.
	 */
	private static function get_reachable_sitemap_url( $sitemap_active ) {
		// Jetpack only serves sitemaps when generation is on and the site is public.
		if ( ! $sitemap_active || (int) get_option( 'blog_public', 1 ) !== 1 ) {
			return '';
		}

		// The Sitemaps module (the librarian class, the `JP_MASTER_SITEMAP_TYPE`
		// constant, and the `jp_sitemap_filename()` / `jetpack_sitemap_uri()`
		// helpers) all live together in plugins/jetpack and load as a unit, so this
		// single guard covers every symbol used below.
		if (
			! class_exists( 'Jetpack_Sitemap_Librarian' )
			|| ! defined( 'JP_MASTER_SITEMAP_TYPE' )
			|| ! function_exists( 'jp_sitemap_filename' )
			|| ! function_exists( 'jetpack_sitemap_uri' )
		) {
			return '';
		}

		// The master sitemap is stored as a post once the cron generation run
		// completes; until then there is nothing to link to.
		// `jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE )` is the master file name
		// ('sitemap.xml'); inlined so this stays one (untestable-in-package) line.
		// @phan-suppress-next-line PhanUndeclaredFunction,PhanUndeclaredClassMethod -- guarded above; symbols live in plugins/jetpack.
		$master = ( new Jetpack_Sitemap_Librarian() )->read_sitemap_data( jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE ), JP_MASTER_SITEMAP_TYPE );
		if ( null === $master ) {
			return '';
		}

		// esc_url_raw (not esc_url): the value is transported via script data and
		// rendered by React, so it must not be HTML-entity-encoded (e.g. the
		// plain-permalink `?jetpack-sitemap=` form keeps its raw `&`).
		// @phan-suppress-next-line PhanUndeclaredFunction -- jp_sitemap_filename()/jetpack_sitemap_uri() live in plugins/jetpack, guarded by function_exists.
		return esc_url_raw( (string) jetpack_sitemap_uri( jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE ) ) );
	}

	/**
	 * Whether canonical URLs are enabled.
	 *
	 * Reads the durable {@see self::CANONICAL_ENABLED_OPTION} flag. The default is only
	 * used when the option is absent (for example before the Jetpack plugin's migration
	 * has run on a freshly upgraded site), in which case it falls back to the live
	 * `canonical-urls` module state so behavior is unchanged in that gap.
	 *
	 * @param Modules $modules Modules instance to read live module state from.
	 * @return bool
	 */
	private static function is_canonical_enabled( Modules $modules ) {
		$enabled = get_option( self::CANONICAL_ENABLED_OPTION, null );

		// Only fall back to the live module state when the durable option is absent.
		// Passing it as get_option()'s default would evaluate it on every call, since
		// PHP resolves function arguments eagerly even when the option exists.
		if ( null === $enabled ) {
			$enabled = $modules->is_active( 'canonical-urls' );
		}

		return (bool) $enabled;
	}

	/**
	 * Whether the Jetpack SEO surface should be discoverable (admin menu registered).
	 *
	 * WordPress.com sites (Simple + Atomic) are always discoverable — how SEO presents
	 * there is a Dotcom decision, independent of the self-hosted rollout. On self-hosted
	 * sites the durable {@see self::VISIBILITY_OPTION} cohort flag decides: fresh installs
	 * are seeded visible, existing installs stay hidden until they opt in. Defaults to
	 * hidden when the option is absent (e.g. before the plugin's seed has run), so an
	 * existing site is never surprised by the new surface before its cohort is recorded.
	 *
	 * @return bool
	 */
	public static function is_seo_surface_visible() {
		if ( class_exists( 'Automattic\\Jetpack\\Status\\Host' ) && ( new Host() )->is_wpcom_platform() ) {
			return true;
		}

		return (bool) get_option( self::VISIBILITY_OPTION, false );
	}

	/**
	 * Whether to offer an existing install the chance to opt into the new SEO experience.
	 *
	 * The single source of truth for the opt-in surfaces (legacy Traffic-page banner, My
	 * Jetpack card). True only when the SEO product is available (the {@see self::FEATURE_FILTER}
	 * flag is on) and the surface isn't visible yet — and since {@see self::is_seo_surface_visible()}
	 * already returns true for WordPress.com and for self-hosted installs that have opted in,
	 * "not visible" cleanly means "a self-hosted install that hasn't opted in".
	 *
	 * @return bool
	 */
	public static function is_optin_available() {
		return (bool) apply_filters( self::FEATURE_FILTER, false ) && ! self::is_seo_surface_visible();
	}

	/**
	 * Build the aggregated Overview state the dashboard renders.
	 *
	 * @return array
	 */
	public static function get_overview_data() {
		$modules = new Modules();
		// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Utils lives in plugins/jetpack and is guarded by class_exists.
		$seo_enabled = class_exists( 'Jetpack_SEO_Utils' ) && Jetpack_SEO_Utils::is_enabled_jetpack_seo();

		$codes = get_option( 'verification_services_codes', array() );
		if ( ! is_array( $codes ) ) {
			$codes = array();
		}

		return array(
			'site_visibility'   => array(
				'search_engines_visible' => (int) get_option( 'blog_public', 1 ) === 1,
				// Read the durable SEO option (seeded/synced from the `sitemaps` module
				// by the Jetpack plugin) so the state survives the module's removal. The
				// reachable sitemap URL + "View" link live on the Settings tab.
				'sitemap_active'         => self::is_sitemap_enabled( $modules ),
				'seo_tools_active'       => $modules->is_active( 'seo-tools' ),
			),
			// Per-service booleans (a code is set or not) for the Overview's
			// Site verification card.
			'site_verification' => array(
				'google'    => ! empty( $codes['google'] ),
				'bing'      => ! empty( $codes['bing'] ),
				'pinterest' => ! empty( $codes['pinterest'] ),
				'yandex'    => ! empty( $codes['yandex'] ),
				'facebook'  => ! empty( $codes['facebook'] ),
			),
			'content_coverage'  => self::get_content_coverage(),
			'plan'              => array(
				'seo_enabled_for_site' => $seo_enabled,
			),
		);
	}

	/**
	 * Post types the content-coverage counts span.
	 *
	 * @return string[]
	 */
	private static function coverage_post_types() {
		return array( 'post', 'page' );
	}

	/**
	 * The SEO post-meta keys the content-coverage counts read.
	 *
	 * @return string[]
	 */
	private static function coverage_meta_keys() {
		return array(
			self::META_SCHEMA_TYPE,
			self::META_TITLE,
			self::META_DESCRIPTION,
			self::META_NOINDEX,
		);
	}

	/**
	 * Factual content-coverage counts for the Overview card: how many published
	 * posts/pages have each SEO field set. State, not a score — the card shows
	 * proportions + raw counts and lets the admin decide what matters.
	 *
	 * Served from {@see self::COVERAGE_COUNTS_TRANSIENT} when it's warm. The counts are read on
	 * every load of the SEO page — and by every tab of it, since the dashboard preloads
	 * all of its REST reads at once — so without a cache a plain reload pays for the
	 * query again having changed nothing.
	 *
	 * @return array{total:int,with_schema:int,with_title:int,with_description:int,with_search_visible:int}
	 */
	private static function get_content_coverage() {
		$cached = get_transient( self::COVERAGE_COUNTS_TRANSIENT );

		if ( self::is_content_coverage( $cached ) ) {
			return $cached;
		}

		$coverage = self::compute_content_coverage();

		set_transient( self::COVERAGE_COUNTS_TRANSIENT, $coverage, self::COVERAGE_COUNTS_TTL );

		return $coverage;
	}

	/**
	 * Whether a value read back from the cache is a coverage payload this code can use.
	 *
	 * @param mixed $value Value read from the transient.
	 * @return bool
	 */
	private static function is_content_coverage( $value ) {
		if ( ! is_array( $value ) ) {
			return false;
		}

		foreach ( array( 'total', 'with_schema', 'with_title', 'with_description', 'with_search_visible' ) as $key ) {
			if ( ! isset( $value[ $key ] ) || ! is_int( $value[ $key ] ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Count the coverage metrics straight from the database.
	 *
	 * @return array{total:int,with_schema:int,with_title:int,with_description:int,with_search_visible:int}
	 */
	private static function compute_content_coverage() {
		global $wpdb;

		$post_types = self::coverage_post_types();
		$meta_keys  = self::coverage_meta_keys();

		$meta_key_placeholders  = implode( ', ', array_fill( 0, count( $meta_keys ), '%s' ) );
		$post_type_placeholders = implode( ', ', array_fill( 0, count( $post_types ), '%s' ) );

		/*
		 * Driven from `wp_postmeta`, not `wp_posts`: most sites have far more published
		 * posts than SEO fields set, so the join starts from the small side, where the
		 * `meta_key` index serves `meta_key IN (…)` directly.
		 *
		 * The aggregate has no GROUP BY, so it still returns its single row — counts at
		 * zero, `total` intact — on a site with no SEO meta at all.
		 *
		 * COUNT( DISTINCT p.ID ) because a post can carry more than one row for the same
		 * meta key. `<> ''` counts a field as set; noindex alone is an exact `= '1'`.
		 */
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
		$sql = $wpdb->prepare(
			"SELECT
				(
					SELECT COUNT(*)
					FROM {$wpdb->posts}
					WHERE post_status = 'publish' AND post_type IN ( {$post_type_placeholders} )
				) AS total,
				COUNT( DISTINCT CASE WHEN pm.meta_key = %s AND pm.meta_value <> '' THEN p.ID END ) AS with_schema,
				COUNT( DISTINCT CASE WHEN pm.meta_key = %s AND pm.meta_value <> '' THEN p.ID END ) AS with_title,
				COUNT( DISTINCT CASE WHEN pm.meta_key = %s AND pm.meta_value <> '' THEN p.ID END ) AS with_description,
				COUNT( DISTINCT CASE WHEN pm.meta_key = %s AND pm.meta_value = '1' THEN p.ID END ) AS noindexed
			FROM {$wpdb->postmeta} pm
			INNER JOIN {$wpdb->posts} p
				ON p.ID = pm.post_id
				AND p.post_status = 'publish'
				AND p.post_type IN ( {$post_type_placeholders} )
			WHERE pm.meta_key IN ( {$meta_key_placeholders} )",
			array_merge(
				$post_types,
				// The CASE arms above, in the order they appear.
				array( self::META_SCHEMA_TYPE, self::META_TITLE, self::META_DESCRIPTION, self::META_NOINDEX ),
				$post_types,
				$meta_keys
			)
		);
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Aggregate count with no core API equivalent; $sql is the prepared statement built directly above. The result is cached in self::COVERAGE_COUNTS_TRANSIENT by the get_content_coverage() wrapper, which is the only caller — the sniff just can't see across the two methods.
		$row = $wpdb->get_row( $sql, ARRAY_A );

		// Defaults, so a query that returns nothing at all reads as an empty site rather
		// than fataling on a missing key.
		$counts = array_map(
			'intval',
			array_merge(
				array(
					'total'            => 0,
					'with_schema'      => 0,
					'with_title'       => 0,
					'with_description' => 0,
					'noindexed'        => 0,
				),
				is_array( $row ) ? $row : array()
			)
		);

		return array(
			'total'               => $counts['total'],
			'with_schema'         => $counts['with_schema'],
			'with_title'          => $counts['with_title'],
			'with_description'    => $counts['with_description'],
			// Search-engine visibility is the inverse of the per-post noindex meta: a
			// post is visible unless it's explicitly set to noindex (stored as '1'), so
			// most posts (no meta row) count as visible.
			'with_search_visible' => max( 0, $counts['total'] - $counts['noindexed'] ),
		);
	}

	/**
	 * Hook the writes that can move the content-coverage counts.
	 *
	 * @return void
	 */
	public static function register_coverage_invalidation() {
		// Covers publish, unpublish, trash, untrash and scheduled posts going live — every
		// route by which a post enters or leaves the published set.
		add_action( 'transition_post_status', array( __CLASS__, 'invalidate_content_coverage_on_status_change' ), 10, 3 );
		add_action( 'deleted_post', array( __CLASS__, 'invalidate_content_coverage_on_delete' ), 10, 2 );

		foreach ( array( 'added_post_meta', 'updated_post_meta', 'deleted_post_meta' ) as $hook ) {
			add_action( $hook, array( __CLASS__, 'invalidate_content_coverage_on_meta_change' ), 10, 3 );
		}
	}

	/**
	 * Drop the cached counts when a post enters or leaves the published set.
	 *
	 * Known limitation: this hook only ever sees the post's new type, so converting a
	 * published post to an uncounted post type (or the reverse) isn't caught here and
	 * leaves `total` stale until the next tracked write or the transient's TTL expiry.
	 * A direct `set_post_type()` bypasses every hook anyway, so the TTL backstop is what
	 * ultimately bounds that staleness.
	 *
	 * @param string        $new_status Status the post is moving to.
	 * @param string        $old_status Status the post is moving from.
	 * @param \WP_Post|null $post       The post being transitioned.
	 * @return void
	 */
	public static function invalidate_content_coverage_on_status_change( $new_status, $old_status, $post ) {
		if ( ! $post instanceof \WP_Post || ! in_array( $post->post_type, self::coverage_post_types(), true ) ) {
			return;
		}

		// Draft to draft, pending to draft, and the like never touch the counts.
		if ( 'publish' !== $new_status && 'publish' !== $old_status ) {
			return;
		}

		self::invalidate_content_coverage();
	}

	/**
	 * Drop the cached counts when a post is deleted outright.
	 *
	 * Trashing already goes through `transition_post_status`; this catches a hard delete,
	 * which for an already-trashed post transitions nothing.
	 *
	 * @param int           $post_id Deleted post ID.
	 * @param \WP_Post|null $post    The post that was deleted.
	 * @return void
	 */
	public static function invalidate_content_coverage_on_delete( $post_id, $post = null ) {
		if ( ! $post instanceof \WP_Post || ! in_array( $post->post_type, self::coverage_post_types(), true ) ) {
			return;
		}

		self::invalidate_content_coverage();
	}

	/**
	 * Drop the cached counts when one of the SEO fields they count is written.
	 *
	 * @param int|int[] $meta_id   Meta row ID, or IDs on delete. Unused.
	 * @param int       $object_id Post the meta belongs to. Unused.
	 * @param string    $meta_key  Meta key written.
	 * @return void
	 */
	public static function invalidate_content_coverage_on_meta_change( $meta_id, $object_id, $meta_key ) {
		if ( ! in_array( $meta_key, self::coverage_meta_keys(), true ) ) {
			return;
		}

		self::invalidate_content_coverage();
	}

	/**
	 * Drop the cached counts.
	 *
	 * @return void
	 */
	private static function invalidate_content_coverage() {
		delete_transient( self::COVERAGE_COUNTS_TRANSIENT );
	}

	/**
	 * Site identity used to render the homepage search/social previews on the
	 * Settings tab: title, URL, and representative images. The front-page
	 * description that completes the preview is read from the Settings form
	 * (it's editable there), not bootstrapped here.
	 *
	 * @return array
	 */
	public static function get_site_data() {
		$icon_url = (string) get_site_icon_url();

		$logo_id  = (int) get_theme_mod( 'custom_logo' );
		$logo_url = $logo_id ? (string) wp_get_attachment_image_url( $logo_id, 'full' ) : '';

		return array(
			'title' => (string) get_bloginfo( 'name' ),
			'url'   => (string) home_url(),
			'icon'  => $icon_url,
			'image' => $logo_url ? $logo_url : $icon_url,
		);
	}

	/**
	 * Expose the core `blog_public` option to the REST settings endpoint.
	 *
	 * Search-engine visibility is a WordPress core option, not a Jetpack one,
	 * so the Settings tab saves it through `/wp/v2/settings` — which only
	 * round-trips settings registered with `show_in_rest`. The core settings
	 * controller enforces the `manage_options` capability on writes.
	 *
	 * @return void
	 */
	public static function register_rest_settings() {
		register_setting(
			'reading',
			'blog_public',
			array(
				'show_in_rest' => true,
				'type'         => 'integer',
				'default'      => 1,
			)
		);
	}

	/**
	 * Register the opt-in REST route that switches an existing self-hosted install over to
	 * the new SEO experience.
	 *
	 * Lives on the `jetpack/v4` namespace and is registered ahead of the cohort gate, so a
	 * site whose SEO surface is still hidden can reach it from the legacy Traffic page or
	 * My Jetpack. See {@see self::handle_optin()}.
	 *
	 * @return void
	 */
	public static function register_optin_route() {
		register_rest_route(
			'jetpack/v4',
			'/seo/opt-in',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( __CLASS__, 'handle_optin' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			)
		);
	}

	/**
	 * Opt an existing install into the new SEO experience: mark the surface visible and
	 * activate the `seo-tools` module, then hand back the dashboard URL to redirect to.
	 *
	 * Idempotent — re-opting-in is harmless. `Modules::activate()` is called with
	 * `$exit = false, $redirect = false`; the defaults would `exit()` and send a 302,
	 * which break a REST response.
	 *
	 * @return \WP_REST_Response
	 */
	public static function handle_optin() {
		update_option( self::VISIBILITY_OPTION, true );

		if ( class_exists( 'Automattic\\Jetpack\\Modules' ) ) {
			( new Modules() )->activate( 'seo-tools', false, false );
		}

		return rest_ensure_response(
			array(
				'success'  => true,
				'redirect' => admin_url( 'admin.php?page=' . self::MENU_SLUG ),
			)
		);
	}

	/**
	 * Map of read-only dashboard routes: tab slug => data-builder callable. The
	 * single source of truth for both the registered routes and the paths
	 * preloaded onto the page, so the two can't drift.
	 *
	 * @return array<string, callable>
	 */
	private static function rest_reads() {
		return array(
			'overview' => array( __CLASS__, 'get_overview_data' ),
			'settings' => array( __CLASS__, 'get_settings_data' ),
			'ai'       => array( __CLASS__, 'get_ai_data' ),
		);
	}

	/**
	 * REST paths the dashboard reads its initial state from, preloaded into the
	 * page (see {@see self::inject_script_data()}) and fetched by the app.
	 *
	 * @return string[]
	 */
	private static function rest_read_paths() {
		return array_map(
			static function ( $slug ) {
				return '/jetpack/v4/seo/' . $slug;
			},
			array_keys( self::rest_reads() )
		);
	}

	/**
	 * Register the read-only REST routes the dashboard hydrates from — one per
	 * data-backed tab, each returning the same builder payload previously injected
	 * synchronously onto the page. Read-only and gated to the page's own
	 * `manage_options`; writes still go through their existing endpoints.
	 *
	 * @return void
	 */
	public static function register_rest_reads() {
		foreach ( self::rest_reads() as $slug => $builder ) {
			register_rest_route(
				'jetpack/v4',
				'/seo/' . $slug,
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => static function () use ( $builder ) {
						return rest_ensure_response( call_user_func( $builder ) );
					},
					'permission_callback' => array( __CLASS__, 'reads_permission_check' ),
				)
			);
		}
	}

	/**
	 * Capability gate for the dashboard's read routes — the same `manage_options`
	 * the SEO admin page itself requires.
	 *
	 * @return bool
	 */
	public static function reads_permission_check() {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Build the editable Settings state the Settings tab hydrates from.
	 *
	 * Read-only bootstrap only. Most writes go through the existing
	 * `/jetpack/v4/settings` REST endpoint, which already validates and
	 * sanitizes those flat fields. Nested Schema writes use the package's
	 * schema-settings route; bootstrapping them here keeps the Settings UI
	 * hydrated without a second request.
	 *
	 * @return array
	 */
	public static function get_settings_data() {
		$modules = new Modules();

		// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Titles lives in plugins/jetpack and is guarded by class_exists.
		$title_formats = class_exists( 'Jetpack_SEO_Titles' ) ? Jetpack_SEO_Titles::get_custom_title_formats() : array();
		// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Utils lives in plugins/jetpack and is guarded by class_exists.
		$front_page_desc = class_exists( 'Jetpack_SEO_Utils' ) ? Jetpack_SEO_Utils::get_front_page_meta_description() : '';

		$codes = get_option( 'verification_services_codes', array() );
		if ( ! is_array( $codes ) ) {
			$codes = array();
		}

		$sitemap_active = self::is_sitemap_enabled( $modules );

		return array(
			'search_engines_visible' => (int) get_option( 'blog_public', 1 ) === 1,
			// Read the durable SEO option (seeded/synced from the `sitemaps` module
			// by the Jetpack plugin) so the state survives the module's removal.
			'sitemap_active'         => $sitemap_active,
			// Empty until the sitemap is genuinely reachable, so the Settings tab can
			// link to it only once it won't 404 (it's built by cron after activation).
			'sitemap_url'            => self::get_reachable_sitemap_url( $sitemap_active ),
			// Read the durable SEO option (seeded/synced from the `canonical-urls` module
			// by the Jetpack plugin) so the state survives the module's removal.
			'canonical_active'       => self::is_canonical_enabled( $modules ),
			// Cast to object so an empty format set serializes as `{}`, not `[]`.
			'title_formats'          => (object) $title_formats,
			'front_page_description' => (string) $front_page_desc,
			'verification'           => array(
				'google'    => isset( $codes['google'] ) ? (string) $codes['google'] : '',
				'bing'      => isset( $codes['bing'] ) ? (string) $codes['bing'] : '',
				'pinterest' => isset( $codes['pinterest'] ) ? (string) $codes['pinterest'] : '',
				'yandex'    => isset( $codes['yandex'] ) ? (string) $codes['yandex'] : '',
				'facebook'  => isset( $codes['facebook'] ) ? (string) $codes['facebook'] : '',
			),
			'schema'                 => Schema_Settings::get_editable(),
		);
	}

	/**
	 * Build the Google site-verification state for the Settings tab.
	 *
	 * The Settings verification card lets a connected user verify with Google via a
	 * WordPress.com keyring OAuth popup (in addition to pasting a meta-tag code). This
	 * bootstraps the keyring connect URL and whether the current user is connected —
	 * the live verified status is fetched client-side from `/jetpack/v4/verify-site/google`
	 * (a wpcom round-trip we don't want to make on every page load).
	 *
	 * Both `Keyring_Helper` (Publicize package) and the connection `Manager` are provided
	 * by the host Jetpack plugin, so they're guarded with `class_exists` like the
	 * `Jetpack_SEO_*` helpers. On a disconnected self-hosted site `is_connected` is false
	 * and the UI falls back to manual code entry only.
	 *
	 * @return array
	 */
	public static function get_google_verify_data() {
		$connect_url = '';
		if ( class_exists( 'Automattic\\Jetpack\\Publicize\\Keyring_Helper' ) ) {
			// @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded; Publicize package is provided by the host plugin.
			$connect_url = (string) \Automattic\Jetpack\Publicize\Keyring_Helper::connect_url( 'google_site_verification', 'other' );
		}

		$is_connected = false;
		if ( class_exists( 'Automattic\\Jetpack\\Connection\\Manager' ) ) {
			// @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded; Connection package is provided by the host plugin.
			$is_connected = ( new \Automattic\Jetpack\Connection\Manager() )->is_user_connected();
		}

		return array(
			'connect_url'  => $connect_url,
			'is_connected' => (bool) $is_connected,
		);
	}

	/**
	 * Build the AI tab's initial state.
	 *
	 * The AI SEO Enhancer auto-generates SEO titles/descriptions/alt-text in the
	 * editor (the generation itself is wpcom/AI-Assistant side); this exposes only
	 * its persisted on/off toggle and whether it's available. Availability mirrors
	 * the legacy Traffic page: the `ai_seo_enhancer_enabled` feature filter must be
	 * on (it still depends on AI being available) AND the site's plan must support
	 * the `ai-seo-enhancer` feature. The toggle writes through the existing
	 * `/jetpack/v4/settings` endpoint (`ai_seo_enhancer_enabled`).
	 *
	 * @return array
	 */
	public static function get_ai_data() {
		$filter_on = (bool) apply_filters( 'ai_seo_enhancer_enabled', true );

		// Current_Plan is provided by the host Jetpack plugin, not a package
		// dependency — guard like the Jetpack_SEO_* helpers above.
		$plan_supports = class_exists( 'Automattic\\Jetpack\\Current_Plan' )
			// @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded by class_exists; host plugin provides the class.
			&& \Automattic\Jetpack\Current_Plan::supports( 'ai-seo-enhancer' );

		return array(
			'enhancer' => array(
				'available' => $filter_on && $plan_supports,
				'enabled'   => (bool) get_option( 'ai_seo_enhancer_enabled', false ),
			),
		);
	}
}