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