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