Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
16.99% covered (danger)
16.99%
53 / 312
7.69% covered (danger)
7.69%
2 / 26
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
16.99% covered (danger)
16.99%
53 / 312
7.69% covered (danger)
7.69%
2 / 26
3649.18
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
4
 is_licensing_ui_enabled
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 add_my_jetpack_menu_item
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 admin_init
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
90
 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
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 enqueue_scripts
0.00% covered (danger)
0.00%
0 / 79
0.00% covered (danger)
0.00%
0 / 1
42
 get_installed_jetpack_plugins
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 get_active_modules
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 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
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 admin_page
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 register_rest_endpoints
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
1
 permissions_callback
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 should_initialize
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 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
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 get_site_info
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 is_commercial_site
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 is_registered
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 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
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
42
 get_idc_container_id
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 maybe_show_red_bubble
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
110
 enqueue_red_bubble_script
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 get_recommended_modules
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
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\Initial_State as Connection_Initial_State;
16use Automattic\Jetpack\Connection\Manager as Connection_Manager;
17use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
18use Automattic\Jetpack\Constants as Jetpack_Constants;
19use Automattic\Jetpack\ExPlat;
20use Automattic\Jetpack\JITMS\JITM;
21use Automattic\Jetpack\Licensing;
22use Automattic\Jetpack\Modules;
23use Automattic\Jetpack\Plugins_Installer;
24use Automattic\Jetpack\Status;
25use Automattic\Jetpack\Status\Host as Status_Host;
26use Automattic\Jetpack\Sync\Functions as Sync_Functions;
27use Automattic\Jetpack\Terms_Of_Service;
28use Automattic\Jetpack\Tracking;
29use Jetpack;
30use WP_Error;
31
32/**
33 * The main Initializer class that registers the admin menu and eneuque the assets.
34 */
35class Initializer {
36
37    /**
38     * My Jetpack package version
39     *
40     * @var string
41     */
42    const PACKAGE_VERSION = '5.37.4';
43
44    /**
45     * HTML container ID for the IDC screen on My Jetpack page.
46     */
47    private const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
48
49    public const JETPACK_PLUGIN_SLUGS = array(
50        'jetpack-backup',
51        'jetpack-boost',
52        'zerobscrm',
53        'jetpack',
54        'jetpack-protect',
55        'jetpack-social',
56        'jetpack-videopress',
57        'jetpack-search',
58    );
59
60    private const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
61
62    /**
63     * Holds info/data about the site (from the /sites/%d endpoint)
64     *
65     * @var object
66     */
67    public static $site_info;
68
69    /**
70     * Initialize My Jetpack
71     *
72     * @return void
73     */
74    public static function init() {
75        if ( ! self::should_initialize() || did_action( 'my_jetpack_init' ) ) {
76            return;
77        }
78
79        // Extend jetpack plugins action links.
80        Products::extend_plugins_action_links();
81
82        // Set up the REST authentication hooks.
83        Connection_Rest_Authentication::init();
84
85        if ( self::is_licensing_ui_enabled() ) {
86            Licensing::instance()->initialize();
87        }
88
89        // Initialize Boost Speed Score
90        new Speed_Score( array(), 'jetpack-my-jetpack' );
91
92        // Add custom WP REST API endoints.
93        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );
94
95        add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );
96
97        add_action( 'admin_init', array( __CLASS__, 'setup_historically_active_jetpack_modules_sync' ) );
98        // This is later than the admin-ui package, which runs on 1000
99        add_action( 'admin_init', array( __CLASS__, 'maybe_show_red_bubble' ), 1001 );
100
101        // Set up the ExPlat package endpoints
102        ExPlat::init();
103
104        // Sets up JITMS.
105        JITM::configure();
106
107        // Add "Jetpack Manage" menu item.
108        Jetpack_Manage::init();
109
110        /**
111         * Fires after the My Jetpack package is initialized
112         *
113         * @since 0.1.0
114         */
115        do_action( 'my_jetpack_init' );
116    }
117
118    /**
119     * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
120     *
121     * @since 1.2.0
122     *
123     * @return boolean
124     */
125    public static function is_licensing_ui_enabled() {
126        // Default changed to true in 1.5.0.
127        $is_enabled = true;
128
129        /*
130         * Bail if My Jetpack is not enabled,
131         * and thus the licensing UI shouldn't be enabled either.
132         */
133        if ( ! self::should_initialize() ) {
134            $is_enabled = false;
135        }
136
137        /**
138         * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
139         *
140         * @param bool $is_enabled Defaults to true.
141         *
142         * @since 1.2.0
143         * @since 1.5.0 Update default value to true.
144         */
145        return apply_filters(
146            'jetpack_my_jetpack_should_enable_add_license_screen',
147            $is_enabled
148        );
149    }
150
151    /**
152     * Add My Jetpack menu item to the admin menu.
153     *
154     * @return void
155     */
156    public static function add_my_jetpack_menu_item() {
157        $page_suffix = Admin_Menu::add_menu(
158            __( 'My Jetpack', 'jetpack-my-jetpack' ),
159            __( 'My Jetpack', 'jetpack-my-jetpack' ),
160            'edit_posts',
161            'my-jetpack',
162            array( __CLASS__, 'admin_page' ),
163            -1
164        );
165        add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
166    }
167
168    /**
169     * Callback for the load my jetpack page hook.
170     *
171     * @return void
172     */
173    public static function admin_init() {
174        $connection = new Connection_Manager();
175
176        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No nonce needed for redirect flow control
177        $step = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';
178
179        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking for partner coupon redemption flow
180        $show_coupon_redemption = isset( $_GET['showCouponRedemption'] );
181
182        // Redirect to Jetpack dashboard for partner coupon redemption
183        if ( $show_coupon_redemption ) {
184            wp_safe_redirect( admin_url( 'admin.php?page=jetpack&showCouponRedemption=1#/dashboard' ) );
185            exit( 0 );
186        }
187
188        // Handle onboarding redirects based on connection status
189        $should_redirect = false;
190        $redirect_args   = array( 'page' => 'my-jetpack' );
191
192        if ( ! $connection->is_connected() && $step !== 'onboarding' ) {
193            // Redirect to onboarding if not connected
194            $redirect_args['step'] = 'onboarding';
195            $should_redirect       = true;
196        } elseif ( $connection->is_connected() && $step === 'onboarding' ) {
197            // Redirect away from onboarding if already connected
198            $should_redirect = true;
199        }
200
201        if ( $should_redirect ) {
202            $admin_page = add_query_arg( $redirect_args, admin_url( 'admin.php' ) );
203            $location   = wp_sanitize_redirect( $admin_page );
204
205            // Remove wp_get_referer filter applied in `fix_redirect` method of `Jetpack_Admin` class
206            remove_filter( 'wp_redirect', 'wp_get_referer' );
207            wp_safe_redirect( $location );
208
209            exit( 0 );
210        }
211
212        // If the user reaches the onboarding page, add a class to the body
213        if ( $step === 'onboarding' ) {
214            add_filter( 'admin_body_class', array( __CLASS__, 'add_onboarding_admin_body_class' ) );
215        }
216
217        self::$site_info = self::get_site_info();
218        add_filter( 'identity_crisis_container_id', array( static::class, 'get_idc_container_id' ) );
219        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
220    }
221
222    /**
223     * Add a body class to the My Jetpack onboarding page.
224     * This class hides the WP Admin toolbar and the sidebar menu.
225     *
226     * @param string $classes The body classes.
227     * @return string The modified body classes.
228     */
229    public static function add_onboarding_admin_body_class( $classes ) {
230        $classes .= 'jetpack-admin-full-screen';
231        return $classes;
232    }
233
234    /**
235     * Returns whether we are in condition to track to use
236     * Analytics functionality like Tracks, MC, or GA.
237     */
238    public static function can_use_analytics() {
239        $status     = new Status();
240        $connection = new Connection_Manager();
241        $tracking   = new Tracking( 'jetpack', $connection );
242
243        return $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
244    }
245
246    /**
247     * Enqueue admin page assets.
248     *
249     * @return void
250     */
251    public static function enqueue_scripts() {
252        /**
253         * Fires after the My Jetpack page is initialized.
254         * Allows for enqueuing additional scripts only on the My Jetpack page.
255         *
256         * @since 4.35.7
257         */
258        do_action( 'myjetpack_enqueue_scripts' );
259        Assets::register_script(
260            'my_jetpack_main_app',
261            '../build/index.js',
262            __FILE__,
263            array(
264                'enqueue'    => true,
265                'in_footer'  => true,
266                'textdomain' => 'jetpack-my-jetpack',
267            )
268        );
269        $modules             = new Modules();
270        $connection          = new Connection_Manager();
271        $speed_score_history = new Speed_Score_History( get_site_url() );
272        $latest_score        = $speed_score_history->latest();
273        $previous_score      = array();
274        if ( $speed_score_history->count() > 1 ) {
275            $previous_score = $speed_score_history->latest( 1 );
276        }
277        $latest_score['previousScores'] = $previous_score['scores'] ?? array();
278
279        $sandboxed_domain = '';
280        $is_dev_version   = false;
281        if ( class_exists( 'Jetpack' ) ) {
282            $is_dev_version   = Jetpack::is_development_version();
283            $sandboxed_domain = defined( 'JETPACK__SANDBOX_DOMAIN' ) ? JETPACK__SANDBOX_DOMAIN : '';
284        }
285
286        wp_localize_script(
287            'my_jetpack_main_app',
288            'myJetpackInitialState',
289            array(
290                'products'               => array(
291                    'items' => Products::get_products(),
292                ),
293                'plugins'                => Plugins_Installer::get_plugins(),
294                'themes'                 => Sync_Functions::get_themes(),
295                'myJetpackUrl'           => admin_url( 'admin.php?page=my-jetpack' ),
296                'myJetpackCheckoutUri'   => admin_url( 'admin.php?page=my-jetpack' ),
297                'topJetpackMenuItemUrl'  => Admin_Menu::get_top_level_menu_item_url(),
298                'siteSuffix'             => ( new Status() )->get_site_suffix(),
299                'siteUrl'                => esc_url( get_site_url() ),
300                'blogID'                 => Connection_Manager::get_site_id( true ),
301                'myJetpackVersion'       => self::PACKAGE_VERSION,
302                'myJetpackFlags'         => self::get_my_jetpack_flags(),
303                'fileSystemWriteAccess'  => self::has_file_system_write_access(),
304                'loadAddLicenseScreen'   => self::is_licensing_ui_enabled(),
305                'adminUrl'               => esc_url( admin_url() ),
306                'IDCContainerID'         => static::get_idc_container_id(),
307                'userIsAdmin'            => current_user_can( 'manage_options' ),
308                'lifecycleStats'         => array(
309                    'jetpackPlugins'            => self::get_installed_jetpack_plugins(),
310                    'historicallyActiveModules' => \Jetpack_Options::get_option( 'historically_active_modules', array() ),
311                    'brokenModules'             => Red_Bubble_Notifications::check_for_broken_modules(),
312                    'isSiteConnected'           => $connection->is_connected(),
313                    'isUserConnected'           => $connection->is_user_connected(),
314                    'modules'                   => self::get_active_modules(),
315                ),
316                'recommendedModules'     => array(
317                    'modules'    => self::get_recommended_modules(),
318                    'isFirstRun' => \Jetpack_Options::get_option( 'recommendations_first_run', true ),
319                    'dismissed'  => \Jetpack_Options::get_option( 'dismissed_recommendations', false ),
320                ),
321                'isStatsModuleActive'    => $modules->is_active( 'stats' ),
322                'canUserViewStats'       => current_user_can( 'manage_options' ) || current_user_can( 'view_stats' ),
323                'sandboxedDomain'        => $sandboxed_domain,
324                'isDevVersion'           => $is_dev_version,
325                'isAtomic'               => ( new Status_Host() )->is_woa_site(),
326                'isJetpackPluginActive'  => class_exists( 'Jetpack' ),
327                'latestBoostSpeedScores' => $latest_score,
328            )
329        );
330
331        wp_localize_script(
332            'my_jetpack_main_app',
333            'myJetpackRest',
334            array(
335                'apiRoot'  => esc_url_raw( rest_url() ),
336                'apiNonce' => wp_create_nonce( 'wp_rest' ),
337            )
338        );
339
340        // Connection Initial State.
341        Connection_Initial_State::render_script( 'my_jetpack_main_app' );
342
343        // Required for Analytics.
344        if ( self::can_use_analytics() ) {
345            Tracking::register_tracks_functions_scripts( true );
346        }
347    }
348
349    /**
350     * Get installed Jetpack plugins
351     *
352     * @return array
353     */
354    public static function get_installed_jetpack_plugins() {
355        $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
356        $plugin_slugs = array_map(
357            static function ( $slug ) {
358                $parts = explode( '/', $slug );
359                // Return the last segment of the filepath without the PHP extension
360                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
361            },
362            $plugin_slugs
363        );
364
365        return array_values( array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs ) );
366    }
367
368    /**
369     * Get active modules (except ones enabled by default)
370     *
371     * @return array
372     */
373    public static function get_active_modules() {
374        $modules        = new Modules();
375        $active_modules = $modules->get_active();
376
377        // if the Jetpack plugin is active, filter out the modules that are active by default
378        if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
379            $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
380        }
381        return array_values( $active_modules );
382    }
383
384    /**
385     * Determine if the current user is "new" to Jetpack
386     * This is used to vary some messaging in My Jetpack
387     *
388     * On the front-end, purchases are also taken into account
389     *
390     * @return bool
391     */
392    public static function is_jetpack_user_new() {
393        // is the user connected?
394        $connection = new Connection_Manager();
395        if ( $connection->is_user_connected() ) {
396            return false;
397        }
398
399        // TODO: add a data point for the last known connection/ disconnection time
400
401        // are any modules active?
402        $active_modules = self::get_active_modules();
403        if ( ! empty( $active_modules ) ) {
404            return false;
405        }
406
407        // check for other Jetpack plugins that are installed on the site (active or not)
408        // If there's more than one Jetpack plugin active, this user is not "new"
409        $plugin_slugs              = array_keys( Plugins_Installer::get_plugins() );
410        $plugin_slugs              = array_map(
411            static function ( $slug ) {
412                $parts = explode( '/', $slug );
413                // Return the last segment of the filepath without the PHP extension
414                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
415            },
416            $plugin_slugs
417        );
418        $installed_jetpack_plugins = array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs );
419        if ( is_countable( $installed_jetpack_plugins ) && count( $installed_jetpack_plugins ) >= 2 ) {
420            return false;
421        }
422
423        // Does the site have any purchases?
424        $purchases = Wpcom_Products::get_site_current_purchases();
425        if ( ! empty( $purchases ) && ! is_wp_error( $purchases ) ) {
426            return false;
427        }
428
429        return true;
430    }
431
432    /**
433     *  Build flags for My Jetpack UI
434     *
435     *  @return array
436     */
437    public static function get_my_jetpack_flags() {
438        $flags = array(
439            'videoPressStats'          => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
440            'showFullJetpackStatsCard' => class_exists( 'Jetpack' ),
441        );
442
443        return $flags;
444    }
445
446    /**
447     * Echoes the admin page content.
448     *
449     * @return void
450     */
451    public static function admin_page() {
452        $step          = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
453        $is_onboarding = $step === 'onboarding';
454
455        // Add data attribute for onboarding, otherwise render normal container
456        echo '<div id="my-jetpack-container" ' . ( $is_onboarding ? 'data-route="onboarding"' : '' ) . '></div>';
457    }
458
459    /**
460     * Register the REST API routes.
461     *
462     * @return void
463     */
464    public static function register_rest_endpoints() {
465        new REST_Products();
466        new REST_Purchases();
467        new REST_Zendesk_Chat();
468        new REST_AI();
469        new REST_Recommendations_Evaluation();
470
471        Products::register_product_endpoints();
472        Historically_Active_Modules::register_rest_endpoints();
473        Jetpack_Manage::register_rest_endpoints();
474        Red_Bubble_Notifications::register_rest_endpoints();
475
476        register_rest_route(
477            'my-jetpack/v1',
478            'site',
479            array(
480                'methods'             => \WP_REST_Server::READABLE,
481                'callback'            => __CLASS__ . '::get_site',
482                'permission_callback' => __CLASS__ . '::permissions_callback',
483            )
484        );
485
486        register_rest_route(
487            'my-jetpack/v1',
488            'site/dismiss-welcome-banner',
489            array(
490                'methods'             => \WP_REST_Server::EDITABLE,
491                'callback'            => __CLASS__ . '::dismiss_welcome_banner',
492                'permission_callback' => __CLASS__ . '::permissions_callback',
493            )
494        );
495    }
496
497    /**
498     * Check user capability to access the endpoint.
499     *
500     * @access public
501     * @static
502     *
503     * @return true|WP_Error
504     */
505    public static function permissions_callback() {
506        return current_user_can( 'manage_options' );
507    }
508
509    /**
510     * Return true if we should initialize the My Jetpack admin page.
511     */
512    public static function should_initialize() {
513        $should = true;
514
515        // All options presented in My Jetpack require a connection to WordPress.com.
516        if ( ( new Status() )->is_offline_mode() ) {
517            $should = false;
518        }
519
520        /**
521         * Allows filtering whether My Jetpack should be initialized.
522         *
523         * @since 0.5.0-alpha
524         *
525         * @param bool $shoud_initialize Should we initialize My Jetpack?
526         */
527        return apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
528    }
529
530    /**
531     * Hook into several connection-based actions to update the historically active Jetpack modules
532     * If the transient that indicates the list needs to be synced, update it and delete the transient
533     *
534     * @return void
535     */
536    public static function setup_historically_active_jetpack_modules_sync() {
537        // yummmm. ham.
538        $ham = new Historically_Active_Modules();
539        if ( get_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY ) && ! wp_doing_ajax() ) {
540            $ham::update_historically_active_jetpack_modules();
541            delete_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY );
542        }
543
544        $actions = array(
545            'jetpack_site_registered',
546            'jetpack_user_authorized',
547            'activated_plugin',
548        );
549
550        foreach ( $actions as $action ) {
551            add_action( $action, array( $ham, 'queue_historically_active_jetpack_modules_update' ), 5 );
552        }
553
554        // Modules are often updated async, so we need to update them right away as there will sometimes be no page reload.
555        add_action( 'jetpack_activate_module', array( $ham, 'update_historically_active_jetpack_modules' ), 5 );
556    }
557
558    /**
559     * Site full-data endpoint.
560     *
561     * @return object Site data.
562     */
563    public static function get_site() {
564        $site_id           = \Jetpack_Options::get_option( 'id' );
565        $wpcom_endpoint    = sprintf( '/sites/%d?force=wpcom', $site_id );
566        $wpcom_api_version = '1.1';
567        $response          = Client::wpcom_json_api_request_as_blog( $wpcom_endpoint, $wpcom_api_version );
568        $response_code     = wp_remote_retrieve_response_code( $response );
569        $body              = json_decode( wp_remote_retrieve_body( $response ) );
570
571        if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
572            return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
573        }
574
575        return rest_ensure_response( $body );
576    }
577
578    /**
579     * Populates the self::$site_info var with site data from the /sites/%d endpoint
580     *
581     * @return object|WP_Error
582     */
583    public static function get_site_info() {
584        static $site_info = null;
585
586        if ( $site_info !== null ) {
587            return $site_info;
588        }
589
590        // Check for a cached value before doing lookup
591        $stored_site_info = get_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY );
592        if ( $stored_site_info !== false ) {
593            return $stored_site_info;
594        }
595
596        $response = self::get_site();
597        if ( is_wp_error( $response ) ) {
598            return $response;
599        }
600        $site_info = $response->data;
601        set_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY, $site_info, DAY_IN_SECONDS );
602
603        return $site_info;
604    }
605
606    /**
607     * Returns whether a site has been determined "commercial" or not.
608     *
609     * @return bool|null
610     */
611    public static function is_commercial_site() {
612        if ( is_wp_error( self::$site_info ) ) {
613            return null;
614        }
615
616        return empty( self::$site_info->options->is_commercial ) ? false : self::$site_info->options->is_commercial;
617    }
618
619    /**
620     * Check if site is registered (has been connected before).
621     *
622     * @return bool
623     */
624    public static function is_registered() {
625        return (bool) \Jetpack_Options::get_option( 'id' );
626    }
627
628    /**
629     * Dismiss the welcome banner.
630     *
631     * @return \WP_REST_Response
632     */
633    public static function dismiss_welcome_banner() {
634        \Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
635        return rest_ensure_response( array( 'success' => true ) );
636    }
637
638    /**
639     * Returns "yes" if the site has file write access to the plugins folder, "no" otherwise.
640     *
641     * @return string
642     **/
643    public static function has_file_system_write_access() {
644
645        $cache = get_transient( 'my_jetpack_write_access' );
646
647        if ( false !== $cache ) {
648            return $cache;
649        }
650
651        if ( ! function_exists( 'get_filesystem_method' ) ) {
652            require_once ABSPATH . 'wp-admin/includes/file.php';
653        }
654
655        require_once ABSPATH . 'wp-admin/includes/template.php';
656
657        $write_access = 'no';
658
659        $filesystem_method = get_filesystem_method( array(), WP_PLUGIN_DIR );
660        if ( 'direct' === $filesystem_method ) {
661            $write_access = 'yes';
662        }
663
664        if ( 'no' === $write_access ) {
665            ob_start();
666            $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
667            ob_end_clean();
668
669            if ( $filesystem_credentials_are_stored ) {
670                $write_access = 'yes';
671            }
672        }
673
674        set_transient( 'my_jetpack_write_access', $write_access, 30 * MINUTE_IN_SECONDS );
675
676        return $write_access;
677    }
678
679    /**
680     * Get container IDC for the IDC screen.
681     *
682     * @return string
683     */
684    public static function get_idc_container_id() {
685        return static::IDC_CONTAINER_ID;
686    }
687
688    /**
689     * Conditionally append the red bubble notification to the "Jetpack" menu item if there are alerts to show.
690     *
691     * On My Jetpack page: Uses blocking behavior to fetch fresh data.
692     * On other admin pages: Uses cached data only to avoid blocking, with async JS fetch if cache is empty.
693     *
694     * @return void
695     */
696    public static function maybe_show_red_bubble() {
697        global $menu, $pagenow;
698
699        // Don't show red bubble alerts for non-admin users
700        // These alerts are generally only actionable for admins
701        if ( ! current_user_can( 'manage_options' ) ) {
702            return;
703        }
704
705        // Don't show any red bubbles when Jetpack is disconnected
706        // Users can't act on most alerts without a connection
707        $connection = new Connection_Manager();
708        if ( ! $connection->is_connected() ) {
709            return;
710        }
711
712        // Check if we're on the My Jetpack page.
713        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
714        $page               = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
715        $is_my_jetpack_page = $pagenow === 'admin.php' && $page === 'my-jetpack';
716
717        if ( $is_my_jetpack_page ) {
718            // On My Jetpack page: use blocking behavior for fresh data.
719            add_filter( 'my_jetpack_red_bubble_notification_slugs', array( Red_Bubble_Notifications::class, 'add_red_bubble_alerts' ) );
720            $red_bubble_alerts = Red_Bubble_Notifications::get_red_bubble_alerts();
721        } else {
722            // On other pages: use cached data only to avoid blocking.
723            $cached_alerts = Red_Bubble_Notifications::get_cached_alerts();
724
725            if ( false === $cached_alerts ) {
726                // No cache - fetch asynchronously via JS.
727                add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_red_bubble_script' ) );
728                return;
729            }
730
731            $red_bubble_alerts = $cached_alerts;
732        }
733
734        // Filter out silent alerts.
735        $red_bubble_alerts = array_filter(
736            $red_bubble_alerts,
737            function ( $alert ) {
738                return empty( $alert['is_silent'] );
739            }
740        );
741
742        // The Jetpack menu item should be on index 3
743        if (
744            ! empty( $red_bubble_alerts ) &&
745            isset( $menu[3] ) &&
746            $menu[3][0] === 'Jetpack'
747        ) {
748            // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
749            $menu[3][0] .= sprintf( ' <span class="awaiting-mod">%d</span>', count( $red_bubble_alerts ) );
750        }
751    }
752
753    /**
754     * Enqueue the notification bubble script.
755     * Fetches fresh alert data via REST API without blocking page load.
756     *
757     * @return void
758     */
759    public static function enqueue_red_bubble_script() {
760        Assets::register_script(
761            'my-jetpack-notification-bubble',
762            '../build/async-notification-bubble.js',
763            __FILE__,
764            array(
765                'enqueue'   => true,
766                'in_footer' => true,
767            )
768        );
769    }
770
771    /**
772     * Get list of module names sorted by their recommendation score
773     *
774     * @return array|null
775     */
776    public static function get_recommended_modules() {
777        $recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );
778
779        if ( ! $recommendations_evaluation ) {
780            return null;
781        }
782
783        arsort( $recommendations_evaluation ); // Sort by scores in descending order
784
785        return array_keys( $recommendations_evaluation ); // Get only module names
786    }
787}