# jetpack/16.3-beta/jetpack_vendor/automattic/jetpack-my-jetpack/src/class-initializer.php

Jetpack – WP Security, Backup, Speed, &amp; Growth, version 16.3-beta. 1,337 lines.

- Page: https://pluginprobe.com/plugins/jetpack/16.3-beta/code/jetpack_vendor/automattic/jetpack-my-jetpack/src/class-initializer.php
- Raw: https://pluginprobe.com/plugins/jetpack/16.3-beta/raw/jetpack_vendor/automattic/jetpack-my-jetpack/src/class-initializer.php
- Modified: 2026-10-05T16:03:54+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/jetpack/16.3-beta/code/jetpack_vendor/automattic/jetpack-my-jetpack/src/class-initializer.php#L10-L20`.

```php
<?php
/**
 * WP Admin page with information and configuration shared among all Jetpack stand-alone plugins
 *
 * @package automattic/my-jetpack
 */

namespace Automattic\Jetpack\My_Jetpack;

use Automattic\Jetpack\Admin_UI\Admin_Menu;
use Automattic\Jetpack\Assets;
use Automattic\Jetpack\Boost_Speed_Score\Speed_Score;
use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_History;
use Automattic\Jetpack\Connection\Client;
use Automattic\Jetpack\Connection\Error_Handler as Connection_Error_Handler;
use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
use Automattic\Jetpack\Connection\REST_Jetpack_AI_JWT;
use Automattic\Jetpack\Constants as Jetpack_Constants;
use Automattic\Jetpack\ExPlat;
use Automattic\Jetpack\Feature_Flags\Feature_Flags;
use Automattic\Jetpack\JITMS\JITM;
use Automattic\Jetpack\Licensing;
use Automattic\Jetpack\Menu_Badges\Menu_Badges;
use Automattic\Jetpack\Menu_Badges\Notification_Counts;
use Automattic\Jetpack\Modules;
use Automattic\Jetpack\Partner_Coupon;
use Automattic\Jetpack\Plugins_Installer;
use Automattic\Jetpack\Status;
use Automattic\Jetpack\Status\Host as Status_Host;
use Automattic\Jetpack\Sync\Functions as Sync_Functions;
use Automattic\Jetpack\Terms_Of_Service;
use Automattic\Jetpack\Tracking;
use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
use Jetpack;
use WP_Error;

/**
 * The main Initializer class that registers the admin menu and eneuque the assets.
 */
class Initializer {

	/**
	 * My Jetpack package version
	 *
	 * @var string
	 */
	const PACKAGE_VERSION = '6.8.0';

	/**
	 * Feature flag that swaps the My Jetpack Products tab for a Features tab.
	 */
	const FEATURES_TAB_FEATURE_FLAG = 'my-jetpack-features-tab';

	/**
	 * Handle for the classic script that carries the React initial state.
	 *
	 * Plugins that render My Jetpack components on their own pages (Boost) depend on this name.
	 */
	const DATA_SCRIPT_HANDLE = 'my_jetpack_main_app';

	/**
	 * Handle for the webpack bundle that renders the onboarding takeover.
	 */
	const ONBOARDING_SCRIPT_HANDLE = 'my_jetpack_onboarding';

	/**
	 * The wp-build page ID, which the generated enqueue check expects as the screen ID.
	 */
	const WP_BUILD_PAGE_ID = 'my-jetpack-dashboard';

	/**
	 * HTML container ID for the IDC screen on My Jetpack page.
	 */
	private const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';

	public const JETPACK_PLUGIN_SLUGS = array(
		'jetpack-backup',
		'jetpack-boost',
		'zerobscrm',
		'jetpack',
		'jetpack-protect',
		'jetpack-social',
		'jetpack-videopress',
		'jetpack-search',
		'jetpack-stats',
	);

	private const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';

	/**
	 * Holds info/data about the site (from the /sites/%d endpoint)
	 *
	 * @var object
	 */
	public static $site_info;

	/**
	 * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
	 *
	 * @var string|null
	 */
	private static $wp_build_original_screen_id = null;

	/**
	 * Initialize My Jetpack
	 *
	 * @return void
	 */
	public static function init() {
		// Before the gate, so the flag stays listed while diagnosing why My Jetpack is off.
		self::register_feature_flags();

		// Before the gate: the Jetpack plugin renders this package's connection screen and footer
		// links even where My Jetpack is off, and `myJetpackInitialState` only exists on its own page.
		add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_admin_script_data' ) );

		if ( ! self::should_initialize() || did_action( 'my_jetpack_init' ) ) {
			return;
		}

		// Answer "is this product on?" for admin menu registration.
		Menu_Visibility::init();

		// Extend jetpack plugins action links.
		Products::extend_plugins_action_links();

		// Set up the REST authentication hooks.
		Connection_Rest_Authentication::init();

		if ( self::is_licensing_ui_enabled() ) {
			Licensing::instance()->initialize();
		}

		// Initialize Boost Speed Score
		new Speed_Score( array(), 'jetpack-my-jetpack' );

		// Add custom WP REST API endoints.
		add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );

		// Both of wp-build's deadlines fall later in this request: its enqueue check must be
		// hooked before `admin_enqueue_scripts`, and its render function defined before
		// the page callback.
		add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );

		add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );

		add_action( 'admin_init', array( __CLASS__, 'setup_historically_active_jetpack_modules_sync' ) );
		// Registered on admin_menu (not admin_init) and well before priority 100000, so the
		// counts it registers exist before the menu-badges renderer runs on admin_menu 100000.
		add_action( 'admin_menu', array( __CLASS__, 'maybe_show_red_bubble' ), 30 );

		// Set up the ExPlat package endpoints
		ExPlat::init();

		// Sets up JITMS.
		JITM::configure();

		// Add "Jetpack Manage" menu item.
		Jetpack_Manage::init();

		/**
		 * Fires after the My Jetpack package is initialized
		 *
		 * @since 0.1.0
		 */
		do_action( 'my_jetpack_init' );
	}

	/**
	 * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
	 *
	 * @since 1.2.0
	 *
	 * @return boolean
	 */
	public static function is_licensing_ui_enabled() {
		// Default changed to true in 1.5.0.
		$is_enabled = true;

		/*
		 * Bail if My Jetpack is not enabled,
		 * and thus the licensing UI shouldn't be enabled either.
		 */
		if ( ! self::should_initialize() ) {
			$is_enabled = false;
		}

		/**
		 * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
		 *
		 * @param bool $is_enabled Defaults to true.
		 *
		 * @since 1.2.0
		 * @since 1.5.0 Update default value to true.
		 */
		return apply_filters(
			'jetpack_my_jetpack_should_enable_add_license_screen',
			$is_enabled
		);
	}

	/**
	 * Add My Jetpack menu item to the admin menu.
	 *
	 * @return void
	 */
	public static function add_my_jetpack_menu_item() {
		$position    = defined( Admin_Menu::class . '::POSITION_FIRST' ) ? Admin_Menu::POSITION_FIRST : -10;
		$menu_slug   = 'my-jetpack';
		$page_suffix = Admin_Menu::add_menu(
			__( 'My Jetpack', 'jetpack-my-jetpack' ),
			__( 'My Jetpack', 'jetpack-my-jetpack' ),
			'edit_posts',
			$menu_slug,
			array( __CLASS__, 'admin_page' ),
			$position
		);
		add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
		// Users who can edit posts but have no Jetpack menu get an admin_page_ hook instead.
		add_action( 'load-admin_page_' . $menu_slug, array( __CLASS__, 'admin_init' ) );
	}

	/**
	 * Callback for the load my jetpack page hook.
	 *
	 * @return void
	 */
	public static function admin_init() {
		$connection = new Connection_Manager();

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No nonce needed for redirect flow control
		$step = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';

		// Handle onboarding redirects based on connection status. Onboarding's only action is the
		// connect request, which answers a user without `jetpack_connect` with a 403.
		$redirect_args = self::get_onboarding_redirect_args(
			$step,
			$connection->is_connected(),
			self::is_onboarding_available() && current_user_can( 'jetpack_connect' )
		);

		if ( null !== $redirect_args ) {
			$admin_page = add_query_arg( $redirect_args, admin_url( 'admin.php' ) );
			$location   = wp_sanitize_redirect( $admin_page );

			// Remove wp_get_referer filter applied in `fix_redirect` method of `Jetpack_Admin` class
			remove_filter( 'wp_redirect', 'wp_get_referer' );
			wp_safe_redirect( $location );

			exit( 0 );
		}

		// If the user reaches the onboarding page, add a class to the body
		if ( $step === 'onboarding' ) {
			add_filter( 'admin_body_class', array( __CLASS__, 'add_onboarding_admin_body_class' ) );
		}

		self::$site_info = self::get_site_info();
		add_filter( 'identity_crisis_container_id', array( static::class, 'get_idc_container_id' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
	}

	/**
	 * Whether the My Jetpack onboarding flow is available on this site.
	 *
	 * WordPress.com Simple sites are connected by definition and don't manage their
	 * connection through My Jetpack, so the onboarding flow (which asks the user to
	 * connect) never applies there. A pending partner coupon brings its own connect screen.
	 *
	 * @internal Not part of the package's public API.
	 *
	 * @return bool
	 */
	public static function is_onboarding_available() {
		return ! ( new Status_Host() )->is_wpcom_simple() && null === self::get_partner_coupon_screen();
	}

	/**
	 * The partner coupon screen's data, when it should replace the dashboard.
	 *
	 * Coupons exist only with the Jetpack plugin, which supplies their products and images.
	 *
	 * @since 6.5.0
	 *
	 * @return array{coupon: array, assetBaseUrl: string}|null
	 */
	public static function get_partner_coupon_screen() {
		if (
			! self::should_initialize()
			|| ! current_user_can( 'manage_options' )
			|| ! Jetpack_Constants::is_defined( 'JETPACK__PLUGIN_FILE' )
		) {
			return null;
		}

		$coupon = Partner_Coupon::get_coupon();
		if ( ! $coupon ) {
			return null;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks which screen renders.
		if ( ! isset( $_GET['showCouponRedemption'] ) && ( new Connection_Manager() )->has_connected_owner() ) {
			return null;
		}

		return array(
			'coupon'       => $coupon,
			'assetBaseUrl' => plugins_url( '', Jetpack_Constants::get_constant( 'JETPACK__PLUGIN_FILE' ) ),
		);
	}

	/**
	 * Decide whether the current My Jetpack request should redirect, and where to.
	 *
	 * @internal Not part of the package's public API.
	 *
	 * @param string $step                 The current `step` query param.
	 * @param bool   $is_connected         Whether the site is connected to WordPress.com.
	 * @param bool   $onboarding_available Whether the onboarding flow is available on this site.
	 * @return array|null Query args for the redirect, or null to stay on the current page.
	 */
	public static function get_onboarding_redirect_args( $step, $is_connected, $onboarding_available ) {
		if ( $onboarding_available && ! $is_connected && $step !== 'onboarding' ) {
			// Redirect to onboarding if not connected
			return array(
				'page' => 'my-jetpack',
				'step' => 'onboarding',
			);
		}

		if ( $step === 'onboarding' && ( ! $onboarding_available || $is_connected ) ) {
			// Redirect away from onboarding if already connected or onboarding is not available on this site
			return array( 'page' => 'my-jetpack' );
		}

		return null;
	}

	/**
	 * Add a body class to the My Jetpack onboarding page.
	 * This class hides the WP Admin toolbar and the sidebar menu.
	 *
	 * @param string $classes The body classes.
	 * @return string The modified body classes.
	 */
	public static function add_onboarding_admin_body_class( $classes ) {
		$classes .= 'jetpack-admin-full-screen';
		return $classes;
	}

	/**
	 * Returns whether we are in condition to track to use
	 * Analytics functionality like Tracks, MC, or GA.
	 */
	public static function can_use_analytics() {
		$status     = new Status();
		$connection = new Connection_Manager();
		$tracking   = new Tracking( 'jetpack', $connection );

		return $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
	}

	/**
	 * Register the package's feature flags.
	 *
	 * @since 6.3.0
	 *
	 * @return void
	 */
	public static function register_feature_flags() {
		Feature_Flags::register(
			self::FEATURES_TAB_FEATURE_FLAG,
			array(
				'default'     => true,
				'description' => 'Replace the My Jetpack Products tab with a Features tab.',
				'owner'       => 'my-jetpack',
			)
		);
	}

	/**
	 * Whether the dashboard shows a Features tab in place of the Products tab.
	 *
	 * @since 6.4.0
	 *
	 * @return bool
	 */
	public static function is_features_tab_enabled() {
		return Feature_Flags::is_enabled( self::FEATURES_TAB_FEATURE_FLAG );
	}

	/**
	 * Get the slug and label that replace the Products tab, for links to it.
	 *
	 * Null while the tab is unchanged, so links keep their own translated "Products" label.
	 *
	 * @since 6.4.0
	 *
	 * @return array{slug: string, label: string}|null
	 */
	public static function get_products_section() {
		if ( ! self::is_features_tab_enabled() ) {
			return null;
		}

		return array(
			'slug'  => 'features',
			'label' => _x( 'Features', 'Navigation item', 'jetpack-my-jetpack' ),
		);
	}

	/**
	 * Whether the current request targets the My Jetpack admin page.
	 *
	 * @since 6.3.0
	 *
	 * @return bool
	 */
	public static function is_my_jetpack_admin_request() {
		if ( ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return false;
		}

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

	/**
	 * Whether the current request is the full-viewport onboarding takeover.
	 *
	 * Onboarding hides all wp-admin chrome and never renders through wp-build.
	 *
	 * @since 6.3.0
	 *
	 * @return bool
	 */
	public static function is_onboarding_request() {
		if ( ! isset( $_GET['step'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return false;
		}

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

	/**
	 * Whether this request is the onboarding takeover rather than the dashboard.
	 *
	 * Loading wp-build, enqueueing scripts and rendering the page must all agree,
	 * so they share this one expression.
	 *
	 * @since 6.3.0
	 *
	 * @return bool
	 */
	public static function is_onboarding_takeover() {
		return self::is_onboarding_request() && self::is_onboarding_available();
	}

	/**
	 * Alias the screen ID to satisfy wp-build's generated enqueue check.
	 *
	 * @since 6.3.0
	 *
	 * @return void
	 */
	public static function alias_screen_id_for_wp_build() {
		$screen = get_current_screen();

		if ( ! $screen ) {
			return;
		}

		self::$wp_build_original_screen_id = $screen->id;
		$screen->id                        = self::WP_BUILD_PAGE_ID;
	}

	/**
	 * Undo alias_screen_id_for_wp_build(), since JITM builds its message path from the screen ID.
	 *
	 * @since 6.3.0
	 *
	 * @return void
	 */
	public static function restore_screen_id_after_wp_build() {
		$screen = get_current_screen();

		if ( ! $screen || null === self::$wp_build_original_screen_id ) {
			return;
		}

		$screen->id                        = self::$wp_build_original_screen_id;
		self::$wp_build_original_screen_id = null;
	}

	/**
	 * Whether this request should load wp-build at all.
	 *
	 * Also what keeps WP_Build_Polyfills from replacing core scripts on every other admin page.
	 *
	 * @since 6.3.0
	 *
	 * @return bool
	 */
	public static function should_load_wp_build() {
		return self::is_my_jetpack_admin_request() && ! self::is_onboarding_takeover();
	}

	/**
	 * Whether this request renders the dashboard through wp-build.
	 *
	 * The generated render function is missing where the package was never built.
	 *
	 * @since 6.3.0
	 *
	 * @return bool
	 */
	public static function should_render_wp_build() {
		return ! self::is_onboarding_takeover()
			&& function_exists( 'jetpack_my_jetpack_my_jetpack_dashboard_wp_admin_render_page' );
	}

	/**
	 * Load wp-build for the My Jetpack dashboard.
	 *
	 * @since 6.3.0
	 *
	 * @return void
	 */
	public static function maybe_load_wp_build() {
		if ( ! self::should_load_wp_build() ) {
			return;
		}

		$build_index = dirname( __DIR__ ) . '/build/build.php';

		if ( file_exists( $build_index ) ) {
			self::load_wp_build( $build_index );
		}
	}

	/**
	 * Require the generated wp-build index and wire it into this request.
	 *
	 * @since 6.3.0
	 *
	 * @param string $build_index Path to the generated `build.php`.
	 * @return void
	 */
	public static function load_wp_build( $build_index ) {
		self::require_wp_build_with_screen_alias( $build_index );

		// wp-build hooks module registration to wp_default_scripts, which has
		// already fired by admin_menu — call it directly or the init module
		// never reaches the import map.
		if ( function_exists( 'jetpack_my_jetpack_register_script_modules' ) ) {
			jetpack_my_jetpack_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
		}

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

	/**
	 * Require the generated build file with the screen ID aliased across its enqueue check.
	 *
	 * @see WP_Build_Screen_Id::load_with_alias()
	 * @param string $build_index Path to the generated `build.php`.
	 * @return void
	 */
	private static function require_wp_build_with_screen_alias( $build_index ) {
		// Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
		if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
			WP_Build_Screen_Id::load_with_alias(
				array( __CLASS__, 'alias_screen_id_for_wp_build' ),
				array( __CLASS__, 'restore_screen_id_after_wp_build' ),
				function () use ( $build_index ) {
					require_once $build_index;
				}
			);
			return;
		}

		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
		require_once $build_index;
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
	}

	/**
	 * Enqueue admin page assets.
	 *
	 * @return void
	 */
	public static function enqueue_scripts() {
		/**
		 * Fires after the My Jetpack page is initialized.
		 * Allows for enqueuing additional scripts only on the My Jetpack page.
		 *
		 * @since 4.35.7
		 */
		do_action( 'myjetpack_enqueue_scripts' );
		add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );

		// Script-less: it only prints the state below, before the dashboard's boot runs on DOMContentLoaded.
		$data_handle = self::DATA_SCRIPT_HANDLE;
		wp_register_script( $data_handle, false, array(), self::PACKAGE_VERSION, true );
		wp_enqueue_script( $data_handle );

		if ( self::is_my_jetpack_admin_request() && self::is_onboarding_takeover() ) {
			Assets::register_script(
				self::ONBOARDING_SCRIPT_HANDLE,
				'../build/onboarding.js',
				__FILE__,
				array(
					'dependencies' => array( $data_handle ),
					'enqueue'      => true,
					'in_footer'    => true,
					'textdomain'   => 'jetpack-my-jetpack',
				)
			);
		} elseif ( self::should_render_wp_build() && wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
			// Registered on every admin page but only enqueued when depended on; the esbuild bundles don't pull it in.
			wp_enqueue_script( 'wp-jp-i18n-loader' );
		}

		$modules             = new Modules();
		$connection          = new Connection_Manager();
		$speed_score_history = new Speed_Score_History( get_site_url() );
		$latest_score        = $speed_score_history->latest();
		$previous_score      = array();
		if ( $speed_score_history->count() > 1 ) {
			$previous_score = $speed_score_history->latest( 1 );
		}
		$latest_score['previousScores'] = $previous_score['scores'] ?? array();

		$sandboxed_domain = '';
		$is_dev_version   = false;
		if ( class_exists( 'Jetpack' ) ) {
			$is_dev_version   = Jetpack::is_development_version();
			$sandboxed_domain = defined( 'JETPACK__SANDBOX_DOMAIN' ) ? JETPACK__SANDBOX_DOMAIN : '';
		}

		$features_tab_enabled = self::is_features_tab_enabled();

		wp_localize_script(
			$data_handle,
			'myJetpackInitialState',
			array(
				'products'               => array(
					'items' => Products::get_products(),
				),
				'mainFeatures'           => $features_tab_enabled ? Main_Features::get_state() : null,
				'featuresBanner'         => $features_tab_enabled ? array( 'isDismissed' => REST_Main_Features::is_banner_dismissed() ) : null,
				'plugins'                => Plugins_Installer::get_plugins(),
				'themes'                 => Sync_Functions::get_themes(),
				'myJetpackUrl'           => admin_url( 'admin.php?page=my-jetpack' ),
				'myJetpackCheckoutUri'   => admin_url( 'admin.php?page=my-jetpack' ),
				'topJetpackMenuItemUrl'  => Admin_Menu::get_top_level_menu_item_url(),
				'siteSuffix'             => ( new Status() )->get_site_suffix(),
				'siteUrl'                => esc_url( get_site_url() ),
				'blogID'                 => Connection_Manager::get_site_id( true ),
				'myJetpackVersion'       => self::PACKAGE_VERSION,
				'myJetpackFlags'         => self::get_my_jetpack_flags(),
				'fileSystemWriteAccess'  => self::has_file_system_write_access(),
				'loadAddLicenseScreen'   => self::is_licensing_ui_enabled(),
				'adminUrl'               => esc_url( admin_url() ),
				'assetsUrl'              => self::get_assets_url(),
				'IDCContainerID'         => static::get_idc_container_id(),
				'userIsAdmin'            => current_user_can( 'manage_options' ),
				'lifecycleStats'         => array(
					'jetpackPlugins'            => self::get_installed_jetpack_plugins(),
					'historicallyActiveModules' => \Jetpack_Options::get_option( 'historically_active_modules', array() ),
					'brokenModules'             => Red_Bubble_Notifications::check_for_broken_modules(),
					'isSiteConnected'           => $connection->is_connected(),
					'isUserConnected'           => $connection->is_user_connected(),
					'modules'                   => self::get_active_modules(),
				),
				'recommendedModules'     => array(
					'modules'    => self::get_recommended_modules(),
					'isFirstRun' => \Jetpack_Options::get_option( 'recommendations_first_run', true ),
					'dismissed'  => \Jetpack_Options::get_option( 'dismissed_recommendations', false ),
				),
				'isStatsModuleActive'    => $modules->is_active( 'stats' ),
				'canUserViewStats'       => current_user_can( 'manage_options' ) || current_user_can( 'view_stats' ),
				'hiddenFeatures'         => Feature_Visibility::get_hidden(),
				'sandboxedDomain'        => $sandboxed_domain,
				'isDevVersion'           => $is_dev_version,
				'isAtomic'               => ( new Status_Host() )->is_woa_site(),
				'isJetpackPluginActive'  => class_exists( 'Jetpack' ),
				'latestBoostSpeedScores' => $latest_score,
				'seoOptIn'               => self::get_seo_opt_in_state(),
				'partnerCoupon'          => self::get_partner_coupon_screen(),
			)
		);

		wp_localize_script(
			$data_handle,
			'myJetpackRest',
			array(
				'apiRoot'  => esc_url_raw( rest_url() ),
				'apiNonce' => wp_create_nonce( 'wp_rest' ),
			)
		);

		// Connection Initial State.
		Connection_Initial_State::render_script( $data_handle );

		// Required for Analytics.
		if ( self::can_use_analytics() ) {
			Tracking::register_tracks_functions_scripts( true );
		}
	}

	/**
	 * Add My Jetpack data to the unified script data object.
	 *
	 * @param array $data The script data.
	 * @return array
	 */
	public static function add_script_data( $data ) {
		$block_availability = class_exists( '\Jetpack_Gutenberg' )
			? \Jetpack_Gutenberg::get_cached_availability()
			: array();

		$data['myJetpack']['siteEditor'] = array(
			'isBlockTheme'            => function_exists( 'wp_is_block_theme' ) && wp_is_block_theme(),
			'isSharingBlockAvailable' => isset( $block_availability['sharing-buttons'] )
				&& $block_availability['sharing-buttons']['available'],
			'isLikeBlockAvailable'    => isset( $block_availability['like'] )
				&& $block_availability['like']['available'],
			'activeThemeStylesheet'   => get_stylesheet(),
		);

		return $data;
	}

	/**
	 * Add My Jetpack availability, image base URL, and products tab to admin script data.
	 *
	 * Printed on every admin page by Script_Data, so the connection screen can resolve its
	 * illustrations and Jetpack footers can link to the products tab off the My Jetpack page.
	 *
	 * @since 6.3.0
	 *
	 * @param array $data Script data.
	 * @return array
	 */
	public static function add_admin_script_data( $data ) {
		$data['myJetpack']['isAvailable']     = self::is_admin_page_available();
		$data['myJetpack']['assetsUrl']       = self::get_assets_url();
		$data['myJetpack']['productsSection'] = self::get_products_section();

		return $data;
	}

	/**
	 * Whether My Jetpack's admin page is available to the current user.
	 *
	 * Meaningful only after admin_menu has registered the page.
	 *
	 * @since 6.5.0
	 *
	 * @return bool
	 */
	public static function is_admin_page_available() {
		global $_registered_pages;

		return did_action( 'my_jetpack_init' ) > 0
			&& isset( $_registered_pages[ get_plugin_page_hookname( 'my-jetpack', 'jetpack' ) ] )
			&& current_user_can( 'edit_posts' );
	}

	/**
	 * Get the base URL of the package's built images, with a trailing slash.
	 *
	 * @since 6.3.0
	 *
	 * @return string
	 */
	public static function get_assets_url() {
		return trailingslashit( Assets::normalize_path( plugins_url( '../build/images/', __FILE__ ) ) );
	}

	/**
	 * Get installed Jetpack plugins
	 *
	 * @return array
	 */
	public static function get_installed_jetpack_plugins() {
		$plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
		$plugin_slugs = array_map(
			static function ( $slug ) {
				$parts = explode( '/', $slug );
				// Return the last segment of the filepath without the PHP extension
				return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
			},
			$plugin_slugs
		);

		return array_values( array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs ) );
	}

	/**
	 * Get active modules (except ones enabled by default)
	 *
	 * @return array
	 */
	public static function get_active_modules() {
		$modules        = new Modules();
		$active_modules = $modules->get_active();

		// if the Jetpack plugin is active, filter out the modules that are active by default
		if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
			$active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
		}
		return array_values( $active_modules );
	}

	/**
	 * Determine if the current user is "new" to Jetpack
	 * This is used to vary some messaging in My Jetpack
	 *
	 * On the front-end, purchases are also taken into account
	 *
	 * @return bool
	 */
	public static function is_jetpack_user_new() {
		// is the user connected?
		$connection = new Connection_Manager();
		if ( $connection->is_user_connected() ) {
			return false;
		}

		// TODO: add a data point for the last known connection/ disconnection time

		// are any modules active?
		$active_modules = self::get_active_modules();
		if ( ! empty( $active_modules ) ) {
			return false;
		}

		// check for other Jetpack plugins that are installed on the site (active or not)
		// If there's more than one Jetpack plugin active, this user is not "new"
		$plugin_slugs              = array_keys( Plugins_Installer::get_plugins() );
		$plugin_slugs              = array_map(
			static function ( $slug ) {
				$parts = explode( '/', $slug );
				// Return the last segment of the filepath without the PHP extension
				return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
			},
			$plugin_slugs
		);
		$installed_jetpack_plugins = array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs );
		if ( is_countable( $installed_jetpack_plugins ) && count( $installed_jetpack_plugins ) >= 2 ) {
			return false;
		}

		// Does the site have any purchases?
		$purchases = Wpcom_Products::get_site_current_purchases();
		if ( ! empty( $purchases ) && ! is_wp_error( $purchases ) ) {
			return false;
		}

		return true;
	}

	/**
	 *  Build flags for My Jetpack UI
	 *
	 *  @return array
	 */
	public static function get_my_jetpack_flags() {
		$flags = array(
			'videoPressStats'          => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
			'showFullJetpackStatsCard' => class_exists( 'Jetpack' ) || Products\Stats::is_standalone_plugin_active(),
			// Only says which destination `manage_url` is: the legacy Stats page
			// caches its report and wants a `force_refresh` hint the dashboard does not.
			'premiumAnalyticsEnabled'  => Products\Stats::is_premium_analytics_enabled(),
			'showAiModuleToggle'       => Products\Jetpack_Ai::is_feature_ui_enabled(),
		);

		return $flags;
	}

	/**
	 * Build the state the My Jetpack "try the new SEO experience" opt-in card hydrates from.
	 *
	 * The card invites an existing self-hosted install to switch over to the new Jetpack SEO
	 * dashboard (JETPACK-1700). Gating lives server-side, where the signals actually are. The
	 * card shows only when all of:
	 *
	 * - the new SEO product is available — the `rsm_jetpack_seo` feature filter is on (the SEO
	 *   package autoloads regardless, so `class_exists()` alone isn't enough; the filter is the
	 *   real availability switch and the same one the SEO package gates its own surface behind);
	 * - the site is self-hosted — WordPress.com (Simple + Atomic) decides its own SEO surface, so
	 *   the opt-in card is for self-hosted installs only;
	 * - the install hasn't opted in yet — `jetpack_seo_surface_visible` is still false. On wpcom
	 *   the SEO package's `is_seo_surface_visible()` short-circuits to `true`, so the
	 *   "not visible yet" check also doubles as the self-hosted guard, but we check the platform
	 *   explicitly for clarity.
	 *
	 * Referenced through `class_exists()` rather than a hard composer dependency: both packages
	 * ship inside the Jetpack plugin and the SEO surface is feature-flagged, so a guarded read of
	 * its public API keeps this from adding plumbing to consumers that don't load SEO.
	 *
	 * The on-success destination is computed by the opt-in endpoint itself; we only seed the card
	 * with the same admin URL so the button has a sensible fallback before the request resolves.
	 *
	 * @return array{showCard: bool, redirect: string}
	 */
	public static function get_seo_opt_in_state() {
		// Guard with method_exists rather than class_exists: an older bundled SEO package can ship
		// the Initializer class without this method, and class_exists alone would still fatal.
		$seo_initializer = 'Automattic\Jetpack\SEO\Initializer';
		// @phan-suppress-next-line PhanUndeclaredClassReference -- optional SEO package, guarded by method_exists.
		$show_card = method_exists( $seo_initializer, 'is_optin_available' ) && $seo_initializer::is_optin_available();

		return array(
			'showCard' => $show_card,
			'redirect' => admin_url( 'admin.php?page=jetpack-seo' ),
		);
	}

	/**
	 * Echoes the admin page content.
	 *
	 * @return void
	 */
	public static function admin_page() {
		// No connection check needed here: admin_init() has already redirected connected users
		// away from onboarding. Availability is re-checked inside the helper on purpose — this
		// render can run even when that redirect did not.
		if ( self::is_onboarding_takeover() ) {
			echo '<div id="my-jetpack-container"></div>';
			return;
		}

		if ( self::should_render_wp_build() ) {
			jetpack_my_jetpack_my_jetpack_dashboard_wp_admin_render_page(); // @phan-suppress-current-line PhanUndeclaredFunction -- should_render_wp_build() checks function_exists(); defined in the generated build/pages/, which Phan excludes.
		}
	}

	/**
	 * Register the REST API routes.
	 *
	 * @return void
	 */
	public static function register_rest_endpoints() {
		new REST_Products();
		new REST_Purchases();
		( new REST_Jetpack_AI_JWT() )->register_rest_route();
		new REST_Recommendations_Evaluation();

		if ( self::is_features_tab_enabled() ) {
			( new REST_Main_Features() )->register_rest_routes();
		}

		Products::register_product_endpoints();
		Historically_Active_Modules::register_rest_endpoints();
		Jetpack_Manage::register_rest_endpoints();
		Red_Bubble_Notifications::register_rest_endpoints();

		register_rest_route(
			'my-jetpack/v1',
			'site',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => __CLASS__ . '::get_site',
				'permission_callback' => __CLASS__ . '::permissions_callback',
			)
		);

		register_rest_route(
			'my-jetpack/v1',
			'site/dismiss-welcome-banner',
			array(
				'methods'             => \WP_REST_Server::EDITABLE,
				'callback'            => __CLASS__ . '::dismiss_welcome_banner',
				'permission_callback' => __CLASS__ . '::permissions_callback',
			)
		);
	}

	/**
	 * Check user capability to access the endpoint.
	 *
	 * @access public
	 * @static
	 *
	 * @return true|WP_Error
	 */
	public static function permissions_callback() {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Return true if we should initialize the My Jetpack admin page.
	 */
	public static function should_initialize() {
		$should = true;

		// All options presented in My Jetpack require a connection to WordPress.com.
		if ( ( new Status() )->is_offline_mode() ) {
			$should = false;
		}

		/**
		 * Allows filtering whether My Jetpack should be initialized.
		 *
		 * @since 0.5.0-alpha
		 *
		 * @param bool $shoud_initialize Should we initialize My Jetpack?
		 */
		return apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
	}

	/**
	 * Hook into several connection-based actions to update the historically active Jetpack modules
	 * If the transient that indicates the list needs to be synced, update it and delete the transient
	 *
	 * @return void
	 */
	public static function setup_historically_active_jetpack_modules_sync() {
		// yummmm. ham.
		$ham = new Historically_Active_Modules();
		if ( get_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY ) && ! wp_doing_ajax() ) {
			$ham::update_historically_active_jetpack_modules();
			delete_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY );
		}

		$actions = array(
			'jetpack_site_registered',
			'jetpack_user_authorized',
			'activated_plugin',
		);

		foreach ( $actions as $action ) {
			add_action( $action, array( $ham, 'queue_historically_active_jetpack_modules_update' ), 5 );
		}

		// Modules are often updated async, so we need to update them right away as there will sometimes be no page reload.
		add_action( 'jetpack_activate_module', array( $ham, 'update_historically_active_jetpack_modules' ), 5 );
	}

	/**
	 * Site full-data endpoint.
	 *
	 * @return object Site data.
	 */
	public static function get_site() {
		$site_id           = \Jetpack_Options::get_option( 'id' );
		$wpcom_endpoint    = sprintf( '/sites/%d?force=wpcom', $site_id );
		$wpcom_api_version = '1.1';
		$response          = Client::wpcom_json_api_request_as_blog( $wpcom_endpoint, $wpcom_api_version );
		$response_code     = wp_remote_retrieve_response_code( $response );
		$body              = json_decode( wp_remote_retrieve_body( $response ) );

		if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
			return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
		}

		return rest_ensure_response( $body );
	}

	/**
	 * Populates the self::$site_info var with site data from the /sites/%d endpoint
	 *
	 * @return object|WP_Error
	 */
	public static function get_site_info() {
		static $site_info = null;

		if ( $site_info !== null ) {
			return $site_info;
		}

		// Check for a cached value before doing lookup
		$stored_site_info = get_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY );
		if ( $stored_site_info !== false ) {
			return $stored_site_info;
		}

		$response = self::get_site();
		if ( is_wp_error( $response ) ) {
			return $response;
		}
		$site_info = $response->data;
		set_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY, $site_info, DAY_IN_SECONDS );

		return $site_info;
	}

	/**
	 * Returns whether a site has been determined "commercial" or not.
	 *
	 * @return bool|null
	 */
	public static function is_commercial_site() {
		if ( is_wp_error( self::$site_info ) ) {
			return null;
		}

		return empty( self::$site_info->options->is_commercial ) ? false : self::$site_info->options->is_commercial;
	}

	/**
	 * Check if site is registered (has been connected before).
	 *
	 * @return bool
	 */
	public static function is_registered() {
		return (bool) \Jetpack_Options::get_option( 'id' );
	}

	/**
	 * Dismiss the welcome banner.
	 *
	 * @return \WP_REST_Response
	 */
	public static function dismiss_welcome_banner() {
		\Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
		return rest_ensure_response( array( 'success' => true ) );
	}

	/**
	 * Returns "yes" if the site has file write access to the plugins folder, "no" otherwise.
	 *
	 * @return string
	 **/
	public static function has_file_system_write_access() {

		$cache = get_transient( 'my_jetpack_write_access' );

		if ( false !== $cache ) {
			return $cache;
		}

		if ( ! function_exists( 'get_filesystem_method' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}

		require_once ABSPATH . 'wp-admin/includes/template.php';

		$write_access = 'no';

		$filesystem_method = get_filesystem_method( array(), WP_PLUGIN_DIR );
		if ( 'direct' === $filesystem_method ) {
			$write_access = 'yes';
		}

		if ( 'no' === $write_access ) {
			ob_start();
			$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
			ob_end_clean();

			if ( $filesystem_credentials_are_stored ) {
				$write_access = 'yes';
			}
		}

		set_transient( 'my_jetpack_write_access', $write_access, 30 * MINUTE_IN_SECONDS );

		return $write_access;
	}

	/**
	 * Get container IDC for the IDC screen.
	 *
	 * @return string
	 */
	public static function get_idc_container_id() {
		return static::IDC_CONTAINER_ID;
	}

	/**
	 * Conditionally append the red bubble notification to the "Jetpack" menu item if there are alerts to show.
	 *
	 * On My Jetpack page: Uses blocking behavior to fetch fresh data.
	 * On other admin pages: Uses cached data only to avoid blocking, with async JS fetch if cache is empty.
	 *
	 * @return void
	 */
	public static function maybe_show_red_bubble() {
		global $pagenow;

		// Don't show red bubble alerts for non-admin users
		// These alerts are generally only actionable for admins
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Don't show any red bubbles when Jetpack is disconnected
		// Users can't act on most alerts without a connection
		$connection = new Connection_Manager();
		if ( ! $connection->is_connected() ) {
			return;
		}

		// Check if we're on the My Jetpack page.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page               = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		$is_my_jetpack_page = $pagenow === 'admin.php' && $page === 'my-jetpack';

		if ( $is_my_jetpack_page ) {
			// On My Jetpack page: use blocking behavior for fresh data.
			add_filter( 'my_jetpack_red_bubble_notification_slugs', array( Red_Bubble_Notifications::class, 'add_red_bubble_alerts' ) );
			$red_bubble_alerts = Red_Bubble_Notifications::get_red_bubble_alerts();
		} else {
			// On other pages: use cached data only to avoid blocking.
			$cached_alerts = Red_Bubble_Notifications::get_cached_alerts();

			if ( false === $cached_alerts ) {
				// No cache: warm it asynchronously via JS. Register a hidden zero-count
				// placeholder so Menu_Renderer emits a `my-jetpack` badge element the
				// warmer can reveal (see async-notification-bubble.ts) without a reload.
				Menu_Badges::init(); // idempotent; wires the renderer.
				Notification_Counts::register(
					'my-jetpack',
					array(
						'menu_slug' => 'my-jetpack',
						'count'     => 0,
						'type'      => 'count',
					)
				);
				add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_red_bubble_script' ) );
				return;
			}

			$red_bubble_alerts = $cached_alerts;
		}

		// Filter out silent alerts.
		$red_bubble_alerts = array_filter(
			$red_bubble_alerts,
			function ( $alert ) {
				return empty( $alert['is_silent'] );
			}
		);

		// Report each non-silent alert to the central menu-badges registry as an
		// attention entry (count 1). The registry + renderer own the badge.
		Menu_Badges::init(); // idempotent; wires the renderer.

		// Connection errors are owned by the Error Handler (the single source of truth):
		// surface any it reports for this viewer as their own attention entry. Read live
		// rather than from the red-bubble transient, since that cache is not viewer-keyed.
		$has_connection_error = self::has_connection_error();
		if ( $has_connection_error ) {
			Notification_Counts::register(
				'my-jetpack-connection-error',
				array(
					'menu_slug' => 'my-jetpack',
					'type'      => 'attention',
				)
			);
		}

		foreach ( array_keys( $red_bubble_alerts ) as $slug ) {
			// Protect reports its own count directly to the registry, but only when its
			// standalone plugin is active (see class-jetpack-protect.php::admin_page_init()).
			// If the standalone plugin isn't active, nobody else registers this count, so we
			// must not skip it here or the alert silently disappears from the menu total.
			if ( 'protect_has_threats' === $slug && Products\Protect::is_standalone_plugin_active() ) {
				continue;
			}
			// The missing-connection slug and a connection error describe the same broken
			// connection; count it once (the error, above, is the more specific signal).
			if ( $has_connection_error && 'missing-connection' === $slug ) {
				continue;
			}
			Notification_Counts::register(
				'my-jetpack-' . $slug,
				array(
					'menu_slug' => 'my-jetpack',
					'type'      => 'attention',
				)
			);
		}
	}

	/**
	 * Whether the Connection Error Handler reports a displayable connection error
	 * for the current viewer.
	 *
	 * Read live (not via the red-bubble transient): get_displayable_errors() is a
	 * cached option read that the Error Handler already scopes and caches per viewer.
	 * Guarded for the mid-plugin-update window, where a stale connection package
	 * predating the method can be loaded.
	 *
	 * @return bool
	 */
	private static function has_connection_error() {
		if ( ! class_exists( Connection_Error_Handler::class ) || ! method_exists( Connection_Error_Handler::class, 'get_displayable_errors' ) ) {
			return false;
		}
		return ! empty( Connection_Error_Handler::get_instance()->get_displayable_errors() );
	}

	/**
	 * Enqueue the notification bubble script.
	 * Fetches fresh alert data via REST API without blocking page load.
	 *
	 * @return void
	 */
	public static function enqueue_red_bubble_script() {
		Assets::register_script(
			'my-jetpack-notification-bubble',
			'../build/async-notification-bubble.js',
			__FILE__,
			array(
				'enqueue'   => true,
				'in_footer' => true,
			)
		);
	}

	/**
	 * Get list of module names sorted by their recommendation score
	 *
	 * @return array|null
	 */
	public static function get_recommended_modules() {
		$recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );

		if ( empty( $recommendations_evaluation ) || ! is_array( $recommendations_evaluation ) ) {
			return null;
		}

		arsort( $recommendations_evaluation ); // Sort by scores in descending order

		return array_keys( $recommendations_evaluation ); // Get only module names
	}
}

```
