Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.44% covered (warning)
85.44%
745 / 872
74.07% covered (warning)
74.07%
60 / 81
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
85.44% covered (warning)
85.44%
745 / 872
74.07% covered (warning)
74.07%
60 / 81
609.80
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
41 / 41
100.00% covered (success)
100.00%
1 / 1
7
 use_local_module_options
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
6.05
 restore_module_options
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 is_licensing_ui_enabled
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 add_my_jetpack_menu_item
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
4
 current_user_can_access_page
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 admin_init
85.71% covered (warning)
85.71%
12 / 14
0.00% covered (danger)
0.00%
0 / 1
6.10
 is_onboarding_settled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 maybe_redirect_to_onboarding
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 get_onboarding_redirect_args_for_step
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 is_onboarding_available
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_partner_coupon_screen
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
8
 get_onboarding_redirect_args
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
12
 silence_onboarding_notices
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 hide_onboarding_jitms
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 add_onboarding_admin_body_class
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 can_use_analytics
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 is_onboarding_wizard_enabled
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 has_never_registered_jetpack
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_onboarding_wizard_state
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 is_my_jetpack_admin_request
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 is_onboarding_request
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 is_onboarding_takeover
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 alias_screen_id_for_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 restore_screen_id_after_wp_build
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 should_load_wp_build
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 should_render_wp_build
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 maybe_load_wp_build
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
4.94
 load_wp_build
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 add_admin_shell_member
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
20
 load_as_admin_shell_guest
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 require_wp_build_with_screen_alias
75.00% covered (warning)
75.00%
9 / 12
0.00% covered (danger)
0.00%
0 / 1
2.06
 enqueue_scripts
97.01% covered (success)
97.01%
130 / 134
0.00% covered (danger)
0.00%
0 / 1
12
 get_header_state
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_plan_urls
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 add_script_data
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 is_modules_rest_api_enabled
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 get_modules_management_url
51.43% covered (warning)
51.43%
36 / 70
0.00% covered (danger)
0.00%
0 / 1
244.13
 print_modules_fallback
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
10
 get_products_section
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 add_admin_script_data
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
8
 get_registered_admin_page_slugs
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 is_admin_page_available
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_assets_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_installed_jetpack_plugins
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 get_active_modules
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 is_jetpack_user_new
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
56
 register_feature_flags
100.00% covered (success)
100.00%
50 / 50
100.00% covered (success)
100.00%
1 / 1
2
 is_header_controls_enabled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 maybe_enqueue_header_controls_script
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 get_my_jetpack_flags
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 is_overview_v1_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_whats_new_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 host_shows_my_jetpack
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_settings_consolidation_on_for_site
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_settings_consolidation_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 shows_settings_notices
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 get_settings_notices_state
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 register_settings_panel_urls
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 resolve_settings_url
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_settings_panel_url
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 is_modules_to_features_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_seo_opt_in_state
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 admin_page
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 register_rest_endpoints
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
3
 permissions_callback
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 should_initialize
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
7
 is_offline_features_enabled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 setup_historically_active_jetpack_modules_sync
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 get_site
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 get_site_info
58.33% covered (warning)
58.33%
7 / 12
0.00% covered (danger)
0.00%
0 / 1
5.16
 is_commercial_site
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 is_registered
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 dismiss_welcome_banner
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 has_file_system_write_access
61.11% covered (warning)
61.11%
11 / 18
0.00% covered (danger)
0.00%
0 / 1
8.12
 get_idc_container_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 maybe_show_red_bubble
96.23% covered (success)
96.23%
51 / 53
0.00% covered (danger)
0.00%
0 / 1
12
 has_connection_error
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 get_alerts_counted_elsewhere
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 enqueue_red_bubble_script
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
 get_recommended_modules
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * WP Admin page with information and configuration shared among all Jetpack stand-alone plugins
4 *
5 * @package automattic/my-jetpack
6 */
7
8namespace Automattic\Jetpack\My_Jetpack;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Admin_UI\Admin_Shell;
12use Automattic\Jetpack\Assets;
13use Automattic\Jetpack\Boost_Speed_Score\Speed_Score;
14use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_History;
15use Automattic\Jetpack\Connection\Client;
16use Automattic\Jetpack\Connection\Error_Handler as Connection_Error_Handler;
17use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
18use Automattic\Jetpack\Connection\Manager as Connection_Manager;
19use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
20use Automattic\Jetpack\Connection\REST_Jetpack_AI_JWT;
21use Automattic\Jetpack\Constants as Jetpack_Constants;
22use Automattic\Jetpack\CookieState;
23use Automattic\Jetpack\ExPlat;
24use Automattic\Jetpack\Feature_Flags\Feature_Flags;
25use Automattic\Jetpack\JITMS\JITM;
26use Automattic\Jetpack\Licensing;
27use Automattic\Jetpack\Menu_Badges\Menu_Badges;
28use Automattic\Jetpack\Menu_Badges\Notification_Counts;
29use Automattic\Jetpack\Modules;
30use Automattic\Jetpack\Partner_Coupon;
31use Automattic\Jetpack\Plugins_Installer;
32use Automattic\Jetpack\Status;
33use Automattic\Jetpack\Status\Host as Status_Host;
34use Automattic\Jetpack\Sync\Functions as Sync_Functions;
35use Automattic\Jetpack\Terms_Of_Service;
36use Automattic\Jetpack\Tracking;
37use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
38use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
39use Jetpack;
40use WP_Error;
41
42/**
43 * The main Initializer class that registers the admin menu and eneuque the assets.
44 */
45class Initializer {
46
47    /**
48     * My Jetpack package version
49     *
50     * @var string
51     */
52    const PACKAGE_VERSION = '6.19.0';
53
54    /**
55     * Feature flag that swaps the single-screen onboarding takeover for the setup wizard.
56     */
57    const ONBOARDING_WIZARD_FEATURE_FLAG = 'my-jetpack-onboarding-wizard';
58
59    /**
60     * User option recording that this user chose to skip setup.
61     *
62     * Per user rather than per site, because skipping is one person saying "not
63     * now": a second admin arriving at a site nobody has set up should still be
64     * offered the flow. Finishing it is the site-wide fact, and that is
65     * ONBOARDING_COMPLETED_OPTION.
66     *
67     * A user option rather than plain user meta: `wp_usermeta` is network-wide, so
68     * without the blog prefix a skip on one site would silence setup on all of them.
69     */
70    const ONBOARDING_DISMISSED_USER_OPTION = 'jetpack_my_jetpack_onboarding_dismissed';
71
72    /**
73     * Option recording that someone has finished setup on this site.
74     *
75     * Site-wide, because the flow connects the site and switches modules on, so a
76     * second admin does not need it again. Deliberately not autoloaded.
77     */
78    const ONBOARDING_COMPLETED_OPTION = 'jetpack_my_jetpack_onboarding_completed';
79
80    /**
81     * Handle for the classic script that carries the React initial state.
82     *
83     * Plugins that render My Jetpack components on their own pages (Boost) depend on this name.
84     */
85    const DATA_SCRIPT_HANDLE = 'my_jetpack_main_app';
86
87    /**
88     * Handle for the webpack bundle that renders the onboarding takeover.
89     */
90    const ONBOARDING_SCRIPT_HANDLE = 'my_jetpack_onboarding';
91
92    /**
93     * Handle for the webpack bundle that gives dashboards outside My Jetpack the shared header's controls.
94     */
95    const HEADER_CONTROLS_SCRIPT_HANDLE = 'my-jetpack-header-controls';
96
97    /**
98     * The wp-build page ID, which the generated enqueue check expects as the screen ID.
99     */
100    const WP_BUILD_PAGE_ID = 'my-jetpack-dashboard';
101
102    /**
103     * HTML container ID for the IDC screen on My Jetpack page.
104     */
105    private const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
106
107    public const JETPACK_PLUGIN_SLUGS = array(
108        'jetpack-backup',
109        'jetpack-boost',
110        'zerobscrm',
111        'jetpack',
112        'jetpack-protect',
113        'jetpack-social',
114        'jetpack-videopress',
115        'jetpack-search',
116        'jetpack-stats',
117    );
118
119    private const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
120
121    /**
122     * Feature flag for connecting the WordPress.com account from a Features card that needs one.
123     *
124     * @var string
125     */
126    public const ACCOUNT_CONNECT_FLAG = 'my-jetpack-account-connect';
127
128    /**
129     * Feature flag for the shared header's global controls.
130     *
131     * @var string
132     */
133    public const HEADER_CONTROLS_FLAG = 'my-jetpack-header-controls';
134
135    /**
136     * Feature flag for Overview v1.
137     *
138     * @var string
139     */
140    public const OVERVIEW_V1_FLAG = 'my-jetpack-overview-v1';
141
142    /**
143     * Feature flag for What's new, shared by every Jetpack product that shows it.
144     *
145     * @var string
146     */
147    public const WHATS_NEW_FLAG = 'jetpack-whats-new';
148
149    /**
150     * Feature flag for sending classic Modules links to Features.
151     *
152     * @var string
153     */
154    public const MODULES_TO_FEATURES_FLAG = 'my-jetpack-modules-to-features';
155
156    /**
157     * Feature flag for consolidating settings in My Jetpack instead of the Settings screen.
158     *
159     * @var string
160     */
161    public const SETTINGS_CONSOLIDATION_FLAG = 'my-jetpack-settings-consolidation';
162
163    /**
164     * Modules whose Jetpack settings link opens in the Features panel. A subset of `moduleSettings` in `settings-panel/registry.ts`; see there for which modules stay out.
165     */
166    public const SETTINGS_PANEL_MODULES = array( 'carousel', 'comments', 'infinite-scroll', 'markdown', 'post-by-email', 'related-posts' );
167
168    /**
169     * Holds info/data about the site (from the /sites/%d endpoint)
170     *
171     * @var object
172     */
173    public static $site_info;
174
175    /**
176     * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
177     *
178     * @var string|null
179     */
180    private static $wp_build_original_screen_id = null;
181
182    /**
183     * Initialize My Jetpack
184     *
185     * @return void
186     */
187    public static function init() {
188        self::register_feature_flags();
189
190        // Before the gate: the Jetpack plugin renders this package's connection screen and footer
191        // links even where My Jetpack is off, and `myJetpackInitialState` only exists on its own page.
192        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_admin_script_data' ) );
193        add_action( 'admin_head', array( __CLASS__, 'print_modules_fallback' ) );
194
195        if ( ! self::should_initialize() || did_action( 'my_jetpack_init' ) ) {
196            return;
197        }
198
199        if ( self::is_offline_features_enabled() ) {
200            add_filter( 'jetpack_my_jetpack_should_enable_add_license_screen', '__return_false' );
201            Connection_Rest_Authentication::init();
202            add_filter( 'rest_request_before_callbacks', array( __CLASS__, 'use_local_module_options' ), 10, 3 );
203            add_filter( 'rest_request_after_callbacks', array( __CLASS__, 'restore_module_options' ), 10, 3 );
204            add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );
205            add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
206            add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );
207            do_action( 'my_jetpack_init' );
208            return;
209        }
210
211        // Answer "is this product on?" for admin menu registration.
212        Menu_Visibility::init();
213        Turned_Off_Page::init();
214
215        // What My Jetpack publishes on the What's new surface it hosts.
216        Whats_New::init();
217
218        self::register_settings_panel_urls();
219
220        // Extend jetpack plugins action links.
221        Products::extend_plugins_action_links();
222
223        // Set up the REST authentication hooks.
224        Connection_Rest_Authentication::init();
225
226        if ( self::is_licensing_ui_enabled() ) {
227            Licensing::instance()->initialize();
228        }
229
230        // Initialize Boost Speed Score
231        new Speed_Score( array(), 'jetpack-my-jetpack' );
232
233        // Add custom WP REST API endoints.
234        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );
235
236        // Both of wp-build's deadlines fall later in this request: its enqueue check must be
237        // hooked before `admin_enqueue_scripts`, and its render function defined before
238        // the page callback.
239        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
240
241        add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );
242
243        if ( class_exists( Admin_Shell::class ) ) {
244            add_filter( 'jetpack_admin_shell_members', array( __CLASS__, 'add_admin_shell_member' ) );
245            // Standalone plugins reach admin-ui only through the admin menu, which admin-ajax never builds.
246            if ( method_exists( Admin_Shell::class, 'init' ) ) {
247                Admin_Shell::init();
248            }
249        }
250
251        add_action( 'admin_init', array( __CLASS__, 'setup_historically_active_jetpack_modules_sync' ) );
252
253        // Not on admin_init: modules are usually toggled over REST, where admin_init never fires.
254        add_action( 'jetpack_activate_module', array( Historically_Active_Modules::class, 'expire_refresh' ) );
255        add_action( 'jetpack_deactivate_module', array( Historically_Active_Modules::class, 'expire_refresh' ) );
256
257        // Nothing else gets to talk over the takeover. See both methods for why it
258        // takes two hooks rather than one.
259        add_action( 'in_admin_header', array( __CLASS__, 'silence_onboarding_notices' ), PHP_INT_MAX );
260        add_filter( 'jetpack_display_jitms_on_screen', array( __CLASS__, 'hide_onboarding_jitms' ), 10, 2 );
261        // Registered on admin_menu (not admin_init) and well before priority 100000, so the
262        // counts it registers exist before the menu-badges renderer runs on admin_menu 100000.
263        add_action( 'admin_menu', array( __CLASS__, 'maybe_show_red_bubble' ), 30 );
264
265        // Set up the ExPlat package endpoints
266        ExPlat::init();
267
268        // Sets up JITMS.
269        JITM::configure();
270
271        // Track whether the user is an agency, for the Automattic for Agencies banner.
272        Jetpack_Manage::init();
273
274        /**
275         * Fires after the My Jetpack package is initialized
276         *
277         * @since 0.1.0
278         */
279        do_action( 'my_jetpack_init' );
280    }
281
282    /**
283     * Keep uncached module-list options local on the offline route.
284     *
285     * @since 6.10.0
286     * @param mixed            $response Response before the callback.
287     * @param array            $handler  Route handler.
288     * @param \WP_REST_Request $request  REST request.
289     * @return mixed
290     */
291    public static function use_local_module_options( $response, $handler, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- WordPress REST filter signature.
292        if ( '/jetpack/v4/module/all' === $request->get_route() ) {
293            // Keep module activation editable when the standalone plugin is not running;
294            // a stale autoloaded VideoPress class can still attach its forcing filter.
295            if ( ! Jetpack_Constants::is_defined( 'JETPACK_VIDEOPRESS_ROOT_FILE' )
296                && ! Products\Videopress::is_standalone_plugin_active()
297                && remove_filter( 'jetpack_active_modules', array( \Automattic\Jetpack\VideoPress\Module_Control::class, 'add_videopress_to_array' ) )
298                && class_exists( 'Jetpack_Modules_Overrides', false )
299            ) {
300                \Jetpack_Modules_Overrides::instance()->clear_cache();
301            }
302            add_filter( 'default_option_monitor_receive_notifications', '__return_false' );
303            add_filter( 'default_option_post_by_email_address' . get_current_user_id(), '__return_false' );
304        }
305        return $response;
306    }
307
308    /**
309     * Restore normal option reads after the offline module-list callback.
310     *
311     * @since 6.10.0
312     * @param mixed            $response Response after the callback.
313     * @param array            $handler  Route handler.
314     * @param \WP_REST_Request $request  REST request.
315     * @return mixed
316     */
317    public static function restore_module_options( $response, $handler, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- WordPress REST filter signature.
318        if ( '/jetpack/v4/module/all' === $request->get_route() ) {
319            remove_filter( 'default_option_monitor_receive_notifications', '__return_false' );
320            remove_filter( 'default_option_post_by_email_address' . get_current_user_id(), '__return_false' );
321        }
322        return $response;
323    }
324
325    /**
326     * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
327     *
328     * @since 1.2.0
329     *
330     * @return boolean
331     */
332    public static function is_licensing_ui_enabled() {
333        // Default changed to true in 1.5.0.
334        $is_enabled = true;
335
336        /*
337         * Bail if My Jetpack is not enabled,
338         * and thus the licensing UI shouldn't be enabled either.
339         */
340        if ( ! self::should_initialize() ) {
341            $is_enabled = false;
342        }
343
344        /**
345         * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
346         *
347         * @param bool $is_enabled Defaults to true.
348         *
349         * @since 1.2.0
350         * @since 1.5.0 Update default value to true.
351         */
352        return apply_filters(
353            'jetpack_my_jetpack_should_enable_add_license_screen',
354            $is_enabled
355        );
356    }
357
358    /**
359     * Add My Jetpack menu item to the admin menu.
360     *
361     * @return void
362     */
363    public static function add_my_jetpack_menu_item() {
364        if ( self::is_offline_features_enabled() && ! self::current_user_can_access_page() ) {
365            return;
366        }
367
368        $position    = defined( Admin_Menu::class . '::POSITION_FIRST' ) ? Admin_Menu::POSITION_FIRST : -10;
369        $menu_slug   = 'my-jetpack';
370        $page_suffix = Admin_Menu::add_menu(
371            __( 'My Jetpack', 'jetpack-my-jetpack' ),
372            __( 'My Jetpack', 'jetpack-my-jetpack' ),
373            'edit_posts',
374            $menu_slug,
375            array( __CLASS__, 'admin_page' ),
376            $position
377        );
378        add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
379        // Users who can edit posts but have no Jetpack menu get an admin_page_ hook instead.
380        add_action( 'load-admin_page_' . $menu_slug, array( __CLASS__, 'admin_init' ) );
381    }
382
383    /**
384     * Whether the current user may access the page selected by My Jetpack.
385     *
386     * @since 6.10.0
387     * @return bool
388     */
389    public static function current_user_can_access_page() {
390        return current_user_can( 'edit_posts' )
391            && ( ! self::is_offline_features_enabled() || REST_Main_Features::permissions_callback() );
392    }
393
394    /**
395     * Callback for the load my jetpack page hook.
396     *
397     * @return void
398     */
399    public static function admin_init() {
400        // Read the Jetpack state before any output: reading it deletes its cookie.
401        if ( self::shows_settings_notices() ) {
402            ( new CookieState() )->state();
403        }
404
405        if ( self::is_offline_features_enabled() ) {
406            if ( ! self::current_user_can_access_page() ) {
407                wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'jetpack-my-jetpack' ), 403 );
408            }
409            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
410            return;
411        }
412
413        self::maybe_redirect_to_onboarding();
414
415        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No nonce needed for redirect flow control
416        $step = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';
417
418        // If the user reaches the onboarding page, add a class to the body
419        if ( $step === 'onboarding' ) {
420            add_filter( 'admin_body_class', array( __CLASS__, 'add_onboarding_admin_body_class' ) );
421        }
422
423        self::$site_info = self::get_site_info();
424        add_filter( 'identity_crisis_container_id', array( static::class, 'get_idc_container_id' ) );
425        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
426    }
427
428    /**
429     * Whether this user has already settled setup, one way or the other.
430     *
431     * Two separate facts. Finishing is site-wide: the wizard connects the site and
432     * switches modules on, so once it is done nobody needs the takeover again.
433     * Skipping is this person saying "not now", and it must not answer for the next
434     * admin who arrives at a site nobody has set up.
435     *
436     * @internal Not part of the package's public API.
437     *
438     * @return bool
439     */
440    public static function is_onboarding_settled() {
441        if ( get_option( self::ONBOARDING_COMPLETED_OPTION, false ) ) {
442            return true;
443        }
444
445        return (bool) get_user_option( self::ONBOARDING_DISMISSED_USER_OPTION );
446    }
447
448    /**
449     * Send the user into setup when they land on My Jetpack without one.
450     *
451     * Runs from My Jetpack's own page load, which nothing but a request for that page
452     * reaches and which fires before any output, so it needs no guards of its own.
453     *
454     * @return void
455     */
456    public static function maybe_redirect_to_onboarding() {
457        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No nonce needed for redirect flow control
458        $step          = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';
459        $redirect_args = self::get_onboarding_redirect_args_for_step( $step );
460
461        if ( null === $redirect_args ) {
462            return;
463        }
464
465        $location = wp_sanitize_redirect( add_query_arg( $redirect_args, admin_url( 'admin.php' ) ) );
466
467        // Remove wp_get_referer filter applied in `fix_redirect` method of `Jetpack_Admin` class
468        remove_filter( 'wp_redirect', 'wp_get_referer' );
469        wp_safe_redirect( $location );
470
471        exit( 0 );
472    }
473
474    /**
475     * Get the setup redirect for the current user and site at the requested step.
476     *
477     * @param string $step The requested setup step, or empty for the dashboard.
478     * @return array|null Query args for the redirect, or null to stay on the page.
479     */
480    private static function get_onboarding_redirect_args_for_step( $step ) {
481        $wizard_enabled = self::is_onboarding_wizard_enabled();
482        $connection     = new Connection_Manager();
483
484        // Only the wizard connects a user, so only it may count a site-only connection as
485        // unfinished setup. The single screen can only register the site, so asking it for
486        // an owner leaves that site on a screen with no way back out.
487        $connection_done = $wizard_enabled ? $connection->has_connected_owner() : $connection->is_connected();
488
489        // Onboarding's only action is the connect request, which answers a user
490        // without `jetpack_connect` with a 403.
491        return self::get_onboarding_redirect_args(
492            $step,
493            $connection_done,
494            self::is_onboarding_available() && current_user_can( 'jetpack_connect' ),
495            $wizard_enabled,
496            // Only the wizard records a settled run, and only a registered site may act on one:
497            // My Jetpack requires the site connection that accepting the terms creates.
498            $wizard_enabled && $connection->is_connected() && self::is_onboarding_settled()
499        );
500    }
501
502    /**
503     * Whether the My Jetpack onboarding flow is available on this site.
504     *
505     * WordPress.com Simple sites are connected by definition and don't manage their
506     * connection through My Jetpack, so the onboarding flow (which asks the user to
507     * connect) never applies there. A pending partner coupon brings its own connect screen.
508     *
509     * @internal Not part of the package's public API.
510     *
511     * @return bool
512     */
513    public static function is_onboarding_available() {
514        if ( self::is_offline_features_enabled() ) {
515            return false;
516        }
517        return ! ( new Status_Host() )->is_wpcom_simple() && null === self::get_partner_coupon_screen();
518    }
519
520    /**
521     * The partner coupon screen's data, when it should replace the dashboard.
522     *
523     * Coupons exist only with the Jetpack plugin, which supplies their products and images.
524     *
525     * @since 6.5.0
526     *
527     * @return array{coupon: array, assetBaseUrl: string}|null
528     */
529    public static function get_partner_coupon_screen() {
530        if (
531            self::is_offline_features_enabled()
532            || ! self::should_initialize()
533            || ! current_user_can( 'manage_options' )
534            || ! Jetpack_Constants::is_defined( 'JETPACK__PLUGIN_FILE' )
535        ) {
536            return null;
537        }
538
539        $coupon = Partner_Coupon::get_coupon();
540        if ( ! $coupon ) {
541            return null;
542        }
543
544        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks which screen renders.
545        if ( ! isset( $_GET['showCouponRedemption'] ) && ( new Connection_Manager() )->has_connected_owner() ) {
546            return null;
547        }
548
549        return array(
550            'coupon'       => $coupon,
551            'assetBaseUrl' => plugins_url( '', Jetpack_Constants::get_constant( 'JETPACK__PLUGIN_FILE' ) ),
552        );
553    }
554
555    /**
556     * Decide whether the current My Jetpack request should redirect, and where to.
557     *
558     * @internal Not part of the package's public API.
559     *
560     * @param string $step                 The current `step` query param.
561     * @param bool   $connection_done      Whether the connection the takeover asks for is in place:
562     *                                     a connected owner with the wizard, a connected site without it.
563     * @param bool   $onboarding_available Whether the onboarding flow is available on this site.
564     * @param bool   $wizard_enabled       Whether the takeover renders the setup wizard.
565     * @param bool   $is_settled           Whether this user has already finished or skipped setup.
566     * @return array|null Query args for the redirect, or null to stay on the current page.
567     */
568    public static function get_onboarding_redirect_args( $step, $connection_done, $onboarding_available, $wizard_enabled = false, $is_settled = false ) {
569        /*
570         * Only the automatic redirect is suppressed once setup is settled. Asking for
571         * the onboarding page by its own URL still works, so someone who skipped can
572         * go back to it, and so can a second admin the site-wide flag does not cover.
573         */
574        if ( $onboarding_available && ! $connection_done && ! $is_settled && $step !== 'onboarding' ) {
575            // The connection setup asks for is not in place, so setup is unfinished.
576            return array(
577                'page' => 'my-jetpack',
578                'step' => 'onboarding',
579            );
580        }
581
582        // The wizard connects mid-flow: the user authorizes on WordPress.com and is sent
583        // back here to finish setup, so arriving connected is not the same as finishing.
584        if ( $step === 'onboarding' && $connection_done && $onboarding_available && $wizard_enabled ) {
585            return null;
586        }
587
588        if ( $step === 'onboarding' && ( ! $onboarding_available || $connection_done ) ) {
589            // Nothing left to set up here, or onboarding does not apply on this site.
590            return array( 'page' => 'my-jetpack' );
591        }
592
593        return null;
594    }
595
596    /**
597     * Empty the notice channels while the takeover is on screen.
598     *
599     * The takeover hides `.notice`, `.error` and `.updated` in CSS, which only
600     * catches notices that use WordPress's own classes. Plenty do not, and a plugin
601     * announcing itself in its own markup lands on top of a full-screen flow that
602     * has no way to scroll past it.
603     *
604     * On `in_admin_header`, the last hook before `admin-header.php` prints notices,
605     * so a notice registered late is caught too.
606     *
607     * @return void
608     */
609    public static function silence_onboarding_notices() {
610        if ( ! self::is_onboarding_request() ) {
611            return;
612        }
613
614        remove_all_actions( 'admin_notices' );
615        remove_all_actions( 'all_admin_notices' );
616        remove_all_actions( 'network_admin_notices' );
617        remove_all_actions( 'user_admin_notices' );
618    }
619
620    /**
621     * Keep Just In Time Messages off the takeover.
622     *
623     * Emptying the notice channels above would also drop the JITM, since that is how
624     * it renders, but only after it has enqueued its script and stylesheet. This is
625     * the package's own opt-out and it runs before any of that.
626     *
627     * The screen id cannot answer this on its own: the takeover and the My Jetpack
628     * dashboard are the same screen, and only the query arg separates them.
629     *
630     * @param bool   $show      Whether to show JITMs on this screen.
631     * @param string $screen_id The current screen's id.
632     * @return bool
633     */
634    public static function hide_onboarding_jitms( $show, $screen_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Required by the filter signature.
635        return self::is_onboarding_request() ? false : $show;
636    }
637
638    /**
639     * Add a body class to the My Jetpack onboarding page.
640     * This class hides the WP Admin toolbar and the sidebar menu.
641     *
642     * @param string $classes The body classes.
643     * @return string The modified body classes.
644     */
645    public static function add_onboarding_admin_body_class( $classes ) {
646        $classes .= ' jetpack-admin-full-screen';
647        return $classes;
648    }
649
650    /**
651     * Returns whether we are in condition to track to use
652     * Analytics functionality like Tracks, MC, or GA.
653     */
654    public static function can_use_analytics() {
655        $status     = new Status();
656        $connection = new Connection_Manager();
657        $tracking   = new Tracking( 'jetpack', $connection );
658
659        return $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
660    }
661
662    /**
663     * Whether the onboarding takeover renders the setup wizard.
664     *
665     * Self-hosted only. On WordPress.com the platform owns the connection and nobody chose
666     * to install Jetpack, so a screen inviting them to start with it and connect an account
667     * does not apply. `is_wpcom_platform()` covers Simple and WordPress.com on Atomic, and
668     * requires wpcomsh, so other Atomic-hosted products still count as self-hosted here.
669     *
670     * @since 6.11.0
671     *
672     * @return bool
673     */
674    public static function is_onboarding_wizard_enabled() {
675        if ( ( new Status_Host() )->is_wpcom_platform() ) {
676            return false;
677        }
678
679        if ( ! Feature_Flags::is_enabled( self::ONBOARDING_WIZARD_FEATURE_FLAG ) ) {
680            return false;
681        }
682
683        // The wizard registers the site at its own first step, which writes the marker
684        // below, so asking again on the way back from WordPress.com would drop someone
685        // out of a run already under way.
686        if ( ( new Connection_Manager() )->is_connected() ) {
687            return true;
688        }
689
690        return self::has_never_registered_jetpack();
691    }
692
693    /**
694     * Whether the Jetpack plugin has never registered this site.
695     *
696     * `unique_registrations` is written on `jetpack_site_registered` by the Jetpack plugin
697     * alone, so a site that has only ever run a standalone plugin still reads as new here.
698     *
699     * @internal Not part of the package's public API.
700     *
701     * @since 6.11.0
702     *
703     * @return bool
704     */
705    public static function has_never_registered_jetpack() {
706        return ! \Jetpack_Options::get_option( 'unique_registrations' );
707    }
708
709    /**
710     * The wizard's configuration, or null while the takeover stays on its single screen.
711     *
712     * @since 6.11.0
713     *
714     * @return array{exitUrl: string, dashboardUrl: string}|null
715     */
716    public static function get_onboarding_wizard_state() {
717        if ( ! self::is_onboarding_wizard_enabled() ) {
718            return null;
719        }
720
721        return array(
722            // Where skipping the wizard lands: the admin menu is hidden, so leaving is always one click.
723            'exitUrl'      => admin_url( 'admin.php?page=my-jetpack' ),
724            // Where leaving Jetpack altogether lands: wp-admin's own dashboard.
725            'dashboardUrl' => admin_url(),
726        );
727    }
728
729    /**
730     * Whether the current request targets the My Jetpack admin page.
731     *
732     * @since 6.3.0
733     *
734     * @return bool
735     */
736    public static function is_my_jetpack_admin_request() {
737        if ( ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
738            return false;
739        }
740
741        return sanitize_text_field( wp_unslash( $_GET['page'] ) ) === 'my-jetpack'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
742    }
743
744    /**
745     * Whether the current request is the full-viewport onboarding takeover.
746     *
747     * Onboarding hides all wp-admin chrome and never renders through wp-build. The page
748     * is part of the question: `in_admin_header` and the JITM filter run everywhere.
749     *
750     * @since 6.3.0
751     *
752     * @return bool
753     */
754    public static function is_onboarding_request() {
755        if ( ! self::is_my_jetpack_admin_request() ) {
756            return false;
757        }
758
759        if ( ! isset( $_GET['step'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
760            return false;
761        }
762
763        return sanitize_text_field( wp_unslash( $_GET['step'] ) ) === 'onboarding'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
764    }
765
766    /**
767     * Whether this request is the onboarding takeover rather than the dashboard.
768     *
769     * Loading wp-build, enqueueing scripts and rendering the page must all agree,
770     * so they share this one expression.
771     *
772     * @since 6.3.0
773     *
774     * @return bool
775     */
776    public static function is_onboarding_takeover() {
777        return self::is_onboarding_request() && self::is_onboarding_available();
778    }
779
780    /**
781     * Alias the screen ID to satisfy wp-build's generated enqueue check.
782     *
783     * @since 6.3.0
784     *
785     * @return void
786     */
787    public static function alias_screen_id_for_wp_build() {
788        $screen = get_current_screen();
789
790        if ( ! $screen ) {
791            return;
792        }
793
794        self::$wp_build_original_screen_id = $screen->id;
795        $screen->id                        = self::WP_BUILD_PAGE_ID;
796    }
797
798    /**
799     * Undo alias_screen_id_for_wp_build(), since JITM builds its message path from the screen ID.
800     *
801     * @since 6.3.0
802     *
803     * @return void
804     */
805    public static function restore_screen_id_after_wp_build() {
806        $screen = get_current_screen();
807
808        if ( ! $screen || null === self::$wp_build_original_screen_id ) {
809            return;
810        }
811
812        $screen->id                        = self::$wp_build_original_screen_id;
813        self::$wp_build_original_screen_id = null;
814    }
815
816    /**
817     * Whether this request should load wp-build at all.
818     *
819     * Also what keeps WP_Build_Polyfills from replacing core scripts on every other admin page.
820     *
821     * @since 6.3.0
822     *
823     * @return bool
824     */
825    public static function should_load_wp_build() {
826        return self::is_my_jetpack_admin_request() && ! self::is_onboarding_takeover();
827    }
828
829    /**
830     * Whether this request renders the dashboard through wp-build.
831     *
832     * The generated render function is missing where the package was never built.
833     *
834     * @since 6.3.0
835     *
836     * @return bool
837     */
838    public static function should_render_wp_build() {
839        return ! self::is_onboarding_takeover()
840            && function_exists( 'jetpack_my_jetpack_my_jetpack_dashboard_wp_admin_render_page' );
841    }
842
843    /**
844     * Load wp-build for the My Jetpack dashboard.
845     *
846     * @since 6.3.0
847     *
848     * @return void
849     */
850    public static function maybe_load_wp_build() {
851        if ( ! self::should_load_wp_build() ) {
852            return;
853        }
854
855        $build_index = dirname( __DIR__ ) . '/build/build.php';
856
857        if ( file_exists( $build_index ) ) {
858            self::load_wp_build( $build_index );
859        }
860    }
861
862    /**
863     * Require the generated wp-build index and wire it into this request.
864     *
865     * @since 6.3.0
866     *
867     * @param string $build_index Path to the generated `build.php`.
868     * @return void
869     */
870    public static function load_wp_build( $build_index ) {
871        self::require_wp_build_with_screen_alias( $build_index );
872
873        // wp-build hooks module registration to wp_default_scripts, which has
874        // already fired by admin_menu â€” call it directly or the init module
875        // never reaches the import map.
876        if ( function_exists( 'jetpack_my_jetpack_register_script_modules' ) ) {
877            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.
878        }
879
880        WP_Build_Polyfills::register(
881            'my-jetpack',
882            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
883        );
884    }
885
886    /**
887     * Register My Jetpack with the admin shell, which switches between Jetpack dashboards without a page load.
888     *
889     * @since 6.18.0
890     *
891     * @param array $members Shell members keyed by admin page slug.
892     * @return array
893     */
894    public static function add_admin_shell_member( $members ) {
895        // A site that still needs onboarding is redirected to the takeover, which isn't a wp-build page.
896        if ( ! self::current_user_can_access_page() || ! file_exists( dirname( __DIR__ ) . '/build/build.php' ) || null !== self::get_onboarding_redirect_args_for_step( '' ) ) {
897            return $members;
898        }
899
900        $members['my-jetpack'] = array(
901            'build_prefix' => 'jetpack_my_jetpack',
902            'build_page'   => self::WP_BUILD_PAGE_ID,
903            'init_modules' => array( '@jetpack-my-jetpack/init' ),
904            'title'        => 'My Jetpack',
905            'header'       => array(
906                'title'    => 'Jetpack',
907                'subtitle' => '',
908            ),
909            'capability'   => 'edit_posts',
910            'handles'      => array( 'my_jetpack_main_app', 'my_jetpack_ai_app', 'jetpack-script-data', 'jetpack-connection', 'my-jetpack-header-controls', 'wp-jp-i18n-loader' ),
911            'load'         => array( __CLASS__, 'load_as_admin_shell_guest' ),
912        );
913        return $members;
914    }
915
916    /**
917     * Ready My Jetpack's routes and page data while another dashboard's page is open.
918     *
919     * Skips the screen ID alias: on another page it would make the generated enqueue boot a second app.
920     *
921     * @since 6.18.0
922     *
923     * @return void
924     */
925    public static function load_as_admin_shell_guest() {
926        require_once dirname( __DIR__ ) . '/build/build.php';
927
928        if ( function_exists( 'jetpack_my_jetpack_register_script_modules' ) ) {
929            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.
930        }
931        WP_Build_Polyfills::register(
932            'my-jetpack',
933            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
934        );
935
936        // On the host page the shell removes this again; the guest endpoint runs it.
937        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
938    }
939
940    /**
941     * Require the generated build file with the screen ID aliased across its enqueue check.
942     *
943     * @see WP_Build_Screen_Id::load_with_alias()
944     * @param string $build_index Path to the generated `build.php`.
945     * @return void
946     */
947    private static function require_wp_build_with_screen_alias( $build_index ) {
948        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
949        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
950            WP_Build_Screen_Id::load_with_alias(
951                array( __CLASS__, 'alias_screen_id_for_wp_build' ),
952                array( __CLASS__, 'restore_screen_id_after_wp_build' ),
953                function () use ( $build_index ) {
954                    require_once $build_index;
955                }
956            );
957            return;
958        }
959
960        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
961        require_once $build_index;
962        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
963    }
964
965    /**
966     * Enqueue admin page assets.
967     *
968     * @return void
969     */
970    public static function enqueue_scripts() {
971        if ( self::is_offline_features_enabled() ) {
972            $data_handle = self::DATA_SCRIPT_HANDLE;
973            wp_register_script( $data_handle, false, array(), self::PACKAGE_VERSION, true );
974            wp_enqueue_script( $data_handle );
975            add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );
976            wp_localize_script(
977                $data_handle,
978                'myJetpackInitialState',
979                array(
980                    'isOfflineFeatures'     => true,
981                    'products'              => array( 'items' => array() ),
982                    'adminUrl'              => esc_url( admin_url() ),
983                    'assetsUrl'             => self::get_assets_url(),
984                    'isJetpackPluginActive' => class_exists( 'Jetpack' ),
985                    'hiddenFeatures'        => Feature_Visibility::get_hidden(),
986                    'deprecatedModules'     => Feature_Visibility::get_deprecated_modules(),
987                    'myJetpackFlags'        => self::get_my_jetpack_flags(),
988                )
989            );
990            wp_localize_script(
991                $data_handle,
992                'myJetpackRest',
993                array(
994                    'apiRoot'  => esc_url_raw( rest_url() ),
995                    'apiNonce' => wp_create_nonce( 'wp_rest' ),
996                )
997            );
998            if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
999                wp_enqueue_script( 'wp-jp-i18n-loader' );
1000            }
1001            self::maybe_enqueue_header_controls_script();
1002            return;
1003        }
1004
1005        /**
1006         * Fires after the My Jetpack page is initialized.
1007         * Allows for enqueuing additional scripts only on the My Jetpack page.
1008         *
1009         * @since 4.35.7
1010         */
1011        do_action( 'myjetpack_enqueue_scripts' );
1012        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );
1013
1014        // Script-less: it only prints the state below, before the dashboard's boot runs on DOMContentLoaded.
1015        $data_handle = self::DATA_SCRIPT_HANDLE;
1016        wp_register_script( $data_handle, false, array(), self::PACKAGE_VERSION, true );
1017        wp_enqueue_script( $data_handle );
1018        self::maybe_enqueue_header_controls_script();
1019
1020        if ( self::is_my_jetpack_admin_request() && self::is_onboarding_takeover() ) {
1021            Assets::register_script(
1022                self::ONBOARDING_SCRIPT_HANDLE,
1023                '../build/onboarding.js',
1024                __FILE__,
1025                array(
1026                    'dependencies' => array( $data_handle ),
1027                    'enqueue'      => true,
1028                    'in_footer'    => true,
1029                    'textdomain'   => 'jetpack-my-jetpack',
1030                )
1031            );
1032        } elseif ( self::should_render_wp_build() && wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
1033            // Registered on every admin page but only enqueued when depended on; the esbuild bundles don't pull it in.
1034            wp_enqueue_script( 'wp-jp-i18n-loader' );
1035        }
1036
1037        $modules             = new Modules();
1038        $connection          = new Connection_Manager();
1039        $speed_score_history = new Speed_Score_History( home_url() );
1040        $latest_score        = $speed_score_history->latest();
1041        $previous_score      = array();
1042        if ( $speed_score_history->count() > 1 ) {
1043            $previous_score = $speed_score_history->latest( 1 );
1044        }
1045        $latest_score['previousScores'] = $previous_score['scores'] ?? array();
1046
1047        $sandboxed_domain = '';
1048        $is_dev_version   = false;
1049        if ( class_exists( 'Jetpack' ) ) {
1050            $is_dev_version   = Jetpack::is_development_version();
1051            $sandboxed_domain = defined( 'JETPACK__SANDBOX_DOMAIN' ) ? JETPACK__SANDBOX_DOMAIN : '';
1052        }
1053
1054        wp_localize_script(
1055            $data_handle,
1056            'myJetpackInitialState',
1057            array(
1058                'products'               => array(
1059                    'items' => Products::get_products(),
1060                ),
1061                'mainFeatures'           => Main_Features::get_state(),
1062                'featuresBanner'         => array( 'isDismissed' => REST_Main_Features::is_banner_dismissed() ),
1063                'onboardingWizard'       => self::get_onboarding_wizard_state(),
1064                'header'                 => self::get_header_state(),
1065                'plugins'                => Plugins_Installer::get_plugins(),
1066                'themes'                 => Sync_Functions::get_themes(),
1067                'myJetpackUrl'           => admin_url( 'admin.php?page=my-jetpack' ),
1068                'myJetpackCheckoutUri'   => admin_url( 'admin.php?page=my-jetpack' ),
1069                'topJetpackMenuItemUrl'  => Admin_Menu::get_top_level_menu_item_url(),
1070                'siteSuffix'             => ( new Status() )->get_site_suffix(),
1071                'siteUrl'                => esc_url( get_site_url() ),
1072                'homeUrl'                => esc_url_raw( home_url() ),
1073                'blogID'                 => Connection_Manager::get_site_id( true ),
1074                'myJetpackVersion'       => self::PACKAGE_VERSION,
1075                'myJetpackFlags'         => self::get_my_jetpack_flags(),
1076                'fileSystemWriteAccess'  => self::has_file_system_write_access(),
1077                'loadAddLicenseScreen'   => self::is_licensing_ui_enabled(),
1078                'planUrls'               => self::get_plan_urls(),
1079                'adminUrl'               => esc_url( admin_url() ),
1080                'assetsUrl'              => self::get_assets_url(),
1081                'IDCContainerID'         => static::get_idc_container_id(),
1082                'userIsAdmin'            => current_user_can( 'manage_options' ),
1083                // wp_localize_script() decodes the HTML entities WordPress stores names with.
1084                'userFirstName'          => (string) wp_get_current_user()->first_name,
1085                'lifecycleStats'         => array(
1086                    'jetpackPlugins'                      => self::get_installed_jetpack_plugins(),
1087                    'historicallyActiveModules'           => \Jetpack_Options::get_option( 'historically_active_modules', array() ),
1088                    'historicallyActiveModulesRefreshDue' => Historically_Active_Modules::is_refresh_due(),
1089                    'brokenModules'                       => Red_Bubble_Notifications::check_for_broken_modules(),
1090                    'isSiteConnected'                     => $connection->is_connected(),
1091                    'isUserConnected'                     => $connection->is_user_connected(),
1092                    'modules'                             => self::get_active_modules(),
1093                ),
1094                'recommendedModules'     => array(
1095                    'modules'    => self::get_recommended_modules(),
1096                    'isFirstRun' => \Jetpack_Options::get_option( 'recommendations_first_run', true ),
1097                    'dismissed'  => \Jetpack_Options::get_option( 'dismissed_recommendations', false ),
1098                ),
1099                'isStatsModuleActive'    => $modules->is_active( 'stats' ),
1100                'canUserViewStats'       => current_user_can( 'manage_options' ) || current_user_can( 'view_stats' ),
1101                'hiddenFeatures'         => Feature_Visibility::get_hidden(),
1102                'deprecatedModules'      => Feature_Visibility::get_deprecated_modules(),
1103                'sandboxedDomain'        => $sandboxed_domain,
1104                'isDevVersion'           => $is_dev_version,
1105                'isAtomic'               => ( new Status_Host() )->is_woa_site(),
1106                'isJetpackPluginActive'  => class_exists( 'Jetpack' ),
1107                'latestBoostSpeedScores' => $latest_score,
1108                'seoOptIn'               => self::get_seo_opt_in_state(),
1109                'protectPageModuleUrls'  => (object) Products\Protect::get_protect_page_module_urls(),
1110                'partnerCoupon'          => self::get_partner_coupon_screen(),
1111                'settingsNotices'        => self::get_settings_notices_state(),
1112            )
1113        );
1114
1115        wp_localize_script(
1116            $data_handle,
1117            'myJetpackRest',
1118            array(
1119                'apiRoot'  => esc_url_raw( rest_url() ),
1120                'apiNonce' => wp_create_nonce( 'wp_rest' ),
1121            )
1122        );
1123
1124        // Connection Initial State.
1125        Connection_Initial_State::render_script( $data_handle );
1126
1127        // Required for Analytics.
1128        if ( self::can_use_analytics() ) {
1129            Tracking::register_tracks_functions_scripts( true );
1130        }
1131    }
1132
1133    /**
1134     * What the shared header needs beyond the rest of the state, so it renders without a request.
1135     *
1136     * @since 6.10.0
1137     *
1138     * @return array{connectorsUrl: string|null} The state.
1139     */
1140    public static function get_header_state() {
1141        return array(
1142            // The same probe the connection package uses: the core screen ships with WordPress 7.0.
1143            // `connector` names the connection package's card, which opens its details for it.
1144            'connectorsUrl' => file_exists( ABSPATH . 'wp-admin/options-connectors.php' ) ? admin_url( 'options-connectors.php?connector=wordpress_com' ) : null,
1145        );
1146    }
1147
1148    /**
1149     * Where a host sends the plan links, in place of Jetpack's own checkout and purchases.
1150     *
1151     * @since 6.19.0
1152     *
1153     * @return array{purchase: string|false, manage: string|false} An empty string keeps Jetpack's own link; false hides the link.
1154     */
1155    public static function get_plan_urls() {
1156        $plan_urls = array(
1157            'purchase' => '',
1158            'manage'   => '',
1159        );
1160
1161        /**
1162         * Filters where My Jetpack's "Purchase a plan" and "Manage your plan" links go, for a host that sells its own plans.
1163         *
1164         * An answer that is neither an http or https URL nor false is discarded, keeping Jetpack's own link.
1165         *
1166         * @since 6.19.0
1167         * @param array{purchase: string|false, manage: string|false} $plan_urls The URL of each link; an empty string keeps Jetpack's own, and false hides the link.
1168         */
1169        $filtered = apply_filters( 'jetpack_my_jetpack_plan_urls', $plan_urls );
1170        $filtered = is_array( $filtered ) ? $filtered : array();
1171
1172        foreach ( array_keys( $plan_urls ) as $link ) {
1173            $answer = $filtered[ $link ] ?? null;
1174
1175            if ( is_string( $answer ) ) {
1176                $plan_urls[ $link ] = esc_url_raw( $answer, array( 'http', 'https' ) );
1177            } elseif ( false === $answer ) {
1178                $plan_urls[ $link ] = false;
1179            }
1180        }
1181
1182        return $plan_urls;
1183    }
1184
1185    /**
1186     * Add My Jetpack data to the unified script data object.
1187     *
1188     * @param array $data The script data.
1189     * @return array
1190     */
1191    public static function add_script_data( $data ) {
1192        $block_availability = ! self::is_offline_features_enabled() && class_exists( '\Jetpack_Gutenberg' )
1193            ? \Jetpack_Gutenberg::get_cached_availability()
1194            : array();
1195
1196        $data['myJetpack']['siteEditor'] = array(
1197            'isBlockTheme'            => function_exists( 'wp_is_block_theme' ) && wp_is_block_theme(),
1198            'isSharingBlockAvailable' => isset( $block_availability['sharing-buttons'] )
1199                && $block_availability['sharing-buttons']['available'],
1200            'isLikeBlockAvailable'    => isset( $block_availability['like'] )
1201                && $block_availability['like']['available'],
1202        );
1203
1204        return $data;
1205    }
1206
1207    /**
1208     * Whether module management can use the REST API.
1209     *
1210     * @since 6.11.0
1211     * @return bool
1212     */
1213    public static function is_modules_rest_api_enabled() {
1214        /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
1215        $enabled = apply_filters( 'rest_enabled', true );
1216        $user    = wp_get_current_user();
1217        $auth    = false;
1218        // Passing true skips WordPress's nonce check, which would sign the user out; restore the user if another filter clears it.
1219        try {
1220            /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
1221            $auth = apply_filters( 'rest_authentication_errors', true );
1222        } finally {
1223            wp_set_current_user( $user->ID );
1224        }
1225        return $enabled && ! is_wp_error( $enabled ) && false !== $auth && ! is_wp_error( $auth );
1226    }
1227
1228    /**
1229     * Get a Features management link with a classic Modules fallback.
1230     *
1231     * @since 6.11.0
1232     * @param array     $args     Query arguments from a classic Modules screen link; only `s` and `module_tag` can carry over to Features.
1233     * @param bool|null $eligible Set to true when the URL points at the Features tab, false when it is the classic Modules screen.
1234     * @return string The management URL.
1235     */
1236    public static function get_modules_management_url( $args = array(), &$eligible = null ) {
1237        $eligible  = false;
1238        $available = self::host_shows_my_jetpack() && self::is_modules_to_features_enabled();
1239        $classic   = add_query_arg( array_merge( urlencode_deep( $args ), array( 'page' => 'jetpack_modules' ) ), admin_url( 'admin.php' ) );
1240        if (
1241            ! $available
1242            || array_diff( array_keys( $args ), array( 's', 'module_tag' ) )
1243            || array_filter( $args, 'is_string' ) !== $args
1244            // Keep links on Modules unless Features can show controls for this installation.
1245            || Main_Features::PLUGIN_ACTIVE !== Main_Features::get_plugin_status( Product::JETPACK_PLUGIN_SLUG )
1246            || ! current_user_can( 'jetpack_manage_modules' )
1247            || ! current_user_can( 'manage_options' )
1248            || ! self::current_user_can_access_page()
1249            || ( new Status() )->is_offline_mode()
1250            || ( new Status_Host() )->is_wpcom_simple()
1251            || is_network_admin()
1252            || ! self::should_initialize()
1253            || ! ( new Connection_Manager() )->is_connected()
1254            || null !== self::get_partner_coupon_screen()
1255            // Predict My Jetpack's setup redirect for a Features URL with no step; keep both decisions in sync.
1256            || null !== self::get_onboarding_redirect_args_for_step( '' )
1257            || ! self::is_modules_rest_api_enabled()
1258        ) {
1259            return $classic;
1260        }
1261
1262        if ( isset( $args['module_tag'] ) && '' !== $args['module_tag'] ) {
1263            if ( ! function_exists( 'jetpack_get_module_i18n_tag' ) ) {
1264                return $classic;
1265            }
1266            $known      = array();
1267            $modules    = new Modules();
1268            $hidden     = Main_Features::get_hidden_modules();
1269            $deprecated = Feature_Visibility::get_deprecated_modules();
1270            foreach ( $modules->get_available() as $slug ) {
1271                if ( in_array( $slug, $hidden, true ) || ( in_array( $slug, $deprecated, true ) && ! $modules->is_active( $slug ) ) ) {
1272                    continue;
1273                }
1274                $module = $modules->get( $slug );
1275                $known  = array_merge( $known, $module['module_tags'] ?? array() );
1276            }
1277            $known = array_map( array( Jetpack::class, 'translate_module_tag' ), $known );
1278            if ( ! in_array( $args['module_tag'], $known, true ) ) {
1279                return $classic;
1280            }
1281        }
1282
1283        if ( isset( $args['s'] ) && '' !== $args['s'] ) {
1284            require_once JETPACK__PLUGIN_DIR . 'class.jetpack-admin.php';
1285            $hidden        = Main_Features::get_hidden_modules();
1286            $deprecated    = Feature_Visibility::get_deprecated_modules();
1287            $hidden_match  = false;
1288            $visible_match = false;
1289            foreach ( Jetpack::get_translated_modules( \Jetpack_Admin::init()->get_modules() ) as $slug => $module ) {
1290                if ( ! empty( $args['module_tag'] ) && ! in_array( $args['module_tag'], $module['module_tags'], true ) ) {
1291                    continue;
1292                }
1293                $text  = $module['name'] . ' ' . $module['description'] . ' ' . $module['long_description'] . ' ' . $module['search_terms'] . ' ' . implode( ',', $module['module_tags'] );
1294                $match = function_exists( 'mb_stripos' ) ? mb_stripos( $text, $args['s'] ) : stripos( $text, $args['s'] );
1295                if ( false === $match ) {
1296                    continue;
1297                }
1298                if ( in_array( $slug, $hidden, true ) || ( in_array( $slug, $deprecated, true ) && ! $module['activated'] ) ) {
1299                    $hidden_match = true;
1300                } else {
1301                    $visible_match = true;
1302                    break;
1303                }
1304            }
1305            if ( $hidden_match && ! $visible_match ) {
1306                return $classic;
1307            }
1308        }
1309
1310        $eligible = true;
1311        $hash     = array();
1312        if ( isset( $args['s'] ) && '' !== $args['s'] ) {
1313            $hash['search'] = $args['s'];
1314        }
1315        if ( isset( $args['module_tag'] ) && '' !== $args['module_tag'] ) {
1316            $hash['module_tag'] = $args['module_tag'];
1317        }
1318        return add_query_arg(
1319            array_merge(
1320                urlencode_deep( $args ),
1321                array(
1322                    'page'             => 'my-jetpack',
1323                    'modules_fallback' => '1',
1324                )
1325            ),
1326            admin_url( 'admin.php' )
1327        )
1328            . '#/features' . ( $hash ? '?' . http_build_query( $hash, '', '&', PHP_QUERY_RFC3986 ) : '' );
1329    }
1330
1331    /**
1332     * With `my-jetpack-modules-to-features` on, send My Jetpack requests with `modules_fallback=1` back to classic Modules:
1333     * always without JavaScript, and for everyone when REST is unavailable.
1334     *
1335     * @since 6.11.0
1336     * @return void
1337     */
1338    public static function print_modules_fallback() {
1339        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only navigation fallback.
1340        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- Only the exact allowlisted marker is accepted.
1341        if ( ! self::is_modules_to_features_enabled() || 'my-jetpack' !== ( $_GET['page'] ?? null ) || '1' !== ( $_GET['modules_fallback'] ?? null ) || Main_Features::PLUGIN_ACTIVE !== Main_Features::get_plugin_status( Product::JETPACK_PLUGIN_SLUG ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
1342            return;
1343        }
1344        $args = array( 'page' => 'jetpack_modules' );
1345        foreach ( array( 's', 'module_tag' ) as $key ) {
1346            if ( isset( $_GET[ $key ] ) && is_string( $_GET[ $key ] ) ) {
1347                $args[ $key ] = sanitize_text_field( wp_unslash( $_GET[ $key ] ) );
1348            }
1349        }
1350        // phpcs:enable WordPress.Security.NonceVerification.Recommended
1351        $meta = '<meta http-equiv="refresh" content="0; url=' . esc_url( add_query_arg( urlencode_deep( $args ), admin_url( 'admin.php' ) ) ) . '">';
1352        echo '<noscript>' . $meta . '</noscript>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- URL escaped above.
1353        if ( ! self::is_modules_rest_api_enabled() ) {
1354            echo $meta; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- URL escaped above.
1355        }
1356    }
1357
1358    /**
1359     * Get the slug and label of the Features tab, for footer links to it.
1360     *
1361     * Kept for footers built before the Products tab was removed: Jetpack 16.3 calls this, and
1362     * older JS footers read it from script data. Without it they link to "Products".
1363     *
1364     * @since 6.4.0
1365     *
1366     * @return array{slug: string, label: string}
1367     */
1368    public static function get_products_section() {
1369        return array(
1370            'slug'  => 'features',
1371            'label' => _x( 'Features', 'Navigation item', 'jetpack-my-jetpack' ),
1372        );
1373    }
1374
1375    /**
1376     * Add My Jetpack's availability, image base URL and link targets to admin script data.
1377     *
1378     * Printed on every admin page by Script_Data, so the connection screen can resolve its
1379     * illustrations and Jetpack footers know whether to link to My Jetpack.
1380     *
1381     * @since 6.3.0
1382     *
1383     * @param array $data Script data.
1384     * @return array
1385     */
1386    public static function add_admin_script_data( $data ) {
1387        $data['myJetpack']['isAvailable']           = self::is_admin_page_available();
1388        $data['myJetpack']['isShownByHost']         = self::host_shows_my_jetpack();
1389        $data['myJetpack']['assetsUrl']             = self::get_assets_url();
1390        $data['myJetpack']['productsSection']       = self::get_products_section();
1391        $data['myJetpack']['settingsConsolidation'] = self::is_settings_consolidation_enabled();
1392        $data['myJetpack']['showsSettingsNotices']  = self::shows_settings_notices();
1393        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only selects which navigation data to seed.
1394        if ( in_array( $_GET['page'] ?? '', array( 'my-jetpack', 'jetpack-settings', 'jetpack' ), true ) ) {
1395            $data['myJetpack']['modulesManagementUrl'] = self::get_modules_management_url();
1396            $data['myJetpack']['googleAnalyticsPanel'] = Google_Analytics_Settings::is_available()
1397                ? self::get_settings_panel_url( Google_Analytics_Settings::SLUG )
1398                : false;
1399        }
1400
1401        // Only administrators can open the pages this points at, so spare everyone else the lookup.
1402        if ( current_user_can( 'manage_options' ) ) {
1403            $data['myJetpack']['aiManageUrl'] = esc_url_raw( Products\Jetpack_Ai::get_manage_url() );
1404        }
1405
1406        if (
1407            self::is_my_jetpack_admin_request()
1408            && self::is_offline_features_enabled()
1409            && self::should_initialize()
1410            && REST_Main_Features::permissions_callback()
1411        ) {
1412            $data['myJetpack']['offlineFeatures'] = array(
1413                'mainFeatures' => Main_Features::get_state( true ),
1414                'plugins'      => Plugins_Installer::get_plugins(),
1415            );
1416            $data['myJetpack']['offlineFeatures']['mainFeatures']['available_admin_pages'] = self::get_registered_admin_page_slugs();
1417        }
1418
1419        return $data;
1420    }
1421
1422    /**
1423     * Get the slugs of registered admin pages.
1424     *
1425     * Skip hooks containing `?`: they are `edit.php?post_type=...` style pages, not page slugs.
1426     *
1427     * @return string[]
1428     */
1429    private static function get_registered_admin_page_slugs() {
1430        global $_registered_pages;
1431
1432        $hooks = array_filter(
1433            array_keys( $_registered_pages ?? array() ),
1434            static fn( $hook ) => false !== strpos( $hook, '_page_' ) && false === strpos( $hook, '?' )
1435        );
1436
1437        return array_values(
1438            array_unique(
1439                array_map( static fn( $hook ) => substr( $hook, strpos( $hook, '_page_' ) + 6 ), $hooks )
1440            )
1441        );
1442    }
1443
1444    /**
1445     * Whether My Jetpack's admin page is available to the current user.
1446     *
1447     * Meaningful only after admin_menu has registered the page.
1448     *
1449     * @since 6.5.0
1450     *
1451     * @return bool
1452     */
1453    public static function is_admin_page_available() {
1454        global $_registered_pages;
1455
1456        return did_action( 'my_jetpack_init' ) > 0
1457            && isset( $_registered_pages[ get_plugin_page_hookname( 'my-jetpack', 'jetpack' ) ] )
1458            && current_user_can( 'edit_posts' );
1459    }
1460
1461    /**
1462     * Get the base URL of the package's built images, with a trailing slash.
1463     *
1464     * @since 6.3.0
1465     *
1466     * @return string
1467     */
1468    public static function get_assets_url() {
1469        return trailingslashit( Assets::normalize_path( plugins_url( '../build/images/', __FILE__ ) ) );
1470    }
1471
1472    /**
1473     * Get installed Jetpack plugins
1474     *
1475     * @return array
1476     */
1477    public static function get_installed_jetpack_plugins() {
1478        $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
1479        $plugin_slugs = array_map(
1480            static function ( $slug ) {
1481                $parts = explode( '/', $slug );
1482                // Return the last segment of the filepath without the PHP extension
1483                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
1484            },
1485            $plugin_slugs
1486        );
1487
1488        return array_values( array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs ) );
1489    }
1490
1491    /**
1492     * Get active modules (except ones enabled by default)
1493     *
1494     * @return array
1495     */
1496    public static function get_active_modules() {
1497        $modules        = new Modules();
1498        $active_modules = $modules->get_active();
1499
1500        // if the Jetpack plugin is active, filter out the modules that are active by default
1501        if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
1502            $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
1503        }
1504        return array_values( $active_modules );
1505    }
1506
1507    /**
1508     * Determine if the current user is "new" to Jetpack
1509     * This is used to vary some messaging in My Jetpack
1510     *
1511     * On the front-end, purchases are also taken into account
1512     *
1513     * @return bool
1514     */
1515    public static function is_jetpack_user_new() {
1516        // is the user connected?
1517        $connection = new Connection_Manager();
1518        if ( $connection->is_user_connected() ) {
1519            return false;
1520        }
1521
1522        // TODO: add a data point for the last known connection/ disconnection time
1523
1524        // are any modules active?
1525        $active_modules = self::get_active_modules();
1526        if ( ! empty( $active_modules ) ) {
1527            return false;
1528        }
1529
1530        // check for other Jetpack plugins that are installed on the site (active or not)
1531        // If there's more than one Jetpack plugin active, this user is not "new"
1532        $plugin_slugs              = array_keys( Plugins_Installer::get_plugins() );
1533        $plugin_slugs              = array_map(
1534            static function ( $slug ) {
1535                $parts = explode( '/', $slug );
1536                // Return the last segment of the filepath without the PHP extension
1537                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
1538            },
1539            $plugin_slugs
1540        );
1541        $installed_jetpack_plugins = array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs );
1542        if ( is_countable( $installed_jetpack_plugins ) && count( $installed_jetpack_plugins ) >= 2 ) {
1543            return false;
1544        }
1545
1546        // Does the site have any purchases?
1547        $purchases = Wpcom_Products::get_site_current_purchases();
1548        if ( ! empty( $purchases ) && ! is_wp_error( $purchases ) ) {
1549            return false;
1550        }
1551
1552        return true;
1553    }
1554
1555    /**
1556     * Register My Jetpack's feature flags.
1557     *
1558     * @since 6.11.0
1559     *
1560     * @return void
1561     */
1562    public static function register_feature_flags() {
1563        Feature_Flags::register(
1564            self::ACCOUNT_CONNECT_FLAG,
1565            array(
1566                'default'     => true,
1567                'description' => 'Connect the account from the Install or Connect button of Features cards that need one, turn the chosen module on once Install Jetpack or Activate Jetpack finishes setup, hide Active and Inactive where the control already shows the state, exclude features from Available when their only action is an install the user cannot make, and show host restrictions below card descriptions.',
1568                'owner'       => 'my-jetpack',
1569            )
1570        );
1571        Feature_Flags::register(
1572            self::HEADER_CONTROLS_FLAG,
1573            array(
1574                'default'     => true,
1575                'description' => 'Show the global controls in the shared header of My Jetpack and Boost.',
1576                'owner'       => 'my-jetpack',
1577            )
1578        );
1579        Feature_Flags::register(
1580            self::OVERVIEW_V1_FLAG,
1581            array(
1582                'default'     => false,
1583                'description' => 'Show Overview v1 in My Jetpack.',
1584                'owner'       => 'my-jetpack',
1585            )
1586        );
1587        // Each Jetpack product that shows What's new registers this flag, with this same definition.
1588        Feature_Flags::register(
1589            self::WHATS_NEW_FLAG,
1590            array(
1591                'default'     => false,
1592                'description' => "Show What's new, the teaser and the reader of the Jetpack announcements, in the Jetpack dashboards.",
1593                'owner'       => 'jetpack',
1594            )
1595        );
1596        Feature_Flags::register(
1597            self::MODULES_TO_FEATURES_FLAG,
1598            array(
1599                'default'     => true,
1600                'description' => 'Open supported classic Modules links in Features.',
1601                'owner'       => 'my-jetpack',
1602            )
1603        );
1604        Feature_Flags::register(
1605            self::SETTINGS_CONSOLIDATION_FLAG,
1606            array(
1607                'default'     => false,
1608                'description' => 'Move settings out of the Settings screen to their new homes: open small features\' settings in a panel from Configure in Features, remove or replace their Settings cards with pointers, and show settings in their new places.',
1609                'owner'       => 'my-jetpack',
1610            )
1611        );
1612
1613        // Without the Jetpack plugin, nothing else registers the shell flag on requests that build no admin menu (CLI, REST, AJAX).
1614        if ( method_exists( Admin_Shell::class, 'register_feature_flag' ) ) {
1615            Admin_Shell::register_feature_flag();
1616        }
1617    }
1618
1619    /**
1620     * Whether the shared header shows its controls: the flag is on, My Jetpack runs, and not in offline Features.
1621     *
1622     * Boost's dashboard gets My Jetpack's page state even where My Jetpack is off, hence the second check.
1623     * Offline Features prints no connection state for the controls to read, and has no connection to show.
1624     *
1625     * @return bool
1626     */
1627    private static function is_header_controls_enabled() {
1628        return Feature_Flags::is_enabled( self::HEADER_CONTROLS_FLAG )
1629            && self::should_initialize()
1630            && ! self::is_offline_features_enabled();
1631    }
1632
1633    /**
1634     * Give dashboards outside My Jetpack, such as Boost's, the header's controls as a shared script.
1635     *
1636     * Bundling them instead would ship a second copy of the connection package next to the page's own.
1637     *
1638     * @return void
1639     */
1640    private static function maybe_enqueue_header_controls_script() {
1641        if ( self::is_my_jetpack_admin_request() || ! self::is_header_controls_enabled() ) {
1642            return;
1643        }
1644
1645        Assets::register_script(
1646            self::HEADER_CONTROLS_SCRIPT_HANDLE,
1647            '../build/header-controls.js',
1648            __FILE__,
1649            array(
1650                'dependencies' => array( self::DATA_SCRIPT_HANDLE ),
1651                'enqueue'      => true,
1652                'in_footer'    => true,
1653                'textdomain'   => 'jetpack-my-jetpack',
1654            )
1655        );
1656    }
1657
1658    /**
1659     *  Build flags for My Jetpack UI
1660     *
1661     *  @return array
1662     */
1663    public static function get_my_jetpack_flags() {
1664        $flags = array(
1665            'videoPressStats'          => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
1666            'showFullJetpackStatsCard' => class_exists( 'Jetpack' ) || Products\Stats::is_standalone_plugin_active(),
1667            // Only says which destination `manage_url` is: the legacy Stats page
1668            // caches its report and wants a `force_refresh` hint the dashboard does not.
1669            'premiumAnalyticsEnabled'  => Products\Stats::is_premium_analytics_enabled(),
1670            'showAiModuleToggle'       => Products\Jetpack_Ai::is_feature_ui_enabled(),
1671            'headerControls'           => self::is_header_controls_enabled(),
1672            'accountConnect'           => Feature_Flags::is_enabled( self::ACCOUNT_CONNECT_FLAG ),
1673            'overviewV1'               => self::is_overview_v1_enabled(),
1674            'whatsNew'                 => self::is_whats_new_enabled(),
1675        );
1676
1677        if ( $flags['accountConnect'] ) {
1678            $flags['showAiModuleToggleOnceConnected'] = Products\Jetpack_Ai::is_feature_ui_waiting_for_owner();
1679        }
1680
1681        return $flags;
1682    }
1683
1684    /**
1685     * Whether My Jetpack shows Overview v1.
1686     *
1687     * @since 6.10.0
1688     * @return bool
1689     */
1690    public static function is_overview_v1_enabled() {
1691        return Feature_Flags::is_enabled( self::OVERVIEW_V1_FLAG );
1692    }
1693
1694    /**
1695     * Whether My Jetpack shows What's new.
1696     *
1697     * @since $$next-version$$
1698     * @return bool
1699     */
1700    public static function is_whats_new_enabled() {
1701        return Feature_Flags::is_enabled( self::WHATS_NEW_FLAG );
1702    }
1703
1704    /**
1705     * Whether the host shows My Jetpack.
1706     *
1707     * @return bool
1708     */
1709    private static function host_shows_my_jetpack() {
1710        /**
1711         * Filters whether the host shows My Jetpack, which lets Modules links open Features and settings move to My Jetpack.
1712         *
1713         * @since 6.11.0
1714         * @since 6.17.1 False also keeps settings on the Settings screen.
1715         * @since 6.19.0 False also removes the links to My Jetpack from Jetpack admin headers and footers.
1716         * @param bool $available True to allow the Features tab; false keeps the classic Modules and Settings screens, for a host where My Jetpack is not shown.
1717         */
1718        return (bool) apply_filters( 'jetpack_my_jetpack_modules_management_available', true );
1719    }
1720
1721    /**
1722     * Whether settings move to My Jetpack on this site: the flag is on, My Jetpack initializes, and the host shows it.
1723     *
1724     * It needs no admin menu, so URL builders that also run in REST use it, while page loads use `is_settings_consolidation_enabled()`.
1725     *
1726     * @since 6.17.1
1727     *
1728     * @return bool
1729     */
1730    public static function is_settings_consolidation_on_for_site() {
1731        return Feature_Flags::is_enabled( self::SETTINGS_CONSOLIDATION_FLAG )
1732            && self::should_initialize()
1733            && self::host_shows_my_jetpack();
1734    }
1735
1736    /**
1737     * Whether settings move to My Jetpack: consolidation is on for the site and My Jetpack's page is available.
1738     *
1739     * Without the page, moved settings would have nowhere to go, so they stay on the Settings screen.
1740     *
1741     * @since 6.15.0
1742     *
1743     * @return bool
1744     */
1745    public static function is_settings_consolidation_enabled() {
1746        return self::is_settings_consolidation_on_for_site() && self::is_admin_page_available();
1747    }
1748
1749    /**
1750     * Whether My Jetpack shows the notices Jetpack â€º Settings used to show, which settings consolidation moves here.
1751     *
1752     * Plugins check that this method exists before sending a pending `Jetpack::state()` here instead of to Settings.
1753     *
1754     * @since 6.19.0
1755     *
1756     * @return bool
1757     */
1758    public static function shows_settings_notices() {
1759        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only reads which setup step is open.
1760        $step = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';
1761
1762        // Neither the offline Features page nor onboarding has the notice slot.
1763        return self::is_settings_consolidation_enabled()
1764            && ! self::is_offline_features_enabled()
1765            && 'onboarding' !== $step
1766            && null === self::get_onboarding_redirect_args_for_step( $step );
1767    }
1768
1769    /**
1770     * What the notices moved from Jetpack â€º Settings need, or null while they stay there, leaving the Jetpack state to Settings.
1771     *
1772     * @since 6.19.0
1773     *
1774     * @return array|null
1775     */
1776    public static function get_settings_notices_state() {
1777        if ( ! self::shows_settings_notices() ) {
1778            return null;
1779        }
1780
1781        $cookie_state = new CookieState();
1782
1783        return array(
1784            'jetpackState'         => array(
1785                'error'            => $cookie_state->state( 'error' ),
1786                'errorDescription' => $cookie_state->state( 'error_description' ),
1787                'message'          => $cookie_state->state( 'message' ),
1788            ),
1789            'jetpackVersion'       => defined( 'JETPACK__VERSION' ) ? constant( 'JETPACK__VERSION' ) : null,
1790            // Settings showed it only to admins, the users who can change it.
1791            'searchEnginesVisible' => current_user_can( 'manage_options' ) ? '0' !== (string) get_option( 'blog_public' ) : null,
1792        );
1793    }
1794
1795    /**
1796     * Point the module's configure URL at its settings panel while settings consolidation is on for the site.
1797     *
1798     * @since 6.16.0
1799     *
1800     * @return void
1801     */
1802    public static function register_settings_panel_urls() {
1803        foreach ( self::SETTINGS_PANEL_MODULES as $module ) {
1804            add_filter(
1805                'jetpack_module_configuration_url_' . $module,
1806                static function ( $url ) use ( $module ) {
1807                    // Only Jetpack's settings-search default: a module's own page, such as SEO's, is its real home.
1808                    return false === strpos( (string) $url, 'page=jetpack-settings#/settings?term=' )
1809                        ? $url
1810                        : self::resolve_settings_url( $module, $url );
1811                }
1812            );
1813        }
1814    }
1815
1816    /**
1817     * Where a module's settings live: its panel in Features while settings consolidation is on for the site, `$fallback` otherwise.
1818     *
1819     * @since 6.16.0
1820     *
1821     * @param string $module   The module slug.
1822     * @param string $fallback The URL to use when the settings stay where they were.
1823     * @return string
1824     */
1825    public static function resolve_settings_url( $module, $fallback ) {
1826        if ( ! in_array( $module, self::SETTINGS_PANEL_MODULES, true ) || ! self::is_settings_consolidation_on_for_site() ) {
1827            return $fallback;
1828        }
1829
1830        return self::get_settings_panel_url( $module );
1831    }
1832
1833    /**
1834     * The URL that opens a settings panel in Features.
1835     *
1836     * @since 6.18.0
1837     *
1838     * @param string $slug The module or settings entry slug.
1839     * @return string
1840     */
1841    public static function get_settings_panel_url( $slug ) {
1842        return add_query_arg(
1843            array(
1844                'page' => 'my-jetpack',
1845                'p'    => rawurlencode( '/features?configure=' . $slug ),
1846            ),
1847            admin_url( 'admin.php' )
1848        );
1849    }
1850
1851    /**
1852     * Whether Modules links may use Features.
1853     *
1854     * @return bool
1855     */
1856    private static function is_modules_to_features_enabled() {
1857        return Feature_Flags::is_enabled( self::MODULES_TO_FEATURES_FLAG );
1858    }
1859
1860    /**
1861     * Build the legacy SEO opt-in card state through the package availability API.
1862     *
1863     * @return array{showCard: bool, redirect: string}
1864     */
1865    public static function get_seo_opt_in_state() {
1866        // Guard with method_exists rather than class_exists: an older bundled SEO package can ship
1867        // the Initializer class without this method, and class_exists alone would still fatal.
1868        $seo_initializer = 'Automattic\Jetpack\SEO\Initializer';
1869        // @phan-suppress-next-line PhanUndeclaredClassReference -- optional SEO package, guarded by method_exists.
1870        $show_card = method_exists( $seo_initializer, 'is_optin_available' ) && $seo_initializer::is_optin_available();
1871
1872        return array(
1873            'showCard' => $show_card,
1874            'redirect' => admin_url( 'admin.php?page=jetpack-seo' ),
1875        );
1876    }
1877
1878    /**
1879     * Echoes the admin page content.
1880     *
1881     * @return void
1882     */
1883    public static function admin_page() {
1884        // Asked again here rather than inferred from the redirect: with the wizard on a
1885        // connected user is deliberately left on this screen to finish setup, and anyone
1886        // who cannot connect never reaches it.
1887        if ( self::is_onboarding_takeover() ) {
1888            echo '<div id="my-jetpack-container"></div>';
1889            return;
1890        }
1891
1892        if ( self::should_render_wp_build() ) {
1893            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.
1894        }
1895    }
1896
1897    /**
1898     * Register the REST API routes.
1899     *
1900     * @return void
1901     */
1902    public static function register_rest_endpoints() {
1903        if ( self::is_offline_features_enabled() ) {
1904            ( new REST_Main_Features() )->register_rest_routes();
1905            return;
1906        }
1907
1908        new REST_Products();
1909        new REST_Purchases();
1910        ( new REST_Jetpack_AI_JWT() )->register_rest_route();
1911        new REST_Recommendations_Evaluation();
1912
1913        ( new REST_Onboarding() )->register_rest_routes();
1914        ( new REST_Main_Features() )->register_rest_routes();
1915        Google_Analytics_Settings::register_rest_routes();
1916
1917        Products::register_product_endpoints();
1918        Historically_Active_Modules::register_rest_endpoints();
1919        Jetpack_Manage::register_rest_endpoints();
1920        Red_Bubble_Notifications::register_rest_endpoints();
1921
1922        if ( self::is_overview_v1_enabled() ) {
1923            REST_Blog_Posts::register_rest_endpoints();
1924        }
1925
1926        register_rest_route(
1927            'my-jetpack/v1',
1928            'site',
1929            array(
1930                'methods'             => \WP_REST_Server::READABLE,
1931                'callback'            => __CLASS__ . '::get_site',
1932                'permission_callback' => __CLASS__ . '::permissions_callback',
1933            )
1934        );
1935
1936        register_rest_route(
1937            'my-jetpack/v1',
1938            'site/dismiss-welcome-banner',
1939            array(
1940                'methods'             => \WP_REST_Server::EDITABLE,
1941                'callback'            => __CLASS__ . '::dismiss_welcome_banner',
1942                'permission_callback' => __CLASS__ . '::permissions_callback',
1943            )
1944        );
1945    }
1946
1947    /**
1948     * Check user capability to access the endpoint.
1949     *
1950     * @access public
1951     * @static
1952     *
1953     * @return true|WP_Error
1954     */
1955    public static function permissions_callback() {
1956        return current_user_can( 'manage_options' );
1957    }
1958
1959    /**
1960     * Return true if we should initialize the My Jetpack admin page.
1961     */
1962    public static function should_initialize() {
1963        $should = true;
1964
1965        if ( ( new Status() )->is_offline_mode() ) {
1966            $should = self::is_offline_features_enabled();
1967        }
1968
1969        /**
1970         * Allows filtering whether My Jetpack should be initialized.
1971         * Outside REST requests, once the user is set, this cannot enable offline Features for a user without access.
1972         *
1973         * @since 0.5.0-alpha
1974         *
1975         * @param bool $shoud_initialize Should we initialize My Jetpack?
1976         */
1977        $should = apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
1978
1979        // REST authenticates after route registration; its permission callbacks check access.
1980        if ( self::is_offline_features_enabled() && ! Jetpack_Constants::is_true( 'REST_REQUEST' ) && function_exists( 'wp_get_current_user' ) && did_action( 'set_current_user' ) && ! self::current_user_can_access_page() ) {
1981            return false;
1982        }
1983
1984        return $should;
1985    }
1986
1987    /**
1988     * Whether the site uses the local Features entry instead of the connected dashboard.
1989     *
1990     * @since 6.10.0
1991     * @return bool
1992     */
1993    public static function is_offline_features_enabled() {
1994        if ( ! ( new Status() )->is_offline_mode() ) {
1995            return false;
1996        }
1997
1998        /**
1999         * Enable local Features data and entry in offline mode.
2000         *
2001         * @since 6.10.0
2002         * @since 6.15.0 Enabled by default.
2003         * @param bool $enabled Whether to enable offline Features. Default true.
2004         */
2005        return (bool) apply_filters( 'jetpack_my_jetpack_offline_features', true );
2006    }
2007
2008    /**
2009     * Hook into several connection-based actions to update the historically active Jetpack modules
2010     * If the transient that indicates the list needs to be synced, update it and delete the transient
2011     *
2012     * @return void
2013     */
2014    public static function setup_historically_active_jetpack_modules_sync() {
2015        // yummmm. ham.
2016        $ham = new Historically_Active_Modules();
2017        if ( get_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY ) && ! wp_doing_ajax() ) {
2018            $ham::update_historically_active_jetpack_modules();
2019            delete_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY );
2020        }
2021
2022        $actions = array(
2023            'jetpack_site_registered',
2024            'jetpack_user_authorized',
2025            'activated_plugin',
2026        );
2027
2028        foreach ( $actions as $action ) {
2029            add_action( $action, array( $ham, 'queue_historically_active_jetpack_modules_update' ), 5 );
2030        }
2031
2032        // Modules are often updated async, so we need to update them right away as there will sometimes be no page reload.
2033        add_action( 'jetpack_activate_module', array( $ham, 'update_historically_active_jetpack_modules' ), 5 );
2034    }
2035
2036    /**
2037     * Site full-data endpoint.
2038     *
2039     * @return object Site data.
2040     */
2041    public static function get_site() {
2042        $site_id           = \Jetpack_Options::get_option( 'id' );
2043        $wpcom_endpoint    = sprintf( '/sites/%d?force=wpcom', $site_id );
2044        $wpcom_api_version = '1.1';
2045        $response          = Client::wpcom_json_api_request_as_blog( $wpcom_endpoint, $wpcom_api_version );
2046        $response_code     = wp_remote_retrieve_response_code( $response );
2047        $body              = json_decode( wp_remote_retrieve_body( $response ) );
2048
2049        if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
2050            return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
2051        }
2052
2053        return rest_ensure_response( $body );
2054    }
2055
2056    /**
2057     * Populates the self::$site_info var with site data from the /sites/%d endpoint
2058     *
2059     * @return object|WP_Error
2060     */
2061    public static function get_site_info() {
2062        static $site_info = null;
2063
2064        if ( $site_info !== null ) {
2065            return $site_info;
2066        }
2067
2068        // Check for a cached value before doing lookup
2069        $stored_site_info = get_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY );
2070        if ( $stored_site_info !== false ) {
2071            return $stored_site_info;
2072        }
2073
2074        $response = self::get_site();
2075        if ( is_wp_error( $response ) ) {
2076            return $response;
2077        }
2078        $site_info = $response->data;
2079        set_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY, $site_info, DAY_IN_SECONDS );
2080
2081        return $site_info;
2082    }
2083
2084    /**
2085     * Returns whether a site has been determined "commercial" or not.
2086     *
2087     * @return bool|null
2088     */
2089    public static function is_commercial_site() {
2090        if ( is_wp_error( self::$site_info ) ) {
2091            return null;
2092        }
2093
2094        return empty( self::$site_info->options->is_commercial ) ? false : self::$site_info->options->is_commercial;
2095    }
2096
2097    /**
2098     * Check if site is registered (has been connected before).
2099     *
2100     * @return bool
2101     */
2102    public static function is_registered() {
2103        return (bool) \Jetpack_Options::get_option( 'id' );
2104    }
2105
2106    /**
2107     * Dismiss the welcome banner.
2108     *
2109     * @return \WP_REST_Response
2110     */
2111    public static function dismiss_welcome_banner() {
2112        \Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
2113        return rest_ensure_response( array( 'success' => true ) );
2114    }
2115
2116    /**
2117     * Returns "yes" if the site has file write access to the plugins folder, "no" otherwise.
2118     *
2119     * @return string
2120     **/
2121    public static function has_file_system_write_access() {
2122
2123        $cache = get_transient( 'my_jetpack_write_access' );
2124
2125        if ( false !== $cache ) {
2126            return $cache;
2127        }
2128
2129        if ( ! function_exists( 'get_filesystem_method' ) ) {
2130            require_once ABSPATH . 'wp-admin/includes/file.php';
2131        }
2132
2133        require_once ABSPATH . 'wp-admin/includes/template.php';
2134
2135        $write_access = 'no';
2136
2137        $filesystem_method = get_filesystem_method( array(), WP_PLUGIN_DIR );
2138        if ( 'direct' === $filesystem_method ) {
2139            $write_access = 'yes';
2140        }
2141
2142        if ( 'no' === $write_access ) {
2143            ob_start();
2144            $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
2145            ob_end_clean();
2146
2147            if ( $filesystem_credentials_are_stored ) {
2148                $write_access = 'yes';
2149            }
2150        }
2151
2152        set_transient( 'my_jetpack_write_access', $write_access, 30 * MINUTE_IN_SECONDS );
2153
2154        return $write_access;
2155    }
2156
2157    /**
2158     * Get container IDC for the IDC screen.
2159     *
2160     * @return string
2161     */
2162    public static function get_idc_container_id() {
2163        return static::IDC_CONTAINER_ID;
2164    }
2165
2166    /**
2167     * Conditionally append the red bubble notification to the "Jetpack" menu item if there are alerts to show.
2168     *
2169     * On My Jetpack page: Uses blocking behavior to fetch fresh data.
2170     * On other admin pages: Uses cached data only to avoid blocking, with async JS fetch if cache is empty.
2171     *
2172     * @return void
2173     */
2174    public static function maybe_show_red_bubble() {
2175        global $pagenow;
2176
2177        // Don't show red bubble alerts for non-admin users
2178        // These alerts are generally only actionable for admins
2179        if ( ! current_user_can( 'manage_options' ) ) {
2180            return;
2181        }
2182
2183        // Don't show any red bubbles when Jetpack is disconnected
2184        // Users can't act on most alerts without a connection
2185        $connection = new Connection_Manager();
2186        if ( ! $connection->is_connected() ) {
2187            return;
2188        }
2189
2190        // Check if we're on the My Jetpack page.
2191        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
2192        $page               = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
2193        $is_my_jetpack_page = $pagenow === 'admin.php' && $page === 'my-jetpack';
2194
2195        if ( $is_my_jetpack_page ) {
2196            // On My Jetpack page: use blocking behavior for fresh data.
2197            add_filter( 'my_jetpack_red_bubble_notification_slugs', array( Red_Bubble_Notifications::class, 'add_red_bubble_alerts' ) );
2198            $red_bubble_alerts = Red_Bubble_Notifications::get_red_bubble_alerts();
2199        } else {
2200            // On other pages: use cached data only to avoid blocking.
2201            $cached_alerts = Red_Bubble_Notifications::get_cached_alerts();
2202
2203            if ( false === $cached_alerts ) {
2204                // No cache: warm it asynchronously via JS. Register a hidden zero-count
2205                // placeholder so Menu_Renderer emits a `my-jetpack` badge element the
2206                // warmer can reveal (see async-notification-bubble.ts) without a reload.
2207                Menu_Badges::init(); // idempotent; wires the renderer.
2208                Notification_Counts::register(
2209                    'my-jetpack',
2210                    array(
2211                        'menu_slug' => 'my-jetpack',
2212                        'count'     => 0,
2213                        'type'      => 'count',
2214                    )
2215                );
2216                add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_red_bubble_script' ) );
2217                return;
2218            }
2219
2220            $red_bubble_alerts = $cached_alerts;
2221        }
2222
2223        // Filter out silent alerts.
2224        $red_bubble_alerts = array_filter(
2225            $red_bubble_alerts,
2226            function ( $alert ) {
2227                return empty( $alert['is_silent'] );
2228            }
2229        );
2230
2231        // Report each non-silent alert to the central menu-badges registry as an
2232        // attention entry (count 1). The registry + renderer own the badge.
2233        Menu_Badges::init(); // idempotent; wires the renderer.
2234
2235        // Connection errors are owned by the Error Handler (the single source of truth):
2236        // surface any it reports for this viewer as their own attention entry. Read live
2237        // rather than from the red-bubble transient, since that cache is not viewer-keyed.
2238        $has_connection_error = self::has_connection_error();
2239        if ( $has_connection_error ) {
2240            Notification_Counts::register(
2241                'my-jetpack-connection-error',
2242                array(
2243                    'menu_slug' => 'my-jetpack',
2244                    'type'      => 'attention',
2245                )
2246            );
2247        }
2248
2249        $counted_elsewhere = self::get_alerts_counted_elsewhere();
2250        foreach ( array_keys( $red_bubble_alerts ) as $slug ) {
2251            if ( in_array( $slug, $counted_elsewhere, true ) ) {
2252                continue;
2253            }
2254            // The missing-connection slug and a connection error describe the same broken
2255            // connection; count it once (the error, above, is the more specific signal).
2256            if ( $has_connection_error && 'missing-connection' === $slug ) {
2257                continue;
2258            }
2259            Notification_Counts::register(
2260                'my-jetpack-' . $slug,
2261                array(
2262                    'menu_slug' => 'my-jetpack',
2263                    'type'      => 'attention',
2264                )
2265            );
2266        }
2267    }
2268
2269    /**
2270     * Whether the Connection Error Handler reports a displayable connection error
2271     * for the current viewer.
2272     *
2273     * Read live (not via the red-bubble transient): get_displayable_errors() is a
2274     * cached option read that the Error Handler already scopes and caches per viewer.
2275     * Guarded for the mid-plugin-update window, where a stale connection package
2276     * predating the method can be loaded.
2277     *
2278     * @return bool
2279     */
2280    private static function has_connection_error() {
2281        if ( ! class_exists( Connection_Error_Handler::class ) || ! method_exists( Connection_Error_Handler::class, 'get_displayable_errors' ) ) {
2282            return false;
2283        }
2284        return ! empty( Connection_Error_Handler::get_instance()->get_displayable_errors() );
2285    }
2286
2287    /**
2288     * Alerts left out of the My Jetpack badge because another menu item already counts them.
2289     *
2290     * The Protect page reports its own count, from the standalone plugin (class-jetpack-protect.php::admin_page_init())
2291     * or the Protect package's dashboard; without either, nobody else counts the threats, so they must stay.
2292     *
2293     * @return string[] Alert slugs.
2294     */
2295    private static function get_alerts_counted_elsewhere() {
2296        // Without has_protect_page(), use the standalone plugin check this relied on before that method existed.
2297        $has_protect_page = method_exists( Products\Protect::class, 'has_protect_page' ) ? Products\Protect::has_protect_page() : Products\Protect::is_standalone_plugin_active();
2298        return $has_protect_page ? array( 'protect_has_threats' ) : array();
2299    }
2300
2301    /**
2302     * Enqueue the notification bubble script.
2303     * Fetches fresh alert data via REST API without blocking page load.
2304     *
2305     * @return void
2306     */
2307    public static function enqueue_red_bubble_script() {
2308        Assets::register_script(
2309            'my-jetpack-notification-bubble',
2310            '../build/async-notification-bubble.js',
2311            __FILE__,
2312            array(
2313                'enqueue'   => true,
2314                'in_footer' => true,
2315            )
2316        );
2317        wp_localize_script(
2318            'my-jetpack-notification-bubble',
2319            'myJetpackNotificationBubble',
2320            array( 'excludedAlerts' => self::get_alerts_counted_elsewhere() )
2321        );
2322    }
2323
2324    /**
2325     * Get list of module names sorted by their recommendation score
2326     *
2327     * @return array|null
2328     */
2329    public static function get_recommended_modules() {
2330        $recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );
2331
2332        if ( empty( $recommendations_evaluation ) || ! is_array( $recommendations_evaluation ) ) {
2333            return null;
2334        }
2335
2336        arsort( $recommendations_evaluation ); // Sort by scores in descending order
2337
2338        return array_keys( $recommendations_evaluation ); // Get only module names
2339    }
2340}