Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.68% covered (warning)
82.68%
377 / 456
58.70% covered (warning)
58.70%
27 / 46
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
82.68% covered (warning)
82.68%
377 / 456
58.70% covered (warning)
58.70%
27 / 46
239.47
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%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 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        return $data;
714    }
715
716    /**
717     * Whether My Jetpack's admin page is available to the current user.
718     *
719     * Meaningful only after admin_menu has registered the page.
720     *
721     * @since 6.5.0
722     *
723     * @return bool
724     */
725    public static function is_admin_page_available() {
726        global $_registered_pages;
727
728        return did_action( 'my_jetpack_init' ) > 0
729            && isset( $_registered_pages[ get_plugin_page_hookname( 'my-jetpack', 'jetpack' ) ] )
730            && current_user_can( 'edit_posts' );
731    }
732
733    /**
734     * Get the base URL of the package's built images, with a trailing slash.
735     *
736     * @since 6.3.0
737     *
738     * @return string
739     */
740    public static function get_assets_url() {
741        return trailingslashit( Assets::normalize_path( plugins_url( '../build/images/', __FILE__ ) ) );
742    }
743
744    /**
745     * Get installed Jetpack plugins
746     *
747     * @return array
748     */
749    public static function get_installed_jetpack_plugins() {
750        $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
751        $plugin_slugs = array_map(
752            static function ( $slug ) {
753                $parts = explode( '/', $slug );
754                // Return the last segment of the filepath without the PHP extension
755                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
756            },
757            $plugin_slugs
758        );
759
760        return array_values( array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs ) );
761    }
762
763    /**
764     * Get active modules (except ones enabled by default)
765     *
766     * @return array
767     */
768    public static function get_active_modules() {
769        $modules        = new Modules();
770        $active_modules = $modules->get_active();
771
772        // if the Jetpack plugin is active, filter out the modules that are active by default
773        if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
774            $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
775        }
776        return array_values( $active_modules );
777    }
778
779    /**
780     * Determine if the current user is "new" to Jetpack
781     * This is used to vary some messaging in My Jetpack
782     *
783     * On the front-end, purchases are also taken into account
784     *
785     * @return bool
786     */
787    public static function is_jetpack_user_new() {
788        // is the user connected?
789        $connection = new Connection_Manager();
790        if ( $connection->is_user_connected() ) {
791            return false;
792        }
793
794        // TODO: add a data point for the last known connection/ disconnection time
795
796        // are any modules active?
797        $active_modules = self::get_active_modules();
798        if ( ! empty( $active_modules ) ) {
799            return false;
800        }
801
802        // check for other Jetpack plugins that are installed on the site (active or not)
803        // If there's more than one Jetpack plugin active, this user is not "new"
804        $plugin_slugs              = array_keys( Plugins_Installer::get_plugins() );
805        $plugin_slugs              = array_map(
806            static function ( $slug ) {
807                $parts = explode( '/', $slug );
808                // Return the last segment of the filepath without the PHP extension
809                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
810            },
811            $plugin_slugs
812        );
813        $installed_jetpack_plugins = array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs );
814        if ( is_countable( $installed_jetpack_plugins ) && count( $installed_jetpack_plugins ) >= 2 ) {
815            return false;
816        }
817
818        // Does the site have any purchases?
819        $purchases = Wpcom_Products::get_site_current_purchases();
820        if ( ! empty( $purchases ) && ! is_wp_error( $purchases ) ) {
821            return false;
822        }
823
824        return true;
825    }
826
827    /**
828     *  Build flags for My Jetpack UI
829     *
830     *  @return array
831     */
832    public static function get_my_jetpack_flags() {
833        $flags = array(
834            'videoPressStats'          => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
835            'showFullJetpackStatsCard' => class_exists( 'Jetpack' ) || Products\Stats::is_standalone_plugin_active(),
836            // Only says which destination `manage_url` is: the legacy Stats page
837            // caches its report and wants a `force_refresh` hint the dashboard does not.
838            'premiumAnalyticsEnabled'  => Products\Stats::is_premium_analytics_enabled(),
839            'showAiModuleToggle'       => Products\Jetpack_Ai::is_feature_ui_enabled(),
840        );
841
842        return $flags;
843    }
844
845    /**
846     * Build the state the My Jetpack "try the new SEO experience" opt-in card hydrates from.
847     *
848     * The card invites an existing self-hosted install to switch over to the new Jetpack SEO
849     * dashboard (JETPACK-1700). Gating lives server-side, where the signals actually are. The
850     * card shows only when all of:
851     *
852     * - the new SEO product is available â€” the `rsm_jetpack_seo` feature filter is on (the SEO
853     *   package autoloads regardless, so `class_exists()` alone isn't enough; the filter is the
854     *   real availability switch and the same one the SEO package gates its own surface behind);
855     * - the site is self-hosted â€” WordPress.com (Simple + Atomic) decides its own SEO surface, so
856     *   the opt-in card is for self-hosted installs only;
857     * - the install hasn't opted in yet â€” `jetpack_seo_surface_visible` is still false. On wpcom
858     *   the SEO package's `is_seo_surface_visible()` short-circuits to `true`, so the
859     *   "not visible yet" check also doubles as the self-hosted guard, but we check the platform
860     *   explicitly for clarity.
861     *
862     * Referenced through `class_exists()` rather than a hard composer dependency: both packages
863     * ship inside the Jetpack plugin and the SEO surface is feature-flagged, so a guarded read of
864     * its public API keeps this from adding plumbing to consumers that don't load SEO.
865     *
866     * The on-success destination is computed by the opt-in endpoint itself; we only seed the card
867     * with the same admin URL so the button has a sensible fallback before the request resolves.
868     *
869     * @return array{showCard: bool, redirect: string}
870     */
871    public static function get_seo_opt_in_state() {
872        // Guard with method_exists rather than class_exists: an older bundled SEO package can ship
873        // the Initializer class without this method, and class_exists alone would still fatal.
874        $seo_initializer = 'Automattic\Jetpack\SEO\Initializer';
875        // @phan-suppress-next-line PhanUndeclaredClassReference -- optional SEO package, guarded by method_exists.
876        $show_card = method_exists( $seo_initializer, 'is_optin_available' ) && $seo_initializer::is_optin_available();
877
878        return array(
879            'showCard' => $show_card,
880            'redirect' => admin_url( 'admin.php?page=jetpack-seo' ),
881        );
882    }
883
884    /**
885     * Echoes the admin page content.
886     *
887     * @return void
888     */
889    public static function admin_page() {
890        // No connection check needed here: admin_init() has already redirected connected users
891        // away from onboarding. Availability is re-checked inside the helper on purpose â€” this
892        // render can run even when that redirect did not.
893        if ( self::is_onboarding_takeover() ) {
894            echo '<div id="my-jetpack-container"></div>';
895            return;
896        }
897
898        if ( self::should_render_wp_build() ) {
899            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.
900        }
901    }
902
903    /**
904     * Register the REST API routes.
905     *
906     * @return void
907     */
908    public static function register_rest_endpoints() {
909        new REST_Products();
910        new REST_Purchases();
911        ( new REST_Jetpack_AI_JWT() )->register_rest_route();
912        new REST_Recommendations_Evaluation();
913
914        ( new REST_Main_Features() )->register_rest_routes();
915
916        Products::register_product_endpoints();
917        Historically_Active_Modules::register_rest_endpoints();
918        Jetpack_Manage::register_rest_endpoints();
919        Red_Bubble_Notifications::register_rest_endpoints();
920
921        register_rest_route(
922            'my-jetpack/v1',
923            'site',
924            array(
925                'methods'             => \WP_REST_Server::READABLE,
926                'callback'            => __CLASS__ . '::get_site',
927                'permission_callback' => __CLASS__ . '::permissions_callback',
928            )
929        );
930
931        register_rest_route(
932            'my-jetpack/v1',
933            'site/dismiss-welcome-banner',
934            array(
935                'methods'             => \WP_REST_Server::EDITABLE,
936                'callback'            => __CLASS__ . '::dismiss_welcome_banner',
937                'permission_callback' => __CLASS__ . '::permissions_callback',
938            )
939        );
940    }
941
942    /**
943     * Check user capability to access the endpoint.
944     *
945     * @access public
946     * @static
947     *
948     * @return true|WP_Error
949     */
950    public static function permissions_callback() {
951        return current_user_can( 'manage_options' );
952    }
953
954    /**
955     * Return true if we should initialize the My Jetpack admin page.
956     */
957    public static function should_initialize() {
958        $should = true;
959
960        // All options presented in My Jetpack require a connection to WordPress.com.
961        if ( ( new Status() )->is_offline_mode() ) {
962            $should = false;
963        }
964
965        /**
966         * Allows filtering whether My Jetpack should be initialized.
967         *
968         * @since 0.5.0-alpha
969         *
970         * @param bool $shoud_initialize Should we initialize My Jetpack?
971         */
972        return apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
973    }
974
975    /**
976     * Hook into several connection-based actions to update the historically active Jetpack modules
977     * If the transient that indicates the list needs to be synced, update it and delete the transient
978     *
979     * @return void
980     */
981    public static function setup_historically_active_jetpack_modules_sync() {
982        // yummmm. ham.
983        $ham = new Historically_Active_Modules();
984        if ( get_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY ) && ! wp_doing_ajax() ) {
985            $ham::update_historically_active_jetpack_modules();
986            delete_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY );
987        }
988
989        $actions = array(
990            'jetpack_site_registered',
991            'jetpack_user_authorized',
992            'activated_plugin',
993        );
994
995        foreach ( $actions as $action ) {
996            add_action( $action, array( $ham, 'queue_historically_active_jetpack_modules_update' ), 5 );
997        }
998
999        // Modules are often updated async, so we need to update them right away as there will sometimes be no page reload.
1000        add_action( 'jetpack_activate_module', array( $ham, 'update_historically_active_jetpack_modules' ), 5 );
1001    }
1002
1003    /**
1004     * Site full-data endpoint.
1005     *
1006     * @return object Site data.
1007     */
1008    public static function get_site() {
1009        $site_id           = \Jetpack_Options::get_option( 'id' );
1010        $wpcom_endpoint    = sprintf( '/sites/%d?force=wpcom', $site_id );
1011        $wpcom_api_version = '1.1';
1012        $response          = Client::wpcom_json_api_request_as_blog( $wpcom_endpoint, $wpcom_api_version );
1013        $response_code     = wp_remote_retrieve_response_code( $response );
1014        $body              = json_decode( wp_remote_retrieve_body( $response ) );
1015
1016        if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
1017            return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
1018        }
1019
1020        return rest_ensure_response( $body );
1021    }
1022
1023    /**
1024     * Populates the self::$site_info var with site data from the /sites/%d endpoint
1025     *
1026     * @return object|WP_Error
1027     */
1028    public static function get_site_info() {
1029        static $site_info = null;
1030
1031        if ( $site_info !== null ) {
1032            return $site_info;
1033        }
1034
1035        // Check for a cached value before doing lookup
1036        $stored_site_info = get_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY );
1037        if ( $stored_site_info !== false ) {
1038            return $stored_site_info;
1039        }
1040
1041        $response = self::get_site();
1042        if ( is_wp_error( $response ) ) {
1043            return $response;
1044        }
1045        $site_info = $response->data;
1046        set_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY, $site_info, DAY_IN_SECONDS );
1047
1048        return $site_info;
1049    }
1050
1051    /**
1052     * Returns whether a site has been determined "commercial" or not.
1053     *
1054     * @return bool|null
1055     */
1056    public static function is_commercial_site() {
1057        if ( is_wp_error( self::$site_info ) ) {
1058            return null;
1059        }
1060
1061        return empty( self::$site_info->options->is_commercial ) ? false : self::$site_info->options->is_commercial;
1062    }
1063
1064    /**
1065     * Check if site is registered (has been connected before).
1066     *
1067     * @return bool
1068     */
1069    public static function is_registered() {
1070        return (bool) \Jetpack_Options::get_option( 'id' );
1071    }
1072
1073    /**
1074     * Dismiss the welcome banner.
1075     *
1076     * @return \WP_REST_Response
1077     */
1078    public static function dismiss_welcome_banner() {
1079        \Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
1080        return rest_ensure_response( array( 'success' => true ) );
1081    }
1082
1083    /**
1084     * Returns "yes" if the site has file write access to the plugins folder, "no" otherwise.
1085     *
1086     * @return string
1087     **/
1088    public static function has_file_system_write_access() {
1089
1090        $cache = get_transient( 'my_jetpack_write_access' );
1091
1092        if ( false !== $cache ) {
1093            return $cache;
1094        }
1095
1096        if ( ! function_exists( 'get_filesystem_method' ) ) {
1097            require_once ABSPATH . 'wp-admin/includes/file.php';
1098        }
1099
1100        require_once ABSPATH . 'wp-admin/includes/template.php';
1101
1102        $write_access = 'no';
1103
1104        $filesystem_method = get_filesystem_method( array(), WP_PLUGIN_DIR );
1105        if ( 'direct' === $filesystem_method ) {
1106            $write_access = 'yes';
1107        }
1108
1109        if ( 'no' === $write_access ) {
1110            ob_start();
1111            $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1112            ob_end_clean();
1113
1114            if ( $filesystem_credentials_are_stored ) {
1115                $write_access = 'yes';
1116            }
1117        }
1118
1119        set_transient( 'my_jetpack_write_access', $write_access, 30 * MINUTE_IN_SECONDS );
1120
1121        return $write_access;
1122    }
1123
1124    /**
1125     * Get container IDC for the IDC screen.
1126     *
1127     * @return string
1128     */
1129    public static function get_idc_container_id() {
1130        return static::IDC_CONTAINER_ID;
1131    }
1132
1133    /**
1134     * Conditionally append the red bubble notification to the "Jetpack" menu item if there are alerts to show.
1135     *
1136     * On My Jetpack page: Uses blocking behavior to fetch fresh data.
1137     * On other admin pages: Uses cached data only to avoid blocking, with async JS fetch if cache is empty.
1138     *
1139     * @return void
1140     */
1141    public static function maybe_show_red_bubble() {
1142        global $pagenow;
1143
1144        // Don't show red bubble alerts for non-admin users
1145        // These alerts are generally only actionable for admins
1146        if ( ! current_user_can( 'manage_options' ) ) {
1147            return;
1148        }
1149
1150        // Don't show any red bubbles when Jetpack is disconnected
1151        // Users can't act on most alerts without a connection
1152        $connection = new Connection_Manager();
1153        if ( ! $connection->is_connected() ) {
1154            return;
1155        }
1156
1157        // Check if we're on the My Jetpack page.
1158        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1159        $page               = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
1160        $is_my_jetpack_page = $pagenow === 'admin.php' && $page === 'my-jetpack';
1161
1162        if ( $is_my_jetpack_page ) {
1163            // On My Jetpack page: use blocking behavior for fresh data.
1164            add_filter( 'my_jetpack_red_bubble_notification_slugs', array( Red_Bubble_Notifications::class, 'add_red_bubble_alerts' ) );
1165            $red_bubble_alerts = Red_Bubble_Notifications::get_red_bubble_alerts();
1166        } else {
1167            // On other pages: use cached data only to avoid blocking.
1168            $cached_alerts = Red_Bubble_Notifications::get_cached_alerts();
1169
1170            if ( false === $cached_alerts ) {
1171                // No cache: warm it asynchronously via JS. Register a hidden zero-count
1172                // placeholder so Menu_Renderer emits a `my-jetpack` badge element the
1173                // warmer can reveal (see async-notification-bubble.ts) without a reload.
1174                Menu_Badges::init(); // idempotent; wires the renderer.
1175                Notification_Counts::register(
1176                    'my-jetpack',
1177                    array(
1178                        'menu_slug' => 'my-jetpack',
1179                        'count'     => 0,
1180                        'type'      => 'count',
1181                    )
1182                );
1183                add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_red_bubble_script' ) );
1184                return;
1185            }
1186
1187            $red_bubble_alerts = $cached_alerts;
1188        }
1189
1190        // Filter out silent alerts.
1191        $red_bubble_alerts = array_filter(
1192            $red_bubble_alerts,
1193            function ( $alert ) {
1194                return empty( $alert['is_silent'] );
1195            }
1196        );
1197
1198        // Report each non-silent alert to the central menu-badges registry as an
1199        // attention entry (count 1). The registry + renderer own the badge.
1200        Menu_Badges::init(); // idempotent; wires the renderer.
1201
1202        // Connection errors are owned by the Error Handler (the single source of truth):
1203        // surface any it reports for this viewer as their own attention entry. Read live
1204        // rather than from the red-bubble transient, since that cache is not viewer-keyed.
1205        $has_connection_error = self::has_connection_error();
1206        if ( $has_connection_error ) {
1207            Notification_Counts::register(
1208                'my-jetpack-connection-error',
1209                array(
1210                    'menu_slug' => 'my-jetpack',
1211                    'type'      => 'attention',
1212                )
1213            );
1214        }
1215
1216        foreach ( array_keys( $red_bubble_alerts ) as $slug ) {
1217            // Protect reports its own count directly to the registry, but only when its
1218            // standalone plugin is active (see class-jetpack-protect.php::admin_page_init()).
1219            // If the standalone plugin isn't active, nobody else registers this count, so we
1220            // must not skip it here or the alert silently disappears from the menu total.
1221            if ( 'protect_has_threats' === $slug && Products\Protect::is_standalone_plugin_active() ) {
1222                continue;
1223            }
1224            // The missing-connection slug and a connection error describe the same broken
1225            // connection; count it once (the error, above, is the more specific signal).
1226            if ( $has_connection_error && 'missing-connection' === $slug ) {
1227                continue;
1228            }
1229            Notification_Counts::register(
1230                'my-jetpack-' . $slug,
1231                array(
1232                    'menu_slug' => 'my-jetpack',
1233                    'type'      => 'attention',
1234                )
1235            );
1236        }
1237    }
1238
1239    /**
1240     * Whether the Connection Error Handler reports a displayable connection error
1241     * for the current viewer.
1242     *
1243     * Read live (not via the red-bubble transient): get_displayable_errors() is a
1244     * cached option read that the Error Handler already scopes and caches per viewer.
1245     * Guarded for the mid-plugin-update window, where a stale connection package
1246     * predating the method can be loaded.
1247     *
1248     * @return bool
1249     */
1250    private static function has_connection_error() {
1251        if ( ! class_exists( Connection_Error_Handler::class ) || ! method_exists( Connection_Error_Handler::class, 'get_displayable_errors' ) ) {
1252            return false;
1253        }
1254        return ! empty( Connection_Error_Handler::get_instance()->get_displayable_errors() );
1255    }
1256
1257    /**
1258     * Enqueue the notification bubble script.
1259     * Fetches fresh alert data via REST API without blocking page load.
1260     *
1261     * @return void
1262     */
1263    public static function enqueue_red_bubble_script() {
1264        Assets::register_script(
1265            'my-jetpack-notification-bubble',
1266            '../build/async-notification-bubble.js',
1267            __FILE__,
1268            array(
1269                'enqueue'   => true,
1270                'in_footer' => true,
1271            )
1272        );
1273    }
1274
1275    /**
1276     * Get list of module names sorted by their recommendation score
1277     *
1278     * @return array|null
1279     */
1280    public static function get_recommended_modules() {
1281        $recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );
1282
1283        if ( empty( $recommendations_evaluation ) || ! is_array( $recommendations_evaluation ) ) {
1284            return null;
1285        }
1286
1287        arsort( $recommendations_evaluation ); // Sort by scores in descending order
1288
1289        return array_keys( $recommendations_evaluation ); // Get only module names
1290    }
1291}