Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.97% covered (warning)
82.97%
385 / 464
58.70% covered (warning)
58.70%
27 / 46
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
82.97% covered (warning)
82.97%
385 / 464
58.70% covered (warning)
58.70%
27 / 46
243.93
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
4
 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%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 admin_init
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
5.03
 is_onboarding_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_partner_coupon_screen
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
7
 get_onboarding_redirect_args
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
7
 add_onboarding_admin_body_class
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 can_use_analytics
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 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%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 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
 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
95.70% covered (success)
95.70%
89 / 93
0.00% covered (danger)
0.00%
0 / 1
10
 add_script_data
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
5.01
 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%
12 / 12
100.00% covered (success)
100.00%
1 / 1
5
 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
 get_my_jetpack_flags
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 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%
27 / 27
100.00% covered (success)
100.00%
1 / 1
1
 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%
4 / 4
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.15% covered (success)
96.15%
50 / 52
0.00% covered (danger)
0.00%
0 / 1
13
 has_connection_error
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 enqueue_red_bubble_script
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 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\Assets;
12use Automattic\Jetpack\Boost_Speed_Score\Speed_Score;
13use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_History;
14use Automattic\Jetpack\Connection\Client;
15use Automattic\Jetpack\Connection\Error_Handler as Connection_Error_Handler;
16use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
17use Automattic\Jetpack\Connection\Manager as Connection_Manager;
18use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
19use Automattic\Jetpack\Connection\REST_Jetpack_AI_JWT;
20use Automattic\Jetpack\Constants as Jetpack_Constants;
21use Automattic\Jetpack\ExPlat;
22use Automattic\Jetpack\JITMS\JITM;
23use Automattic\Jetpack\Licensing;
24use Automattic\Jetpack\Menu_Badges\Menu_Badges;
25use Automattic\Jetpack\Menu_Badges\Notification_Counts;
26use Automattic\Jetpack\Modules;
27use Automattic\Jetpack\Partner_Coupon;
28use Automattic\Jetpack\Plugins_Installer;
29use Automattic\Jetpack\Status;
30use Automattic\Jetpack\Status\Host as Status_Host;
31use Automattic\Jetpack\Sync\Functions as Sync_Functions;
32use Automattic\Jetpack\Terms_Of_Service;
33use Automattic\Jetpack\Tracking;
34use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
35use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
36use Jetpack;
37use WP_Error;
38
39/**
40 * The main Initializer class that registers the admin menu and eneuque the assets.
41 */
42class Initializer {
43
44    /**
45     * My Jetpack package version
46     *
47     * @var string
48     */
49    const PACKAGE_VERSION = '6.9.0';
50
51    /**
52     * Handle for the classic script that carries the React initial state.
53     *
54     * Plugins that render My Jetpack components on their own pages (Boost) depend on this name.
55     */
56    const DATA_SCRIPT_HANDLE = 'my_jetpack_main_app';
57
58    /**
59     * Handle for the webpack bundle that renders the onboarding takeover.
60     */
61    const ONBOARDING_SCRIPT_HANDLE = 'my_jetpack_onboarding';
62
63    /**
64     * The wp-build page ID, which the generated enqueue check expects as the screen ID.
65     */
66    const WP_BUILD_PAGE_ID = 'my-jetpack-dashboard';
67
68    /**
69     * HTML container ID for the IDC screen on My Jetpack page.
70     */
71    private const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
72
73    public const JETPACK_PLUGIN_SLUGS = array(
74        'jetpack-backup',
75        'jetpack-boost',
76        'zerobscrm',
77        'jetpack',
78        'jetpack-protect',
79        'jetpack-social',
80        'jetpack-videopress',
81        'jetpack-search',
82        'jetpack-stats',
83    );
84
85    private const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
86
87    /**
88     * Holds info/data about the site (from the /sites/%d endpoint)
89     *
90     * @var object
91     */
92    public static $site_info;
93
94    /**
95     * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
96     *
97     * @var string|null
98     */
99    private static $wp_build_original_screen_id = null;
100
101    /**
102     * Initialize My Jetpack
103     *
104     * @return void
105     */
106    public static function init() {
107        // Before the gate: the Jetpack plugin renders this package's connection screen and footer
108        // links even where My Jetpack is off, and `myJetpackInitialState` only exists on its own page.
109        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_admin_script_data' ) );
110
111        if ( ! self::should_initialize() || did_action( 'my_jetpack_init' ) ) {
112            return;
113        }
114
115        // Answer "is this product on?" for admin menu registration.
116        Menu_Visibility::init();
117
118        // Extend jetpack plugins action links.
119        Products::extend_plugins_action_links();
120
121        // Set up the REST authentication hooks.
122        Connection_Rest_Authentication::init();
123
124        if ( self::is_licensing_ui_enabled() ) {
125            Licensing::instance()->initialize();
126        }
127
128        // Initialize Boost Speed Score
129        new Speed_Score( array(), 'jetpack-my-jetpack' );
130
131        // Add custom WP REST API endoints.
132        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );
133
134        // Both of wp-build's deadlines fall later in this request: its enqueue check must be
135        // hooked before `admin_enqueue_scripts`, and its render function defined before
136        // the page callback.
137        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
138
139        add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );
140
141        add_action( 'admin_init', array( __CLASS__, 'setup_historically_active_jetpack_modules_sync' ) );
142        // Registered on admin_menu (not admin_init) and well before priority 100000, so the
143        // counts it registers exist before the menu-badges renderer runs on admin_menu 100000.
144        add_action( 'admin_menu', array( __CLASS__, 'maybe_show_red_bubble' ), 30 );
145
146        // Set up the ExPlat package endpoints
147        ExPlat::init();
148
149        // Sets up JITMS.
150        JITM::configure();
151
152        // Add "Jetpack Manage" menu item.
153        Jetpack_Manage::init();
154
155        /**
156         * Fires after the My Jetpack package is initialized
157         *
158         * @since 0.1.0
159         */
160        do_action( 'my_jetpack_init' );
161    }
162
163    /**
164     * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
165     *
166     * @since 1.2.0
167     *
168     * @return boolean
169     */
170    public static function is_licensing_ui_enabled() {
171        // Default changed to true in 1.5.0.
172        $is_enabled = true;
173
174        /*
175         * Bail if My Jetpack is not enabled,
176         * and thus the licensing UI shouldn't be enabled either.
177         */
178        if ( ! self::should_initialize() ) {
179            $is_enabled = false;
180        }
181
182        /**
183         * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
184         *
185         * @param bool $is_enabled Defaults to true.
186         *
187         * @since 1.2.0
188         * @since 1.5.0 Update default value to true.
189         */
190        return apply_filters(
191            'jetpack_my_jetpack_should_enable_add_license_screen',
192            $is_enabled
193        );
194    }
195
196    /**
197     * Add My Jetpack menu item to the admin menu.
198     *
199     * @return void
200     */
201    public static function add_my_jetpack_menu_item() {
202        $position    = defined( Admin_Menu::class . '::POSITION_FIRST' ) ? Admin_Menu::POSITION_FIRST : -10;
203        $menu_slug   = 'my-jetpack';
204        $page_suffix = Admin_Menu::add_menu(
205            __( 'My Jetpack', 'jetpack-my-jetpack' ),
206            __( 'My Jetpack', 'jetpack-my-jetpack' ),
207            'edit_posts',
208            $menu_slug,
209            array( __CLASS__, 'admin_page' ),
210            $position
211        );
212        add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
213        // Users who can edit posts but have no Jetpack menu get an admin_page_ hook instead.
214        add_action( 'load-admin_page_' . $menu_slug, array( __CLASS__, 'admin_init' ) );
215    }
216
217    /**
218     * Callback for the load my jetpack page hook.
219     *
220     * @return void
221     */
222    public static function admin_init() {
223        $connection = new Connection_Manager();
224
225        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No nonce needed for redirect flow control
226        $step = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';
227
228        // Handle onboarding redirects based on connection status. Onboarding's only action is the
229        // connect request, which answers a user without `jetpack_connect` with a 403.
230        $redirect_args = self::get_onboarding_redirect_args(
231            $step,
232            $connection->is_connected(),
233            self::is_onboarding_available() && current_user_can( 'jetpack_connect' )
234        );
235
236        if ( null !== $redirect_args ) {
237            $admin_page = add_query_arg( $redirect_args, admin_url( 'admin.php' ) );
238            $location   = wp_sanitize_redirect( $admin_page );
239
240            // Remove wp_get_referer filter applied in `fix_redirect` method of `Jetpack_Admin` class
241            remove_filter( 'wp_redirect', 'wp_get_referer' );
242            wp_safe_redirect( $location );
243
244            exit( 0 );
245        }
246
247        // If the user reaches the onboarding page, add a class to the body
248        if ( $step === 'onboarding' ) {
249            add_filter( 'admin_body_class', array( __CLASS__, 'add_onboarding_admin_body_class' ) );
250        }
251
252        self::$site_info = self::get_site_info();
253        add_filter( 'identity_crisis_container_id', array( static::class, 'get_idc_container_id' ) );
254        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
255    }
256
257    /**
258     * Whether the My Jetpack onboarding flow is available on this site.
259     *
260     * WordPress.com Simple sites are connected by definition and don't manage their
261     * connection through My Jetpack, so the onboarding flow (which asks the user to
262     * connect) never applies there. A pending partner coupon brings its own connect screen.
263     *
264     * @internal Not part of the package's public API.
265     *
266     * @return bool
267     */
268    public static function is_onboarding_available() {
269        return ! ( new Status_Host() )->is_wpcom_simple() && null === self::get_partner_coupon_screen();
270    }
271
272    /**
273     * The partner coupon screen's data, when it should replace the dashboard.
274     *
275     * Coupons exist only with the Jetpack plugin, which supplies their products and images.
276     *
277     * @since 6.5.0
278     *
279     * @return array{coupon: array, assetBaseUrl: string}|null
280     */
281    public static function get_partner_coupon_screen() {
282        if (
283            ! self::should_initialize()
284            || ! current_user_can( 'manage_options' )
285            || ! Jetpack_Constants::is_defined( 'JETPACK__PLUGIN_FILE' )
286        ) {
287            return null;
288        }
289
290        $coupon = Partner_Coupon::get_coupon();
291        if ( ! $coupon ) {
292            return null;
293        }
294
295        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks which screen renders.
296        if ( ! isset( $_GET['showCouponRedemption'] ) && ( new Connection_Manager() )->has_connected_owner() ) {
297            return null;
298        }
299
300        return array(
301            'coupon'       => $coupon,
302            'assetBaseUrl' => plugins_url( '', Jetpack_Constants::get_constant( 'JETPACK__PLUGIN_FILE' ) ),
303        );
304    }
305
306    /**
307     * Decide whether the current My Jetpack request should redirect, and where to.
308     *
309     * @internal Not part of the package's public API.
310     *
311     * @param string $step                 The current `step` query param.
312     * @param bool   $is_connected         Whether the site is connected to WordPress.com.
313     * @param bool   $onboarding_available Whether the onboarding flow is available on this site.
314     * @return array|null Query args for the redirect, or null to stay on the current page.
315     */
316    public static function get_onboarding_redirect_args( $step, $is_connected, $onboarding_available ) {
317        if ( $onboarding_available && ! $is_connected && $step !== 'onboarding' ) {
318            // Redirect to onboarding if not connected
319            return array(
320                'page' => 'my-jetpack',
321                'step' => 'onboarding',
322            );
323        }
324
325        if ( $step === 'onboarding' && ( ! $onboarding_available || $is_connected ) ) {
326            // Redirect away from onboarding if already connected or onboarding is not available on this site
327            return array( 'page' => 'my-jetpack' );
328        }
329
330        return null;
331    }
332
333    /**
334     * Add a body class to the My Jetpack onboarding page.
335     * This class hides the WP Admin toolbar and the sidebar menu.
336     *
337     * @param string $classes The body classes.
338     * @return string The modified body classes.
339     */
340    public static function add_onboarding_admin_body_class( $classes ) {
341        $classes .= 'jetpack-admin-full-screen';
342        return $classes;
343    }
344
345    /**
346     * Returns whether we are in condition to track to use
347     * Analytics functionality like Tracks, MC, or GA.
348     */
349    public static function can_use_analytics() {
350        $status     = new Status();
351        $connection = new Connection_Manager();
352        $tracking   = new Tracking( 'jetpack', $connection );
353
354        return $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
355    }
356
357    /**
358     * Whether the current request targets the My Jetpack admin page.
359     *
360     * @since 6.3.0
361     *
362     * @return bool
363     */
364    public static function is_my_jetpack_admin_request() {
365        if ( ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
366            return false;
367        }
368
369        return sanitize_text_field( wp_unslash( $_GET['page'] ) ) === 'my-jetpack'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
370    }
371
372    /**
373     * Whether the current request is the full-viewport onboarding takeover.
374     *
375     * Onboarding hides all wp-admin chrome and never renders through wp-build.
376     *
377     * @since 6.3.0
378     *
379     * @return bool
380     */
381    public static function is_onboarding_request() {
382        if ( ! isset( $_GET['step'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
383            return false;
384        }
385
386        return sanitize_text_field( wp_unslash( $_GET['step'] ) ) === 'onboarding'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
387    }
388
389    /**
390     * Whether this request is the onboarding takeover rather than the dashboard.
391     *
392     * Loading wp-build, enqueueing scripts and rendering the page must all agree,
393     * so they share this one expression.
394     *
395     * @since 6.3.0
396     *
397     * @return bool
398     */
399    public static function is_onboarding_takeover() {
400        return self::is_onboarding_request() && self::is_onboarding_available();
401    }
402
403    /**
404     * Alias the screen ID to satisfy wp-build's generated enqueue check.
405     *
406     * @since 6.3.0
407     *
408     * @return void
409     */
410    public static function alias_screen_id_for_wp_build() {
411        $screen = get_current_screen();
412
413        if ( ! $screen ) {
414            return;
415        }
416
417        self::$wp_build_original_screen_id = $screen->id;
418        $screen->id                        = self::WP_BUILD_PAGE_ID;
419    }
420
421    /**
422     * Undo alias_screen_id_for_wp_build(), since JITM builds its message path from the screen ID.
423     *
424     * @since 6.3.0
425     *
426     * @return void
427     */
428    public static function restore_screen_id_after_wp_build() {
429        $screen = get_current_screen();
430
431        if ( ! $screen || null === self::$wp_build_original_screen_id ) {
432            return;
433        }
434
435        $screen->id                        = self::$wp_build_original_screen_id;
436        self::$wp_build_original_screen_id = null;
437    }
438
439    /**
440     * Whether this request should load wp-build at all.
441     *
442     * Also what keeps WP_Build_Polyfills from replacing core scripts on every other admin page.
443     *
444     * @since 6.3.0
445     *
446     * @return bool
447     */
448    public static function should_load_wp_build() {
449        return self::is_my_jetpack_admin_request() && ! self::is_onboarding_takeover();
450    }
451
452    /**
453     * Whether this request renders the dashboard through wp-build.
454     *
455     * The generated render function is missing where the package was never built.
456     *
457     * @since 6.3.0
458     *
459     * @return bool
460     */
461    public static function should_render_wp_build() {
462        return ! self::is_onboarding_takeover()
463            && function_exists( 'jetpack_my_jetpack_my_jetpack_dashboard_wp_admin_render_page' );
464    }
465
466    /**
467     * Load wp-build for the My Jetpack dashboard.
468     *
469     * @since 6.3.0
470     *
471     * @return void
472     */
473    public static function maybe_load_wp_build() {
474        if ( ! self::should_load_wp_build() ) {
475            return;
476        }
477
478        $build_index = dirname( __DIR__ ) . '/build/build.php';
479
480        if ( file_exists( $build_index ) ) {
481            self::load_wp_build( $build_index );
482        }
483    }
484
485    /**
486     * Require the generated wp-build index and wire it into this request.
487     *
488     * @since 6.3.0
489     *
490     * @param string $build_index Path to the generated `build.php`.
491     * @return void
492     */
493    public static function load_wp_build( $build_index ) {
494        self::require_wp_build_with_screen_alias( $build_index );
495
496        // wp-build hooks module registration to wp_default_scripts, which has
497        // already fired by admin_menu â€” call it directly or the init module
498        // never reaches the import map.
499        if ( function_exists( 'jetpack_my_jetpack_register_script_modules' ) ) {
500            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.
501        }
502
503        WP_Build_Polyfills::register(
504            'my-jetpack',
505            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
506        );
507    }
508
509    /**
510     * Require the generated build file with the screen ID aliased across its enqueue check.
511     *
512     * @see WP_Build_Screen_Id::load_with_alias()
513     * @param string $build_index Path to the generated `build.php`.
514     * @return void
515     */
516    private static function require_wp_build_with_screen_alias( $build_index ) {
517        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
518        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
519            WP_Build_Screen_Id::load_with_alias(
520                array( __CLASS__, 'alias_screen_id_for_wp_build' ),
521                array( __CLASS__, 'restore_screen_id_after_wp_build' ),
522                function () use ( $build_index ) {
523                    require_once $build_index;
524                }
525            );
526            return;
527        }
528
529        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
530        require_once $build_index;
531        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
532    }
533
534    /**
535     * Enqueue admin page assets.
536     *
537     * @return void
538     */
539    public static function enqueue_scripts() {
540        /**
541         * Fires after the My Jetpack page is initialized.
542         * Allows for enqueuing additional scripts only on the My Jetpack page.
543         *
544         * @since 4.35.7
545         */
546        do_action( 'myjetpack_enqueue_scripts' );
547        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );
548
549        // Script-less: it only prints the state below, before the dashboard's boot runs on DOMContentLoaded.
550        $data_handle = self::DATA_SCRIPT_HANDLE;
551        wp_register_script( $data_handle, false, array(), self::PACKAGE_VERSION, true );
552        wp_enqueue_script( $data_handle );
553
554        if ( self::is_my_jetpack_admin_request() && self::is_onboarding_takeover() ) {
555            Assets::register_script(
556                self::ONBOARDING_SCRIPT_HANDLE,
557                '../build/onboarding.js',
558                __FILE__,
559                array(
560                    'dependencies' => array( $data_handle ),
561                    'enqueue'      => true,
562                    'in_footer'    => true,
563                    'textdomain'   => 'jetpack-my-jetpack',
564                )
565            );
566        } elseif ( self::should_render_wp_build() && wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
567            // Registered on every admin page but only enqueued when depended on; the esbuild bundles don't pull it in.
568            wp_enqueue_script( 'wp-jp-i18n-loader' );
569        }
570
571        $modules             = new Modules();
572        $connection          = new Connection_Manager();
573        $speed_score_history = new Speed_Score_History( get_site_url() );
574        $latest_score        = $speed_score_history->latest();
575        $previous_score      = array();
576        if ( $speed_score_history->count() > 1 ) {
577            $previous_score = $speed_score_history->latest( 1 );
578        }
579        $latest_score['previousScores'] = $previous_score['scores'] ?? array();
580
581        $sandboxed_domain = '';
582        $is_dev_version   = false;
583        if ( class_exists( 'Jetpack' ) ) {
584            $is_dev_version   = Jetpack::is_development_version();
585            $sandboxed_domain = defined( 'JETPACK__SANDBOX_DOMAIN' ) ? JETPACK__SANDBOX_DOMAIN : '';
586        }
587
588        wp_localize_script(
589            $data_handle,
590            'myJetpackInitialState',
591            array(
592                'products'               => array(
593                    'items' => Products::get_products(),
594                ),
595                'mainFeatures'           => Main_Features::get_state(),
596                'featuresBanner'         => array( 'isDismissed' => REST_Main_Features::is_banner_dismissed() ),
597                'plugins'                => Plugins_Installer::get_plugins(),
598                'themes'                 => Sync_Functions::get_themes(),
599                'myJetpackUrl'           => admin_url( 'admin.php?page=my-jetpack' ),
600                'myJetpackCheckoutUri'   => admin_url( 'admin.php?page=my-jetpack' ),
601                'topJetpackMenuItemUrl'  => Admin_Menu::get_top_level_menu_item_url(),
602                'siteSuffix'             => ( new Status() )->get_site_suffix(),
603                'siteUrl'                => esc_url( get_site_url() ),
604                'blogID'                 => Connection_Manager::get_site_id( true ),
605                'myJetpackVersion'       => self::PACKAGE_VERSION,
606                'myJetpackFlags'         => self::get_my_jetpack_flags(),
607                'fileSystemWriteAccess'  => self::has_file_system_write_access(),
608                'loadAddLicenseScreen'   => self::is_licensing_ui_enabled(),
609                'adminUrl'               => esc_url( admin_url() ),
610                'assetsUrl'              => self::get_assets_url(),
611                'IDCContainerID'         => static::get_idc_container_id(),
612                'userIsAdmin'            => current_user_can( 'manage_options' ),
613                'lifecycleStats'         => array(
614                    'jetpackPlugins'            => self::get_installed_jetpack_plugins(),
615                    'historicallyActiveModules' => \Jetpack_Options::get_option( 'historically_active_modules', array() ),
616                    'brokenModules'             => Red_Bubble_Notifications::check_for_broken_modules(),
617                    'isSiteConnected'           => $connection->is_connected(),
618                    'isUserConnected'           => $connection->is_user_connected(),
619                    'modules'                   => self::get_active_modules(),
620                ),
621                'recommendedModules'     => array(
622                    'modules'    => self::get_recommended_modules(),
623                    'isFirstRun' => \Jetpack_Options::get_option( 'recommendations_first_run', true ),
624                    'dismissed'  => \Jetpack_Options::get_option( 'dismissed_recommendations', false ),
625                ),
626                'isStatsModuleActive'    => $modules->is_active( 'stats' ),
627                'canUserViewStats'       => current_user_can( 'manage_options' ) || current_user_can( 'view_stats' ),
628                'hiddenFeatures'         => Feature_Visibility::get_hidden(),
629                'sandboxedDomain'        => $sandboxed_domain,
630                'isDevVersion'           => $is_dev_version,
631                'isAtomic'               => ( new Status_Host() )->is_woa_site(),
632                'isJetpackPluginActive'  => class_exists( 'Jetpack' ),
633                'latestBoostSpeedScores' => $latest_score,
634                'seoOptIn'               => self::get_seo_opt_in_state(),
635                'partnerCoupon'          => self::get_partner_coupon_screen(),
636            )
637        );
638
639        wp_localize_script(
640            $data_handle,
641            'myJetpackRest',
642            array(
643                'apiRoot'  => esc_url_raw( rest_url() ),
644                'apiNonce' => wp_create_nonce( 'wp_rest' ),
645            )
646        );
647
648        // Connection Initial State.
649        Connection_Initial_State::render_script( $data_handle );
650
651        // Required for Analytics.
652        if ( self::can_use_analytics() ) {
653            Tracking::register_tracks_functions_scripts( true );
654        }
655    }
656
657    /**
658     * Add My Jetpack data to the unified script data object.
659     *
660     * @param array $data The script data.
661     * @return array
662     */
663    public static function add_script_data( $data ) {
664        $block_availability = class_exists( '\Jetpack_Gutenberg' )
665            ? \Jetpack_Gutenberg::get_cached_availability()
666            : array();
667
668        $data['myJetpack']['siteEditor'] = array(
669            'isBlockTheme'            => function_exists( 'wp_is_block_theme' ) && wp_is_block_theme(),
670            'isSharingBlockAvailable' => isset( $block_availability['sharing-buttons'] )
671                && $block_availability['sharing-buttons']['available'],
672            'isLikeBlockAvailable'    => isset( $block_availability['like'] )
673                && $block_availability['like']['available'],
674            'activeThemeStylesheet'   => get_stylesheet(),
675        );
676
677        return $data;
678    }
679
680    /**
681     * Get the slug and label of the Features tab, for footer links to it.
682     *
683     * Kept for footers built before the Products tab was removed: Jetpack 16.3 calls this, and
684     * older JS footers read it from script data. Without it they link to "Products".
685     *
686     * @since 6.4.0
687     *
688     * @return array{slug: string, label: string}
689     */
690    public static function get_products_section() {
691        return array(
692            'slug'  => 'features',
693            'label' => _x( 'Features', 'Navigation item', 'jetpack-my-jetpack' ),
694        );
695    }
696
697    /**
698     * Add My Jetpack availability and image base URL to admin script data.
699     *
700     * Printed on every admin page by Script_Data, so the connection screen can resolve its
701     * illustrations and Jetpack footers know whether to link to My Jetpack.
702     *
703     * @since 6.3.0
704     *
705     * @param array $data Script data.
706     * @return array
707     */
708    public static function add_admin_script_data( $data ) {
709        $data['myJetpack']['isAvailable']     = self::is_admin_page_available();
710        $data['myJetpack']['assetsUrl']       = self::get_assets_url();
711        $data['myJetpack']['productsSection'] = self::get_products_section();
712
713        if (
714            ( new Status() )->is_offline_mode()
715            /**
716             * Temporarily expose the local Features seed without enabling offline entry.
717             *
718             * @since $$next-version$$
719             * @param bool $enabled Whether to expose the seed. Default false.
720             */
721            && apply_filters( 'jetpack_my_jetpack_offline_features', false )
722            // Honor an explicit host veto without enabling offline entry.
723            /** This filter is documented in self::should_initialize(). */
724            && apply_filters( 'jetpack_my_jetpack_should_initialize', true )
725            && REST_Main_Features::permissions_callback()
726        ) {
727            $data['myJetpack']['offlineFeatures'] = array(
728                'mainFeatures' => Main_Features::get_state( true ),
729                'plugins'      => Plugins_Installer::get_plugins(),
730            );
731        }
732
733        return $data;
734    }
735
736    /**
737     * Whether My Jetpack's admin page is available to the current user.
738     *
739     * Meaningful only after admin_menu has registered the page.
740     *
741     * @since 6.5.0
742     *
743     * @return bool
744     */
745    public static function is_admin_page_available() {
746        global $_registered_pages;
747
748        return did_action( 'my_jetpack_init' ) > 0
749            && isset( $_registered_pages[ get_plugin_page_hookname( 'my-jetpack', 'jetpack' ) ] )
750            && current_user_can( 'edit_posts' );
751    }
752
753    /**
754     * Get the base URL of the package's built images, with a trailing slash.
755     *
756     * @since 6.3.0
757     *
758     * @return string
759     */
760    public static function get_assets_url() {
761        return trailingslashit( Assets::normalize_path( plugins_url( '../build/images/', __FILE__ ) ) );
762    }
763
764    /**
765     * Get installed Jetpack plugins
766     *
767     * @return array
768     */
769    public static function get_installed_jetpack_plugins() {
770        $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
771        $plugin_slugs = array_map(
772            static function ( $slug ) {
773                $parts = explode( '/', $slug );
774                // Return the last segment of the filepath without the PHP extension
775                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
776            },
777            $plugin_slugs
778        );
779
780        return array_values( array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs ) );
781    }
782
783    /**
784     * Get active modules (except ones enabled by default)
785     *
786     * @return array
787     */
788    public static function get_active_modules() {
789        $modules        = new Modules();
790        $active_modules = $modules->get_active();
791
792        // if the Jetpack plugin is active, filter out the modules that are active by default
793        if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
794            $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
795        }
796        return array_values( $active_modules );
797    }
798
799    /**
800     * Determine if the current user is "new" to Jetpack
801     * This is used to vary some messaging in My Jetpack
802     *
803     * On the front-end, purchases are also taken into account
804     *
805     * @return bool
806     */
807    public static function is_jetpack_user_new() {
808        // is the user connected?
809        $connection = new Connection_Manager();
810        if ( $connection->is_user_connected() ) {
811            return false;
812        }
813
814        // TODO: add a data point for the last known connection/ disconnection time
815
816        // are any modules active?
817        $active_modules = self::get_active_modules();
818        if ( ! empty( $active_modules ) ) {
819            return false;
820        }
821
822        // check for other Jetpack plugins that are installed on the site (active or not)
823        // If there's more than one Jetpack plugin active, this user is not "new"
824        $plugin_slugs              = array_keys( Plugins_Installer::get_plugins() );
825        $plugin_slugs              = array_map(
826            static function ( $slug ) {
827                $parts = explode( '/', $slug );
828                // Return the last segment of the filepath without the PHP extension
829                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
830            },
831            $plugin_slugs
832        );
833        $installed_jetpack_plugins = array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs );
834        if ( is_countable( $installed_jetpack_plugins ) && count( $installed_jetpack_plugins ) >= 2 ) {
835            return false;
836        }
837
838        // Does the site have any purchases?
839        $purchases = Wpcom_Products::get_site_current_purchases();
840        if ( ! empty( $purchases ) && ! is_wp_error( $purchases ) ) {
841            return false;
842        }
843
844        return true;
845    }
846
847    /**
848     *  Build flags for My Jetpack UI
849     *
850     *  @return array
851     */
852    public static function get_my_jetpack_flags() {
853        $flags = array(
854            'videoPressStats'          => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
855            'showFullJetpackStatsCard' => class_exists( 'Jetpack' ) || Products\Stats::is_standalone_plugin_active(),
856            // Only says which destination `manage_url` is: the legacy Stats page
857            // caches its report and wants a `force_refresh` hint the dashboard does not.
858            'premiumAnalyticsEnabled'  => Products\Stats::is_premium_analytics_enabled(),
859            'showAiModuleToggle'       => Products\Jetpack_Ai::is_feature_ui_enabled(),
860        );
861
862        return $flags;
863    }
864
865    /**
866     * Build the state the My Jetpack "try the new SEO experience" opt-in card hydrates from.
867     *
868     * The card invites an existing self-hosted install to switch over to the new Jetpack SEO
869     * dashboard (JETPACK-1700). Gating lives server-side, where the signals actually are. The
870     * card shows only when all of:
871     *
872     * - the new SEO product is available â€” the `rsm_jetpack_seo` feature filter is on (the SEO
873     *   package autoloads regardless, so `class_exists()` alone isn't enough; the filter is the
874     *   real availability switch and the same one the SEO package gates its own surface behind);
875     * - the site is self-hosted â€” WordPress.com (Simple + Atomic) decides its own SEO surface, so
876     *   the opt-in card is for self-hosted installs only;
877     * - the install hasn't opted in yet â€” `jetpack_seo_surface_visible` is still false. On wpcom
878     *   the SEO package's `is_seo_surface_visible()` short-circuits to `true`, so the
879     *   "not visible yet" check also doubles as the self-hosted guard, but we check the platform
880     *   explicitly for clarity.
881     *
882     * Referenced through `class_exists()` rather than a hard composer dependency: both packages
883     * ship inside the Jetpack plugin and the SEO surface is feature-flagged, so a guarded read of
884     * its public API keeps this from adding plumbing to consumers that don't load SEO.
885     *
886     * The on-success destination is computed by the opt-in endpoint itself; we only seed the card
887     * with the same admin URL so the button has a sensible fallback before the request resolves.
888     *
889     * @return array{showCard: bool, redirect: string}
890     */
891    public static function get_seo_opt_in_state() {
892        // Guard with method_exists rather than class_exists: an older bundled SEO package can ship
893        // the Initializer class without this method, and class_exists alone would still fatal.
894        $seo_initializer = 'Automattic\Jetpack\SEO\Initializer';
895        // @phan-suppress-next-line PhanUndeclaredClassReference -- optional SEO package, guarded by method_exists.
896        $show_card = method_exists( $seo_initializer, 'is_optin_available' ) && $seo_initializer::is_optin_available();
897
898        return array(
899            'showCard' => $show_card,
900            'redirect' => admin_url( 'admin.php?page=jetpack-seo' ),
901        );
902    }
903
904    /**
905     * Echoes the admin page content.
906     *
907     * @return void
908     */
909    public static function admin_page() {
910        // No connection check needed here: admin_init() has already redirected connected users
911        // away from onboarding. Availability is re-checked inside the helper on purpose â€” this
912        // render can run even when that redirect did not.
913        if ( self::is_onboarding_takeover() ) {
914            echo '<div id="my-jetpack-container"></div>';
915            return;
916        }
917
918        if ( self::should_render_wp_build() ) {
919            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.
920        }
921    }
922
923    /**
924     * Register the REST API routes.
925     *
926     * @return void
927     */
928    public static function register_rest_endpoints() {
929        new REST_Products();
930        new REST_Purchases();
931        ( new REST_Jetpack_AI_JWT() )->register_rest_route();
932        new REST_Recommendations_Evaluation();
933
934        ( new REST_Main_Features() )->register_rest_routes();
935
936        Products::register_product_endpoints();
937        Historically_Active_Modules::register_rest_endpoints();
938        Jetpack_Manage::register_rest_endpoints();
939        Red_Bubble_Notifications::register_rest_endpoints();
940
941        register_rest_route(
942            'my-jetpack/v1',
943            'site',
944            array(
945                'methods'             => \WP_REST_Server::READABLE,
946                'callback'            => __CLASS__ . '::get_site',
947                'permission_callback' => __CLASS__ . '::permissions_callback',
948            )
949        );
950
951        register_rest_route(
952            'my-jetpack/v1',
953            'site/dismiss-welcome-banner',
954            array(
955                'methods'             => \WP_REST_Server::EDITABLE,
956                'callback'            => __CLASS__ . '::dismiss_welcome_banner',
957                'permission_callback' => __CLASS__ . '::permissions_callback',
958            )
959        );
960    }
961
962    /**
963     * Check user capability to access the endpoint.
964     *
965     * @access public
966     * @static
967     *
968     * @return true|WP_Error
969     */
970    public static function permissions_callback() {
971        return current_user_can( 'manage_options' );
972    }
973
974    /**
975     * Return true if we should initialize the My Jetpack admin page.
976     */
977    public static function should_initialize() {
978        $should = true;
979
980        // All options presented in My Jetpack require a connection to WordPress.com.
981        if ( ( new Status() )->is_offline_mode() ) {
982            $should = false;
983        }
984
985        /**
986         * Allows filtering whether My Jetpack should be initialized.
987         *
988         * @since 0.5.0-alpha
989         *
990         * @param bool $shoud_initialize Should we initialize My Jetpack?
991         */
992        return apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
993    }
994
995    /**
996     * Hook into several connection-based actions to update the historically active Jetpack modules
997     * If the transient that indicates the list needs to be synced, update it and delete the transient
998     *
999     * @return void
1000     */
1001    public static function setup_historically_active_jetpack_modules_sync() {
1002        // yummmm. ham.
1003        $ham = new Historically_Active_Modules();
1004        if ( get_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY ) && ! wp_doing_ajax() ) {
1005            $ham::update_historically_active_jetpack_modules();
1006            delete_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY );
1007        }
1008
1009        $actions = array(
1010            'jetpack_site_registered',
1011            'jetpack_user_authorized',
1012            'activated_plugin',
1013        );
1014
1015        foreach ( $actions as $action ) {
1016            add_action( $action, array( $ham, 'queue_historically_active_jetpack_modules_update' ), 5 );
1017        }
1018
1019        // Modules are often updated async, so we need to update them right away as there will sometimes be no page reload.
1020        add_action( 'jetpack_activate_module', array( $ham, 'update_historically_active_jetpack_modules' ), 5 );
1021    }
1022
1023    /**
1024     * Site full-data endpoint.
1025     *
1026     * @return object Site data.
1027     */
1028    public static function get_site() {
1029        $site_id           = \Jetpack_Options::get_option( 'id' );
1030        $wpcom_endpoint    = sprintf( '/sites/%d?force=wpcom', $site_id );
1031        $wpcom_api_version = '1.1';
1032        $response          = Client::wpcom_json_api_request_as_blog( $wpcom_endpoint, $wpcom_api_version );
1033        $response_code     = wp_remote_retrieve_response_code( $response );
1034        $body              = json_decode( wp_remote_retrieve_body( $response ) );
1035
1036        if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
1037            return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
1038        }
1039
1040        return rest_ensure_response( $body );
1041    }
1042
1043    /**
1044     * Populates the self::$site_info var with site data from the /sites/%d endpoint
1045     *
1046     * @return object|WP_Error
1047     */
1048    public static function get_site_info() {
1049        static $site_info = null;
1050
1051        if ( $site_info !== null ) {
1052            return $site_info;
1053        }
1054
1055        // Check for a cached value before doing lookup
1056        $stored_site_info = get_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY );
1057        if ( $stored_site_info !== false ) {
1058            return $stored_site_info;
1059        }
1060
1061        $response = self::get_site();
1062        if ( is_wp_error( $response ) ) {
1063            return $response;
1064        }
1065        $site_info = $response->data;
1066        set_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY, $site_info, DAY_IN_SECONDS );
1067
1068        return $site_info;
1069    }
1070
1071    /**
1072     * Returns whether a site has been determined "commercial" or not.
1073     *
1074     * @return bool|null
1075     */
1076    public static function is_commercial_site() {
1077        if ( is_wp_error( self::$site_info ) ) {
1078            return null;
1079        }
1080
1081        return empty( self::$site_info->options->is_commercial ) ? false : self::$site_info->options->is_commercial;
1082    }
1083
1084    /**
1085     * Check if site is registered (has been connected before).
1086     *
1087     * @return bool
1088     */
1089    public static function is_registered() {
1090        return (bool) \Jetpack_Options::get_option( 'id' );
1091    }
1092
1093    /**
1094     * Dismiss the welcome banner.
1095     *
1096     * @return \WP_REST_Response
1097     */
1098    public static function dismiss_welcome_banner() {
1099        \Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
1100        return rest_ensure_response( array( 'success' => true ) );
1101    }
1102
1103    /**
1104     * Returns "yes" if the site has file write access to the plugins folder, "no" otherwise.
1105     *
1106     * @return string
1107     **/
1108    public static function has_file_system_write_access() {
1109
1110        $cache = get_transient( 'my_jetpack_write_access' );
1111
1112        if ( false !== $cache ) {
1113            return $cache;
1114        }
1115
1116        if ( ! function_exists( 'get_filesystem_method' ) ) {
1117            require_once ABSPATH . 'wp-admin/includes/file.php';
1118        }
1119
1120        require_once ABSPATH . 'wp-admin/includes/template.php';
1121
1122        $write_access = 'no';
1123
1124        $filesystem_method = get_filesystem_method( array(), WP_PLUGIN_DIR );
1125        if ( 'direct' === $filesystem_method ) {
1126            $write_access = 'yes';
1127        }
1128
1129        if ( 'no' === $write_access ) {
1130            ob_start();
1131            $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1132            ob_end_clean();
1133
1134            if ( $filesystem_credentials_are_stored ) {
1135                $write_access = 'yes';
1136            }
1137        }
1138
1139        set_transient( 'my_jetpack_write_access', $write_access, 30 * MINUTE_IN_SECONDS );
1140
1141        return $write_access;
1142    }
1143
1144    /**
1145     * Get container IDC for the IDC screen.
1146     *
1147     * @return string
1148     */
1149    public static function get_idc_container_id() {
1150        return static::IDC_CONTAINER_ID;
1151    }
1152
1153    /**
1154     * Conditionally append the red bubble notification to the "Jetpack" menu item if there are alerts to show.
1155     *
1156     * On My Jetpack page: Uses blocking behavior to fetch fresh data.
1157     * On other admin pages: Uses cached data only to avoid blocking, with async JS fetch if cache is empty.
1158     *
1159     * @return void
1160     */
1161    public static function maybe_show_red_bubble() {
1162        global $pagenow;
1163
1164        // Don't show red bubble alerts for non-admin users
1165        // These alerts are generally only actionable for admins
1166        if ( ! current_user_can( 'manage_options' ) ) {
1167            return;
1168        }
1169
1170        // Don't show any red bubbles when Jetpack is disconnected
1171        // Users can't act on most alerts without a connection
1172        $connection = new Connection_Manager();
1173        if ( ! $connection->is_connected() ) {
1174            return;
1175        }
1176
1177        // Check if we're on the My Jetpack page.
1178        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1179        $page               = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
1180        $is_my_jetpack_page = $pagenow === 'admin.php' && $page === 'my-jetpack';
1181
1182        if ( $is_my_jetpack_page ) {
1183            // On My Jetpack page: use blocking behavior for fresh data.
1184            add_filter( 'my_jetpack_red_bubble_notification_slugs', array( Red_Bubble_Notifications::class, 'add_red_bubble_alerts' ) );
1185            $red_bubble_alerts = Red_Bubble_Notifications::get_red_bubble_alerts();
1186        } else {
1187            // On other pages: use cached data only to avoid blocking.
1188            $cached_alerts = Red_Bubble_Notifications::get_cached_alerts();
1189
1190            if ( false === $cached_alerts ) {
1191                // No cache: warm it asynchronously via JS. Register a hidden zero-count
1192                // placeholder so Menu_Renderer emits a `my-jetpack` badge element the
1193                // warmer can reveal (see async-notification-bubble.ts) without a reload.
1194                Menu_Badges::init(); // idempotent; wires the renderer.
1195                Notification_Counts::register(
1196                    'my-jetpack',
1197                    array(
1198                        'menu_slug' => 'my-jetpack',
1199                        'count'     => 0,
1200                        'type'      => 'count',
1201                    )
1202                );
1203                add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_red_bubble_script' ) );
1204                return;
1205            }
1206
1207            $red_bubble_alerts = $cached_alerts;
1208        }
1209
1210        // Filter out silent alerts.
1211        $red_bubble_alerts = array_filter(
1212            $red_bubble_alerts,
1213            function ( $alert ) {
1214                return empty( $alert['is_silent'] );
1215            }
1216        );
1217
1218        // Report each non-silent alert to the central menu-badges registry as an
1219        // attention entry (count 1). The registry + renderer own the badge.
1220        Menu_Badges::init(); // idempotent; wires the renderer.
1221
1222        // Connection errors are owned by the Error Handler (the single source of truth):
1223        // surface any it reports for this viewer as their own attention entry. Read live
1224        // rather than from the red-bubble transient, since that cache is not viewer-keyed.
1225        $has_connection_error = self::has_connection_error();
1226        if ( $has_connection_error ) {
1227            Notification_Counts::register(
1228                'my-jetpack-connection-error',
1229                array(
1230                    'menu_slug' => 'my-jetpack',
1231                    'type'      => 'attention',
1232                )
1233            );
1234        }
1235
1236        foreach ( array_keys( $red_bubble_alerts ) as $slug ) {
1237            // Protect reports its own count directly to the registry, but only when its
1238            // standalone plugin is active (see class-jetpack-protect.php::admin_page_init()).
1239            // If the standalone plugin isn't active, nobody else registers this count, so we
1240            // must not skip it here or the alert silently disappears from the menu total.
1241            if ( 'protect_has_threats' === $slug && Products\Protect::is_standalone_plugin_active() ) {
1242                continue;
1243            }
1244            // The missing-connection slug and a connection error describe the same broken
1245            // connection; count it once (the error, above, is the more specific signal).
1246            if ( $has_connection_error && 'missing-connection' === $slug ) {
1247                continue;
1248            }
1249            Notification_Counts::register(
1250                'my-jetpack-' . $slug,
1251                array(
1252                    'menu_slug' => 'my-jetpack',
1253                    'type'      => 'attention',
1254                )
1255            );
1256        }
1257    }
1258
1259    /**
1260     * Whether the Connection Error Handler reports a displayable connection error
1261     * for the current viewer.
1262     *
1263     * Read live (not via the red-bubble transient): get_displayable_errors() is a
1264     * cached option read that the Error Handler already scopes and caches per viewer.
1265     * Guarded for the mid-plugin-update window, where a stale connection package
1266     * predating the method can be loaded.
1267     *
1268     * @return bool
1269     */
1270    private static function has_connection_error() {
1271        if ( ! class_exists( Connection_Error_Handler::class ) || ! method_exists( Connection_Error_Handler::class, 'get_displayable_errors' ) ) {
1272            return false;
1273        }
1274        return ! empty( Connection_Error_Handler::get_instance()->get_displayable_errors() );
1275    }
1276
1277    /**
1278     * Enqueue the notification bubble script.
1279     * Fetches fresh alert data via REST API without blocking page load.
1280     *
1281     * @return void
1282     */
1283    public static function enqueue_red_bubble_script() {
1284        Assets::register_script(
1285            'my-jetpack-notification-bubble',
1286            '../build/async-notification-bubble.js',
1287            __FILE__,
1288            array(
1289                'enqueue'   => true,
1290                'in_footer' => true,
1291            )
1292        );
1293    }
1294
1295    /**
1296     * Get list of module names sorted by their recommendation score
1297     *
1298     * @return array|null
1299     */
1300    public static function get_recommended_modules() {
1301        $recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );
1302
1303        if ( empty( $recommendations_evaluation ) || ! is_array( $recommendations_evaluation ) ) {
1304            return null;
1305        }
1306
1307        arsort( $recommendations_evaluation ); // Sort by scores in descending order
1308
1309        return array_keys( $recommendations_evaluation ); // Get only module names
1310    }
1311}