Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.27% covered (warning)
85.27%
735 / 862
73.75% covered (warning)
73.75%
59 / 80
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
85.27% covered (warning)
85.27%
735 / 862
73.75% covered (warning)
73.75%
59 / 80
617.34
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
7
 use_local_module_options
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
6.05
 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
86.67% covered (warning)
86.67%
13 / 15
0.00% covered (danger)
0.00%
0 / 1
6.09
 is_onboarding_settled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 maybe_redirect_to_onboarding
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 get_onboarding_redirect_args_for_step
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 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%
10 / 10
100.00% covered (success)
100.00%
1 / 1
12
 silence_onboarding_notices
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 hide_onboarding_jitms
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 add_onboarding_admin_body_class
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 can_use_analytics
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 is_onboarding_wizard_enabled
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 has_never_registered_jetpack
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_onboarding_wizard_state
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 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%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 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
 add_admin_shell_member
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
20
 load_as_admin_shell_guest
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 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
97.01% covered (success)
97.01%
130 / 134
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
 get_plan_urls
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 add_script_data
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 is_modules_rest_api_enabled
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 get_modules_management_url
51.43% covered (warning)
51.43%
36 / 70
0.00% covered (danger)
0.00%
0 / 1
244.13
 print_modules_fallback
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
10
 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%
23 / 23
100.00% covered (success)
100.00%
1 / 1
8
 get_registered_admin_page_slugs
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 is_admin_page_available
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_assets_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_installed_jetpack_plugins
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 get_active_modules
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 is_jetpack_user_new
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
56
 register_feature_flags
100.00% covered (success)
100.00%
42 / 42
100.00% covered (success)
100.00%
1 / 1
2
 is_header_controls_enabled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 maybe_enqueue_header_controls_script
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 get_my_jetpack_flags
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 is_overview_v1_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 host_shows_my_jetpack
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_settings_consolidation_on_for_site
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_settings_consolidation_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 shows_settings_notices
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 get_settings_notices_state
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 register_settings_panel_urls
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 resolve_settings_url
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_settings_panel_url
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 is_modules_to_features_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_seo_opt_in_state
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 admin_page
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 register_rest_endpoints
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
3
 permissions_callback
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 should_initialize
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
7
 is_offline_features_enabled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 setup_historically_active_jetpack_modules_sync
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 get_site
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 get_site_info
58.33% covered (warning)
58.33%
7 / 12
0.00% covered (danger)
0.00%
0 / 1
5.16
 is_commercial_site
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 is_registered
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 dismiss_welcome_banner
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 has_file_system_write_access
61.11% covered (warning)
61.11%
11 / 18
0.00% covered (danger)
0.00%
0 / 1
8.12
 get_idc_container_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 maybe_show_red_bubble
96.23% covered (success)
96.23%
51 / 53
0.00% covered (danger)
0.00%
0 / 1
12
 has_connection_error
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 get_alerts_counted_elsewhere
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 enqueue_red_bubble_script
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
 get_recommended_modules
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * WP Admin page with information and configuration shared among all Jetpack stand-alone plugins
4 *
5 * @package automattic/my-jetpack
6 */
7
8namespace Automattic\Jetpack\My_Jetpack;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Admin_UI\Admin_Shell;
12use Automattic\Jetpack\Assets;
13use Automattic\Jetpack\Boost_Speed_Score\Speed_Score;
14use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_History;
15use Automattic\Jetpack\Connection\Client;
16use Automattic\Jetpack\Connection\Error_Handler as Connection_Error_Handler;
17use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
18use Automattic\Jetpack\Connection\Manager as Connection_Manager;
19use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
20use Automattic\Jetpack\Connection\REST_Jetpack_AI_JWT;
21use Automattic\Jetpack\Constants as Jetpack_Constants;
22use Automattic\Jetpack\CookieState;
23use Automattic\Jetpack\ExPlat;
24use Automattic\Jetpack\Feature_Flags\Feature_Flags;
25use Automattic\Jetpack\JITMS\JITM;
26use Automattic\Jetpack\Licensing;
27use Automattic\Jetpack\Menu_Badges\Menu_Badges;
28use Automattic\Jetpack\Menu_Badges\Notification_Counts;
29use Automattic\Jetpack\Modules;
30use Automattic\Jetpack\Partner_Coupon;
31use Automattic\Jetpack\Plugins_Installer;
32use Automattic\Jetpack\Status;
33use Automattic\Jetpack\Status\Host as Status_Host;
34use Automattic\Jetpack\Sync\Functions as Sync_Functions;
35use Automattic\Jetpack\Terms_Of_Service;
36use Automattic\Jetpack\Tracking;
37use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
38use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
39use Jetpack;
40use WP_Error;
41
42/**
43 * The main Initializer class that registers the admin menu and eneuque the assets.
44 */
45class Initializer {
46
47    /**
48     * My Jetpack package version
49     *
50     * @var string
51     */
52    const PACKAGE_VERSION = '6.19.0';
53
54    /**
55     * Feature flag that swaps the single-screen onboarding takeover for the setup wizard.
56     */
57    const ONBOARDING_WIZARD_FEATURE_FLAG = 'my-jetpack-onboarding-wizard';
58
59    /**
60     * User option recording that this user chose to skip setup.
61     *
62     * Per user rather than per site, because skipping is one person saying "not
63     * now": a second admin arriving at a site nobody has set up should still be
64     * offered the flow. Finishing it is the site-wide fact, and that is
65     * ONBOARDING_COMPLETED_OPTION.
66     *
67     * A user option rather than plain user meta: `wp_usermeta` is network-wide, so
68     * without the blog prefix a skip on one site would silence setup on all of them.
69     */
70    const ONBOARDING_DISMISSED_USER_OPTION = 'jetpack_my_jetpack_onboarding_dismissed';
71
72    /**
73     * Option recording that someone has finished setup on this site.
74     *
75     * Site-wide, because the flow connects the site and switches modules on, so a
76     * second admin does not need it again. Deliberately not autoloaded.
77     */
78    const ONBOARDING_COMPLETED_OPTION = 'jetpack_my_jetpack_onboarding_completed';
79
80    /**
81     * Handle for the classic script that carries the React initial state.
82     *
83     * Plugins that render My Jetpack components on their own pages (Boost) depend on this name.
84     */
85    const DATA_SCRIPT_HANDLE = 'my_jetpack_main_app';
86
87    /**
88     * Handle for the webpack bundle that renders the onboarding takeover.
89     */
90    const ONBOARDING_SCRIPT_HANDLE = 'my_jetpack_onboarding';
91
92    /**
93     * Handle for the webpack bundle that gives dashboards outside My Jetpack the shared header's controls.
94     */
95    const HEADER_CONTROLS_SCRIPT_HANDLE = 'my-jetpack-header-controls';
96
97    /**
98     * The wp-build page ID, which the generated enqueue check expects as the screen ID.
99     */
100    const WP_BUILD_PAGE_ID = 'my-jetpack-dashboard';
101
102    /**
103     * HTML container ID for the IDC screen on My Jetpack page.
104     */
105    private const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
106
107    public const JETPACK_PLUGIN_SLUGS = array(
108        'jetpack-backup',
109        'jetpack-boost',
110        'zerobscrm',
111        'jetpack',
112        'jetpack-protect',
113        'jetpack-social',
114        'jetpack-videopress',
115        'jetpack-search',
116        'jetpack-stats',
117    );
118
119    private const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
120
121    /**
122     * Feature flag for connecting the WordPress.com account from a Features card that needs one.
123     *
124     * @var string
125     */
126    public const ACCOUNT_CONNECT_FLAG = 'my-jetpack-account-connect';
127
128    /**
129     * Feature flag for the shared header's global controls.
130     *
131     * @var string
132     */
133    public const HEADER_CONTROLS_FLAG = 'my-jetpack-header-controls';
134
135    /**
136     * Feature flag for Overview v1.
137     *
138     * @var string
139     */
140    public const OVERVIEW_V1_FLAG = 'my-jetpack-overview-v1';
141
142    /**
143     * Feature flag for sending classic Modules links to Features.
144     *
145     * @var string
146     */
147    public const MODULES_TO_FEATURES_FLAG = 'my-jetpack-modules-to-features';
148
149    /**
150     * Feature flag for consolidating settings in My Jetpack instead of the Settings screen.
151     *
152     * @var string
153     */
154    public const SETTINGS_CONSOLIDATION_FLAG = 'my-jetpack-settings-consolidation';
155
156    /**
157     * Modules whose Jetpack settings link opens in the Features panel. A subset of `moduleSettings` in `settings-panel/registry.ts`; see there for which modules stay out.
158     */
159    public const SETTINGS_PANEL_MODULES = array( 'carousel', 'comments', 'infinite-scroll', 'markdown', 'post-by-email', 'related-posts' );
160
161    /**
162     * Holds info/data about the site (from the /sites/%d endpoint)
163     *
164     * @var object
165     */
166    public static $site_info;
167
168    /**
169     * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
170     *
171     * @var string|null
172     */
173    private static $wp_build_original_screen_id = null;
174
175    /**
176     * Initialize My Jetpack
177     *
178     * @return void
179     */
180    public static function init() {
181        self::register_feature_flags();
182
183        // Before the gate: the Jetpack plugin renders this package's connection screen and footer
184        // links even where My Jetpack is off, and `myJetpackInitialState` only exists on its own page.
185        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_admin_script_data' ) );
186        add_action( 'admin_head', array( __CLASS__, 'print_modules_fallback' ) );
187
188        if ( ! self::should_initialize() || did_action( 'my_jetpack_init' ) ) {
189            return;
190        }
191
192        if ( self::is_offline_features_enabled() ) {
193            add_filter( 'jetpack_my_jetpack_should_enable_add_license_screen', '__return_false' );
194            Connection_Rest_Authentication::init();
195            add_filter( 'rest_request_before_callbacks', array( __CLASS__, 'use_local_module_options' ), 10, 3 );
196            add_filter( 'rest_request_after_callbacks', array( __CLASS__, 'restore_module_options' ), 10, 3 );
197            add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );
198            add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
199            add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );
200            do_action( 'my_jetpack_init' );
201            return;
202        }
203
204        // Answer "is this product on?" for admin menu registration.
205        Menu_Visibility::init();
206        Turned_Off_Page::init();
207
208        self::register_settings_panel_urls();
209
210        // Extend jetpack plugins action links.
211        Products::extend_plugins_action_links();
212
213        // Set up the REST authentication hooks.
214        Connection_Rest_Authentication::init();
215
216        if ( self::is_licensing_ui_enabled() ) {
217            Licensing::instance()->initialize();
218        }
219
220        // Initialize Boost Speed Score
221        new Speed_Score( array(), 'jetpack-my-jetpack' );
222
223        // Add custom WP REST API endoints.
224        add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );
225
226        // Both of wp-build's deadlines fall later in this request: its enqueue check must be
227        // hooked before `admin_enqueue_scripts`, and its render function defined before
228        // the page callback.
229        add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
230
231        add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );
232
233        if ( class_exists( Admin_Shell::class ) ) {
234            add_filter( 'jetpack_admin_shell_members', array( __CLASS__, 'add_admin_shell_member' ) );
235            // Standalone plugins reach admin-ui only through the admin menu, which admin-ajax never builds.
236            if ( method_exists( Admin_Shell::class, 'init' ) ) {
237                Admin_Shell::init();
238            }
239        }
240
241        add_action( 'admin_init', array( __CLASS__, 'setup_historically_active_jetpack_modules_sync' ) );
242
243        // Not on admin_init: modules are usually toggled over REST, where admin_init never fires.
244        add_action( 'jetpack_activate_module', array( Historically_Active_Modules::class, 'expire_refresh' ) );
245        add_action( 'jetpack_deactivate_module', array( Historically_Active_Modules::class, 'expire_refresh' ) );
246
247        // Nothing else gets to talk over the takeover. See both methods for why it
248        // takes two hooks rather than one.
249        add_action( 'in_admin_header', array( __CLASS__, 'silence_onboarding_notices' ), PHP_INT_MAX );
250        add_filter( 'jetpack_display_jitms_on_screen', array( __CLASS__, 'hide_onboarding_jitms' ), 10, 2 );
251        // Registered on admin_menu (not admin_init) and well before priority 100000, so the
252        // counts it registers exist before the menu-badges renderer runs on admin_menu 100000.
253        add_action( 'admin_menu', array( __CLASS__, 'maybe_show_red_bubble' ), 30 );
254
255        // Set up the ExPlat package endpoints
256        ExPlat::init();
257
258        // Sets up JITMS.
259        JITM::configure();
260
261        // Track whether the user is an agency, for the Automattic for Agencies banner.
262        Jetpack_Manage::init();
263
264        /**
265         * Fires after the My Jetpack package is initialized
266         *
267         * @since 0.1.0
268         */
269        do_action( 'my_jetpack_init' );
270    }
271
272    /**
273     * Keep uncached module-list options local on the offline route.
274     *
275     * @since 6.10.0
276     * @param mixed            $response Response before the callback.
277     * @param array            $handler  Route handler.
278     * @param \WP_REST_Request $request  REST request.
279     * @return mixed
280     */
281    public static function use_local_module_options( $response, $handler, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- WordPress REST filter signature.
282        if ( '/jetpack/v4/module/all' === $request->get_route() ) {
283            // Keep module activation editable when the standalone plugin is not running;
284            // a stale autoloaded VideoPress class can still attach its forcing filter.
285            if ( ! Jetpack_Constants::is_defined( 'JETPACK_VIDEOPRESS_ROOT_FILE' )
286                && ! Products\Videopress::is_standalone_plugin_active()
287                && remove_filter( 'jetpack_active_modules', array( \Automattic\Jetpack\VideoPress\Module_Control::class, 'add_videopress_to_array' ) )
288                && class_exists( 'Jetpack_Modules_Overrides', false )
289            ) {
290                \Jetpack_Modules_Overrides::instance()->clear_cache();
291            }
292            add_filter( 'default_option_monitor_receive_notifications', '__return_false' );
293            add_filter( 'default_option_post_by_email_address' . get_current_user_id(), '__return_false' );
294        }
295        return $response;
296    }
297
298    /**
299     * Restore normal option reads after the offline module-list callback.
300     *
301     * @since 6.10.0
302     * @param mixed            $response Response after the callback.
303     * @param array            $handler  Route handler.
304     * @param \WP_REST_Request $request  REST request.
305     * @return mixed
306     */
307    public static function restore_module_options( $response, $handler, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- WordPress REST filter signature.
308        if ( '/jetpack/v4/module/all' === $request->get_route() ) {
309            remove_filter( 'default_option_monitor_receive_notifications', '__return_false' );
310            remove_filter( 'default_option_post_by_email_address' . get_current_user_id(), '__return_false' );
311        }
312        return $response;
313    }
314
315    /**
316     * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
317     *
318     * @since 1.2.0
319     *
320     * @return boolean
321     */
322    public static function is_licensing_ui_enabled() {
323        // Default changed to true in 1.5.0.
324        $is_enabled = true;
325
326        /*
327         * Bail if My Jetpack is not enabled,
328         * and thus the licensing UI shouldn't be enabled either.
329         */
330        if ( ! self::should_initialize() ) {
331            $is_enabled = false;
332        }
333
334        /**
335         * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
336         *
337         * @param bool $is_enabled Defaults to true.
338         *
339         * @since 1.2.0
340         * @since 1.5.0 Update default value to true.
341         */
342        return apply_filters(
343            'jetpack_my_jetpack_should_enable_add_license_screen',
344            $is_enabled
345        );
346    }
347
348    /**
349     * Add My Jetpack menu item to the admin menu.
350     *
351     * @return void
352     */
353    public static function add_my_jetpack_menu_item() {
354        if ( self::is_offline_features_enabled() && ! self::current_user_can_access_page() ) {
355            return;
356        }
357
358        $position    = defined( Admin_Menu::class . '::POSITION_FIRST' ) ? Admin_Menu::POSITION_FIRST : -10;
359        $menu_slug   = 'my-jetpack';
360        $page_suffix = Admin_Menu::add_menu(
361            __( 'My Jetpack', 'jetpack-my-jetpack' ),
362            __( 'My Jetpack', 'jetpack-my-jetpack' ),
363            'edit_posts',
364            $menu_slug,
365            array( __CLASS__, 'admin_page' ),
366            $position
367        );
368        add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
369        // Users who can edit posts but have no Jetpack menu get an admin_page_ hook instead.
370        add_action( 'load-admin_page_' . $menu_slug, array( __CLASS__, 'admin_init' ) );
371    }
372
373    /**
374     * Whether the current user may access the page selected by My Jetpack.
375     *
376     * @since 6.10.0
377     * @return bool
378     */
379    public static function current_user_can_access_page() {
380        return current_user_can( 'edit_posts' )
381            && ( ! self::is_offline_features_enabled() || REST_Main_Features::permissions_callback() );
382    }
383
384    /**
385     * Callback for the load my jetpack page hook.
386     *
387     * @return void
388     */
389    public static function admin_init() {
390        // Read the Jetpack state before any output: reading it deletes its cookie.
391        if ( self::shows_settings_notices() ) {
392            ( new CookieState() )->state();
393        }
394
395        if ( self::is_offline_features_enabled() ) {
396            if ( ! self::current_user_can_access_page() ) {
397                wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'jetpack-my-jetpack' ), 403 );
398            }
399            add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
400            return;
401        }
402
403        self::maybe_redirect_to_onboarding();
404
405        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No nonce needed for redirect flow control
406        $step = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';
407
408        // If the user reaches the onboarding page, add a class to the body
409        if ( $step === 'onboarding' ) {
410            add_filter( 'admin_body_class', array( __CLASS__, 'add_onboarding_admin_body_class' ) );
411        }
412
413        self::$site_info = self::get_site_info();
414        add_filter( 'identity_crisis_container_id', array( static::class, 'get_idc_container_id' ) );
415        // The Safe Mode window shows the new screen itself.
416        add_filter( 'jetpack_identity_crisis_show_notice', '__return_false' );
417        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
418    }
419
420    /**
421     * Whether this user has already settled setup, one way or the other.
422     *
423     * Two separate facts. Finishing is site-wide: the wizard connects the site and
424     * switches modules on, so once it is done nobody needs the takeover again.
425     * Skipping is this person saying "not now", and it must not answer for the next
426     * admin who arrives at a site nobody has set up.
427     *
428     * @internal Not part of the package's public API.
429     *
430     * @return bool
431     */
432    public static function is_onboarding_settled() {
433        if ( get_option( self::ONBOARDING_COMPLETED_OPTION, false ) ) {
434            return true;
435        }
436
437        return (bool) get_user_option( self::ONBOARDING_DISMISSED_USER_OPTION );
438    }
439
440    /**
441     * Send the user into setup when they land on My Jetpack without one.
442     *
443     * Runs from My Jetpack's own page load, which nothing but a request for that page
444     * reaches and which fires before any output, so it needs no guards of its own.
445     *
446     * @return void
447     */
448    public static function maybe_redirect_to_onboarding() {
449        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No nonce needed for redirect flow control
450        $step          = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';
451        $redirect_args = self::get_onboarding_redirect_args_for_step( $step );
452
453        if ( null === $redirect_args ) {
454            return;
455        }
456
457        $location = wp_sanitize_redirect( add_query_arg( $redirect_args, admin_url( 'admin.php' ) ) );
458
459        // Remove wp_get_referer filter applied in `fix_redirect` method of `Jetpack_Admin` class
460        remove_filter( 'wp_redirect', 'wp_get_referer' );
461        wp_safe_redirect( $location );
462
463        exit( 0 );
464    }
465
466    /**
467     * Get the setup redirect for the current user and site at the requested step.
468     *
469     * @param string $step The requested setup step, or empty for the dashboard.
470     * @return array|null Query args for the redirect, or null to stay on the page.
471     */
472    private static function get_onboarding_redirect_args_for_step( $step ) {
473        $wizard_enabled = self::is_onboarding_wizard_enabled();
474        $connection     = new Connection_Manager();
475
476        // Only the wizard connects a user, so only it may count a site-only connection as
477        // unfinished setup. The single screen can only register the site, so asking it for
478        // an owner leaves that site on a screen with no way back out.
479        $connection_done = $wizard_enabled ? $connection->has_connected_owner() : $connection->is_connected();
480
481        // Onboarding's only action is the connect request, which answers a user
482        // without `jetpack_connect` with a 403.
483        return self::get_onboarding_redirect_args(
484            $step,
485            $connection_done,
486            self::is_onboarding_available() && current_user_can( 'jetpack_connect' ),
487            $wizard_enabled,
488            // Only the wizard records a settled run, and only a registered site may act on one:
489            // My Jetpack requires the site connection that accepting the terms creates.
490            $wizard_enabled && $connection->is_connected() && self::is_onboarding_settled()
491        );
492    }
493
494    /**
495     * Whether the My Jetpack onboarding flow is available on this site.
496     *
497     * WordPress.com Simple sites are connected by definition and don't manage their
498     * connection through My Jetpack, so the onboarding flow (which asks the user to
499     * connect) never applies there. A pending partner coupon brings its own connect screen.
500     *
501     * @internal Not part of the package's public API.
502     *
503     * @return bool
504     */
505    public static function is_onboarding_available() {
506        if ( self::is_offline_features_enabled() ) {
507            return false;
508        }
509        return ! ( new Status_Host() )->is_wpcom_simple() && null === self::get_partner_coupon_screen();
510    }
511
512    /**
513     * The partner coupon screen's data, when it should replace the dashboard.
514     *
515     * Coupons exist only with the Jetpack plugin, which supplies their products and images.
516     *
517     * @since 6.5.0
518     *
519     * @return array{coupon: array, assetBaseUrl: string}|null
520     */
521    public static function get_partner_coupon_screen() {
522        if (
523            self::is_offline_features_enabled()
524            || ! self::should_initialize()
525            || ! current_user_can( 'manage_options' )
526            || ! Jetpack_Constants::is_defined( 'JETPACK__PLUGIN_FILE' )
527        ) {
528            return null;
529        }
530
531        $coupon = Partner_Coupon::get_coupon();
532        if ( ! $coupon ) {
533            return null;
534        }
535
536        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks which screen renders.
537        if ( ! isset( $_GET['showCouponRedemption'] ) && ( new Connection_Manager() )->has_connected_owner() ) {
538            return null;
539        }
540
541        return array(
542            'coupon'       => $coupon,
543            'assetBaseUrl' => plugins_url( '', Jetpack_Constants::get_constant( 'JETPACK__PLUGIN_FILE' ) ),
544        );
545    }
546
547    /**
548     * Decide whether the current My Jetpack request should redirect, and where to.
549     *
550     * @internal Not part of the package's public API.
551     *
552     * @param string $step                 The current `step` query param.
553     * @param bool   $connection_done      Whether the connection the takeover asks for is in place:
554     *                                     a connected owner with the wizard, a connected site without it.
555     * @param bool   $onboarding_available Whether the onboarding flow is available on this site.
556     * @param bool   $wizard_enabled       Whether the takeover renders the setup wizard.
557     * @param bool   $is_settled           Whether this user has already finished or skipped setup.
558     * @return array|null Query args for the redirect, or null to stay on the current page.
559     */
560    public static function get_onboarding_redirect_args( $step, $connection_done, $onboarding_available, $wizard_enabled = false, $is_settled = false ) {
561        /*
562         * Only the automatic redirect is suppressed once setup is settled. Asking for
563         * the onboarding page by its own URL still works, so someone who skipped can
564         * go back to it, and so can a second admin the site-wide flag does not cover.
565         */
566        if ( $onboarding_available && ! $connection_done && ! $is_settled && $step !== 'onboarding' ) {
567            // The connection setup asks for is not in place, so setup is unfinished.
568            return array(
569                'page' => 'my-jetpack',
570                'step' => 'onboarding',
571            );
572        }
573
574        // The wizard connects mid-flow: the user authorizes on WordPress.com and is sent
575        // back here to finish setup, so arriving connected is not the same as finishing.
576        if ( $step === 'onboarding' && $connection_done && $onboarding_available && $wizard_enabled ) {
577            return null;
578        }
579
580        if ( $step === 'onboarding' && ( ! $onboarding_available || $connection_done ) ) {
581            // Nothing left to set up here, or onboarding does not apply on this site.
582            return array( 'page' => 'my-jetpack' );
583        }
584
585        return null;
586    }
587
588    /**
589     * Empty the notice channels while the takeover is on screen.
590     *
591     * The takeover hides `.notice`, `.error` and `.updated` in CSS, which only
592     * catches notices that use WordPress's own classes. Plenty do not, and a plugin
593     * announcing itself in its own markup lands on top of a full-screen flow that
594     * has no way to scroll past it.
595     *
596     * On `in_admin_header`, the last hook before `admin-header.php` prints notices,
597     * so a notice registered late is caught too.
598     *
599     * @return void
600     */
601    public static function silence_onboarding_notices() {
602        if ( ! self::is_onboarding_request() ) {
603            return;
604        }
605
606        remove_all_actions( 'admin_notices' );
607        remove_all_actions( 'all_admin_notices' );
608        remove_all_actions( 'network_admin_notices' );
609        remove_all_actions( 'user_admin_notices' );
610    }
611
612    /**
613     * Keep Just In Time Messages off the takeover.
614     *
615     * Emptying the notice channels above would also drop the JITM, since that is how
616     * it renders, but only after it has enqueued its script and stylesheet. This is
617     * the package's own opt-out and it runs before any of that.
618     *
619     * The screen id cannot answer this on its own: the takeover and the My Jetpack
620     * dashboard are the same screen, and only the query arg separates them.
621     *
622     * @param bool   $show      Whether to show JITMs on this screen.
623     * @param string $screen_id The current screen's id.
624     * @return bool
625     */
626    public static function hide_onboarding_jitms( $show, $screen_id ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Required by the filter signature.
627        return self::is_onboarding_request() ? false : $show;
628    }
629
630    /**
631     * Add a body class to the My Jetpack onboarding page.
632     * This class hides the WP Admin toolbar and the sidebar menu.
633     *
634     * @param string $classes The body classes.
635     * @return string The modified body classes.
636     */
637    public static function add_onboarding_admin_body_class( $classes ) {
638        $classes .= ' jetpack-admin-full-screen';
639        return $classes;
640    }
641
642    /**
643     * Returns whether we are in condition to track to use
644     * Analytics functionality like Tracks, MC, or GA.
645     */
646    public static function can_use_analytics() {
647        $status     = new Status();
648        $connection = new Connection_Manager();
649        $tracking   = new Tracking( 'jetpack', $connection );
650
651        return $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
652    }
653
654    /**
655     * Whether the onboarding takeover renders the setup wizard.
656     *
657     * Self-hosted only. On WordPress.com the platform owns the connection and nobody chose
658     * to install Jetpack, so a screen inviting them to start with it and connect an account
659     * does not apply. `is_wpcom_platform()` covers Simple and WordPress.com on Atomic, and
660     * requires wpcomsh, so other Atomic-hosted products still count as self-hosted here.
661     *
662     * @since 6.11.0
663     *
664     * @return bool
665     */
666    public static function is_onboarding_wizard_enabled() {
667        if ( ( new Status_Host() )->is_wpcom_platform() ) {
668            return false;
669        }
670
671        if ( ! Feature_Flags::is_enabled( self::ONBOARDING_WIZARD_FEATURE_FLAG ) ) {
672            return false;
673        }
674
675        // The wizard registers the site at its own first step, which writes the marker
676        // below, so asking again on the way back from WordPress.com would drop someone
677        // out of a run already under way.
678        if ( ( new Connection_Manager() )->is_connected() ) {
679            return true;
680        }
681
682        return self::has_never_registered_jetpack();
683    }
684
685    /**
686     * Whether the Jetpack plugin has never registered this site.
687     *
688     * `unique_registrations` is written on `jetpack_site_registered` by the Jetpack plugin
689     * alone, so a site that has only ever run a standalone plugin still reads as new here.
690     *
691     * @internal Not part of the package's public API.
692     *
693     * @since 6.11.0
694     *
695     * @return bool
696     */
697    public static function has_never_registered_jetpack() {
698        return ! \Jetpack_Options::get_option( 'unique_registrations' );
699    }
700
701    /**
702     * The wizard's configuration, or null while the takeover stays on its single screen.
703     *
704     * @since 6.11.0
705     *
706     * @return array{exitUrl: string, dashboardUrl: string}|null
707     */
708    public static function get_onboarding_wizard_state() {
709        if ( ! self::is_onboarding_wizard_enabled() ) {
710            return null;
711        }
712
713        return array(
714            // Where skipping the wizard lands: the admin menu is hidden, so leaving is always one click.
715            'exitUrl'      => admin_url( 'admin.php?page=my-jetpack' ),
716            // Where leaving Jetpack altogether lands: wp-admin's own dashboard.
717            'dashboardUrl' => admin_url(),
718        );
719    }
720
721    /**
722     * Whether the current request targets the My Jetpack admin page.
723     *
724     * @since 6.3.0
725     *
726     * @return bool
727     */
728    public static function is_my_jetpack_admin_request() {
729        if ( ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
730            return false;
731        }
732
733        return sanitize_text_field( wp_unslash( $_GET['page'] ) ) === 'my-jetpack'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
734    }
735
736    /**
737     * Whether the current request is the full-viewport onboarding takeover.
738     *
739     * Onboarding hides all wp-admin chrome and never renders through wp-build. The page
740     * is part of the question: `in_admin_header` and the JITM filter run everywhere.
741     *
742     * @since 6.3.0
743     *
744     * @return bool
745     */
746    public static function is_onboarding_request() {
747        if ( ! self::is_my_jetpack_admin_request() ) {
748            return false;
749        }
750
751        if ( ! isset( $_GET['step'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
752            return false;
753        }
754
755        return sanitize_text_field( wp_unslash( $_GET['step'] ) ) === 'onboarding'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
756    }
757
758    /**
759     * Whether this request is the onboarding takeover rather than the dashboard.
760     *
761     * Loading wp-build, enqueueing scripts and rendering the page must all agree,
762     * so they share this one expression.
763     *
764     * @since 6.3.0
765     *
766     * @return bool
767     */
768    public static function is_onboarding_takeover() {
769        return self::is_onboarding_request() && self::is_onboarding_available();
770    }
771
772    /**
773     * Alias the screen ID to satisfy wp-build's generated enqueue check.
774     *
775     * @since 6.3.0
776     *
777     * @return void
778     */
779    public static function alias_screen_id_for_wp_build() {
780        $screen = get_current_screen();
781
782        if ( ! $screen ) {
783            return;
784        }
785
786        self::$wp_build_original_screen_id = $screen->id;
787        $screen->id                        = self::WP_BUILD_PAGE_ID;
788    }
789
790    /**
791     * Undo alias_screen_id_for_wp_build(), since JITM builds its message path from the screen ID.
792     *
793     * @since 6.3.0
794     *
795     * @return void
796     */
797    public static function restore_screen_id_after_wp_build() {
798        $screen = get_current_screen();
799
800        if ( ! $screen || null === self::$wp_build_original_screen_id ) {
801            return;
802        }
803
804        $screen->id                        = self::$wp_build_original_screen_id;
805        self::$wp_build_original_screen_id = null;
806    }
807
808    /**
809     * Whether this request should load wp-build at all.
810     *
811     * Also what keeps WP_Build_Polyfills from replacing core scripts on every other admin page.
812     *
813     * @since 6.3.0
814     *
815     * @return bool
816     */
817    public static function should_load_wp_build() {
818        return self::is_my_jetpack_admin_request() && ! self::is_onboarding_takeover();
819    }
820
821    /**
822     * Whether this request renders the dashboard through wp-build.
823     *
824     * The generated render function is missing where the package was never built.
825     *
826     * @since 6.3.0
827     *
828     * @return bool
829     */
830    public static function should_render_wp_build() {
831        return ! self::is_onboarding_takeover()
832            && function_exists( 'jetpack_my_jetpack_my_jetpack_dashboard_wp_admin_render_page' );
833    }
834
835    /**
836     * Load wp-build for the My Jetpack dashboard.
837     *
838     * @since 6.3.0
839     *
840     * @return void
841     */
842    public static function maybe_load_wp_build() {
843        if ( ! self::should_load_wp_build() ) {
844            return;
845        }
846
847        $build_index = dirname( __DIR__ ) . '/build/build.php';
848
849        if ( file_exists( $build_index ) ) {
850            self::load_wp_build( $build_index );
851        }
852    }
853
854    /**
855     * Require the generated wp-build index and wire it into this request.
856     *
857     * @since 6.3.0
858     *
859     * @param string $build_index Path to the generated `build.php`.
860     * @return void
861     */
862    public static function load_wp_build( $build_index ) {
863        self::require_wp_build_with_screen_alias( $build_index );
864
865        // wp-build hooks module registration to wp_default_scripts, which has
866        // already fired by admin_menu â€” call it directly or the init module
867        // never reaches the import map.
868        if ( function_exists( 'jetpack_my_jetpack_register_script_modules' ) ) {
869            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.
870        }
871
872        WP_Build_Polyfills::register(
873            'my-jetpack',
874            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
875        );
876    }
877
878    /**
879     * Register My Jetpack with the admin shell, which switches between Jetpack dashboards without a page load.
880     *
881     * @since 6.18.0
882     *
883     * @param array $members Shell members keyed by admin page slug.
884     * @return array
885     */
886    public static function add_admin_shell_member( $members ) {
887        // A site that still needs onboarding is redirected to the takeover, which isn't a wp-build page.
888        if ( ! self::current_user_can_access_page() || ! file_exists( dirname( __DIR__ ) . '/build/build.php' ) || null !== self::get_onboarding_redirect_args_for_step( '' ) ) {
889            return $members;
890        }
891
892        $members['my-jetpack'] = array(
893            'build_prefix' => 'jetpack_my_jetpack',
894            'build_page'   => self::WP_BUILD_PAGE_ID,
895            'init_modules' => array( '@jetpack-my-jetpack/init' ),
896            'title'        => 'My Jetpack',
897            'header'       => array(
898                'title'    => 'Jetpack',
899                'subtitle' => '',
900            ),
901            'capability'   => 'edit_posts',
902            'handles'      => array( 'my_jetpack_main_app', 'my_jetpack_ai_app', 'jetpack-script-data', 'jetpack-connection', 'my-jetpack-header-controls', 'wp-jp-i18n-loader' ),
903            'load'         => array( __CLASS__, 'load_as_admin_shell_guest' ),
904        );
905        return $members;
906    }
907
908    /**
909     * Ready My Jetpack's routes and page data while another dashboard's page is open.
910     *
911     * Skips the screen ID alias: on another page it would make the generated enqueue boot a second app.
912     *
913     * @since 6.18.0
914     *
915     * @return void
916     */
917    public static function load_as_admin_shell_guest() {
918        require_once dirname( __DIR__ ) . '/build/build.php';
919
920        if ( function_exists( 'jetpack_my_jetpack_register_script_modules' ) ) {
921            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.
922        }
923        WP_Build_Polyfills::register(
924            'my-jetpack',
925            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
926        );
927
928        // On the host page the shell removes this again; the guest endpoint runs it.
929        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
930    }
931
932    /**
933     * Require the generated build file with the screen ID aliased across its enqueue check.
934     *
935     * @see WP_Build_Screen_Id::load_with_alias()
936     * @param string $build_index Path to the generated `build.php`.
937     * @return void
938     */
939    private static function require_wp_build_with_screen_alias( $build_index ) {
940        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
941        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
942            WP_Build_Screen_Id::load_with_alias(
943                array( __CLASS__, 'alias_screen_id_for_wp_build' ),
944                array( __CLASS__, 'restore_screen_id_after_wp_build' ),
945                function () use ( $build_index ) {
946                    require_once $build_index;
947                }
948            );
949            return;
950        }
951
952        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
953        require_once $build_index;
954        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
955    }
956
957    /**
958     * Enqueue admin page assets.
959     *
960     * @return void
961     */
962    public static function enqueue_scripts() {
963        if ( self::is_offline_features_enabled() ) {
964            $data_handle = self::DATA_SCRIPT_HANDLE;
965            wp_register_script( $data_handle, false, array(), self::PACKAGE_VERSION, true );
966            wp_enqueue_script( $data_handle );
967            add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );
968            wp_localize_script(
969                $data_handle,
970                'myJetpackInitialState',
971                array(
972                    'isOfflineFeatures'     => true,
973                    'products'              => array( 'items' => array() ),
974                    'adminUrl'              => esc_url( admin_url() ),
975                    'assetsUrl'             => self::get_assets_url(),
976                    'isJetpackPluginActive' => class_exists( 'Jetpack' ),
977                    'hiddenFeatures'        => Feature_Visibility::get_hidden(),
978                    'deprecatedModules'     => Feature_Visibility::get_deprecated_modules(),
979                    'myJetpackFlags'        => self::get_my_jetpack_flags(),
980                )
981            );
982            wp_localize_script(
983                $data_handle,
984                'myJetpackRest',
985                array(
986                    'apiRoot'  => esc_url_raw( rest_url() ),
987                    'apiNonce' => wp_create_nonce( 'wp_rest' ),
988                )
989            );
990            if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
991                wp_enqueue_script( 'wp-jp-i18n-loader' );
992            }
993            self::maybe_enqueue_header_controls_script();
994            return;
995        }
996
997        /**
998         * Fires after the My Jetpack page is initialized.
999         * Allows for enqueuing additional scripts only on the My Jetpack page.
1000         *
1001         * @since 4.35.7
1002         */
1003        do_action( 'myjetpack_enqueue_scripts' );
1004        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );
1005
1006        // Script-less: it only prints the state below, before the dashboard's boot runs on DOMContentLoaded.
1007        $data_handle = self::DATA_SCRIPT_HANDLE;
1008        wp_register_script( $data_handle, false, array(), self::PACKAGE_VERSION, true );
1009        wp_enqueue_script( $data_handle );
1010        self::maybe_enqueue_header_controls_script();
1011
1012        if ( self::is_my_jetpack_admin_request() && self::is_onboarding_takeover() ) {
1013            Assets::register_script(
1014                self::ONBOARDING_SCRIPT_HANDLE,
1015                '../build/onboarding.js',
1016                __FILE__,
1017                array(
1018                    'dependencies' => array( $data_handle ),
1019                    'enqueue'      => true,
1020                    'in_footer'    => true,
1021                    'textdomain'   => 'jetpack-my-jetpack',
1022                )
1023            );
1024        } elseif ( self::should_render_wp_build() && wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
1025            // Registered on every admin page but only enqueued when depended on; the esbuild bundles don't pull it in.
1026            wp_enqueue_script( 'wp-jp-i18n-loader' );
1027        }
1028
1029        $modules             = new Modules();
1030        $connection          = new Connection_Manager();
1031        $speed_score_history = new Speed_Score_History( home_url() );
1032        $latest_score        = $speed_score_history->latest();
1033        $previous_score      = array();
1034        if ( $speed_score_history->count() > 1 ) {
1035            $previous_score = $speed_score_history->latest( 1 );
1036        }
1037        $latest_score['previousScores'] = $previous_score['scores'] ?? array();
1038
1039        $sandboxed_domain = '';
1040        $is_dev_version   = false;
1041        if ( class_exists( 'Jetpack' ) ) {
1042            $is_dev_version   = Jetpack::is_development_version();
1043            $sandboxed_domain = defined( 'JETPACK__SANDBOX_DOMAIN' ) ? JETPACK__SANDBOX_DOMAIN : '';
1044        }
1045
1046        wp_localize_script(
1047            $data_handle,
1048            'myJetpackInitialState',
1049            array(
1050                'products'               => array(
1051                    'items' => Products::get_products(),
1052                ),
1053                'mainFeatures'           => Main_Features::get_state(),
1054                'featuresBanner'         => array( 'isDismissed' => REST_Main_Features::is_banner_dismissed() ),
1055                'onboardingWizard'       => self::get_onboarding_wizard_state(),
1056                'header'                 => self::get_header_state(),
1057                'plugins'                => Plugins_Installer::get_plugins(),
1058                'themes'                 => Sync_Functions::get_themes(),
1059                'myJetpackUrl'           => admin_url( 'admin.php?page=my-jetpack' ),
1060                'myJetpackCheckoutUri'   => admin_url( 'admin.php?page=my-jetpack' ),
1061                'topJetpackMenuItemUrl'  => Admin_Menu::get_top_level_menu_item_url(),
1062                'siteSuffix'             => ( new Status() )->get_site_suffix(),
1063                'siteUrl'                => esc_url( get_site_url() ),
1064                'homeUrl'                => esc_url_raw( home_url() ),
1065                'blogID'                 => Connection_Manager::get_site_id( true ),
1066                'myJetpackVersion'       => self::PACKAGE_VERSION,
1067                'myJetpackFlags'         => self::get_my_jetpack_flags(),
1068                'fileSystemWriteAccess'  => self::has_file_system_write_access(),
1069                'loadAddLicenseScreen'   => self::is_licensing_ui_enabled(),
1070                'planUrls'               => self::get_plan_urls(),
1071                'adminUrl'               => esc_url( admin_url() ),
1072                'assetsUrl'              => self::get_assets_url(),
1073                'IDCContainerID'         => static::get_idc_container_id(),
1074                'userIsAdmin'            => current_user_can( 'manage_options' ),
1075                // wp_localize_script() decodes the HTML entities WordPress stores names with.
1076                'userFirstName'          => (string) wp_get_current_user()->first_name,
1077                'lifecycleStats'         => array(
1078                    'jetpackPlugins'                      => self::get_installed_jetpack_plugins(),
1079                    'historicallyActiveModules'           => \Jetpack_Options::get_option( 'historically_active_modules', array() ),
1080                    'historicallyActiveModulesRefreshDue' => Historically_Active_Modules::is_refresh_due(),
1081                    'brokenModules'                       => Red_Bubble_Notifications::check_for_broken_modules(),
1082                    'isSiteConnected'                     => $connection->is_connected(),
1083                    'isUserConnected'                     => $connection->is_user_connected(),
1084                    'modules'                             => self::get_active_modules(),
1085                ),
1086                'recommendedModules'     => array(
1087                    'modules'    => self::get_recommended_modules(),
1088                    'isFirstRun' => \Jetpack_Options::get_option( 'recommendations_first_run', true ),
1089                    'dismissed'  => \Jetpack_Options::get_option( 'dismissed_recommendations', false ),
1090                ),
1091                'isStatsModuleActive'    => $modules->is_active( 'stats' ),
1092                'canUserViewStats'       => current_user_can( 'manage_options' ) || current_user_can( 'view_stats' ),
1093                'hiddenFeatures'         => Feature_Visibility::get_hidden(),
1094                'deprecatedModules'      => Feature_Visibility::get_deprecated_modules(),
1095                'sandboxedDomain'        => $sandboxed_domain,
1096                'isDevVersion'           => $is_dev_version,
1097                'isAtomic'               => ( new Status_Host() )->is_woa_site(),
1098                'isJetpackPluginActive'  => class_exists( 'Jetpack' ),
1099                'latestBoostSpeedScores' => $latest_score,
1100                'seoOptIn'               => self::get_seo_opt_in_state(),
1101                'protectPageModuleUrls'  => (object) Products\Protect::get_protect_page_module_urls(),
1102                'partnerCoupon'          => self::get_partner_coupon_screen(),
1103                'settingsNotices'        => self::get_settings_notices_state(),
1104            )
1105        );
1106
1107        wp_localize_script(
1108            $data_handle,
1109            'myJetpackRest',
1110            array(
1111                'apiRoot'  => esc_url_raw( rest_url() ),
1112                'apiNonce' => wp_create_nonce( 'wp_rest' ),
1113            )
1114        );
1115
1116        // Connection Initial State.
1117        Connection_Initial_State::render_script( $data_handle );
1118
1119        // Required for Analytics.
1120        if ( self::can_use_analytics() ) {
1121            Tracking::register_tracks_functions_scripts( true );
1122        }
1123    }
1124
1125    /**
1126     * What the shared header needs beyond the rest of the state, so it renders without a request.
1127     *
1128     * @since 6.10.0
1129     *
1130     * @return array{connectorsUrl: string|null} The state.
1131     */
1132    public static function get_header_state() {
1133        return array(
1134            // The same probe the connection package uses: the core screen ships with WordPress 7.0.
1135            // `connector` names the connection package's card, which opens its details for it.
1136            'connectorsUrl' => file_exists( ABSPATH . 'wp-admin/options-connectors.php' ) ? admin_url( 'options-connectors.php?connector=wordpress_com' ) : null,
1137        );
1138    }
1139
1140    /**
1141     * Where a host sends the plan links, in place of Jetpack's own checkout and purchases.
1142     *
1143     * @since 6.19.0
1144     *
1145     * @return array{purchase: string|false, manage: string|false} An empty string keeps Jetpack's own link; false hides the link.
1146     */
1147    public static function get_plan_urls() {
1148        $plan_urls = array(
1149            'purchase' => '',
1150            'manage'   => '',
1151        );
1152
1153        /**
1154         * Filters where My Jetpack's "Purchase a plan" and "Manage your plan" links go, for a host that sells its own plans.
1155         *
1156         * An answer that is neither an http or https URL nor false is discarded, keeping Jetpack's own link.
1157         *
1158         * @since 6.19.0
1159         * @param array{purchase: string|false, manage: string|false} $plan_urls The URL of each link; an empty string keeps Jetpack's own, and false hides the link.
1160         */
1161        $filtered = apply_filters( 'jetpack_my_jetpack_plan_urls', $plan_urls );
1162        $filtered = is_array( $filtered ) ? $filtered : array();
1163
1164        foreach ( array_keys( $plan_urls ) as $link ) {
1165            $answer = $filtered[ $link ] ?? null;
1166
1167            if ( is_string( $answer ) ) {
1168                $plan_urls[ $link ] = esc_url_raw( $answer, array( 'http', 'https' ) );
1169            } elseif ( false === $answer ) {
1170                $plan_urls[ $link ] = false;
1171            }
1172        }
1173
1174        return $plan_urls;
1175    }
1176
1177    /**
1178     * Add My Jetpack data to the unified script data object.
1179     *
1180     * @param array $data The script data.
1181     * @return array
1182     */
1183    public static function add_script_data( $data ) {
1184        $block_availability = ! self::is_offline_features_enabled() && class_exists( '\Jetpack_Gutenberg' )
1185            ? \Jetpack_Gutenberg::get_cached_availability()
1186            : array();
1187
1188        $data['myJetpack']['siteEditor'] = array(
1189            'isBlockTheme'            => function_exists( 'wp_is_block_theme' ) && wp_is_block_theme(),
1190            'isSharingBlockAvailable' => isset( $block_availability['sharing-buttons'] )
1191                && $block_availability['sharing-buttons']['available'],
1192            'isLikeBlockAvailable'    => isset( $block_availability['like'] )
1193                && $block_availability['like']['available'],
1194        );
1195
1196        return $data;
1197    }
1198
1199    /**
1200     * Whether module management can use the REST API.
1201     *
1202     * @since 6.11.0
1203     * @return bool
1204     */
1205    public static function is_modules_rest_api_enabled() {
1206        /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
1207        $enabled = apply_filters( 'rest_enabled', true );
1208        $user    = wp_get_current_user();
1209        $auth    = false;
1210        // Passing true skips WordPress's nonce check, which would sign the user out; restore the user if another filter clears it.
1211        try {
1212            /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
1213            $auth = apply_filters( 'rest_authentication_errors', true );
1214        } finally {
1215            wp_set_current_user( $user->ID );
1216        }
1217        return $enabled && ! is_wp_error( $enabled ) && false !== $auth && ! is_wp_error( $auth );
1218    }
1219
1220    /**
1221     * Get a Features management link with a classic Modules fallback.
1222     *
1223     * @since 6.11.0
1224     * @param array     $args     Query arguments from a classic Modules screen link; only `s` and `module_tag` can carry over to Features.
1225     * @param bool|null $eligible Set to true when the URL points at the Features tab, false when it is the classic Modules screen.
1226     * @return string The management URL.
1227     */
1228    public static function get_modules_management_url( $args = array(), &$eligible = null ) {
1229        $eligible  = false;
1230        $available = self::host_shows_my_jetpack() && self::is_modules_to_features_enabled();
1231        $classic   = add_query_arg( array_merge( urlencode_deep( $args ), array( 'page' => 'jetpack_modules' ) ), admin_url( 'admin.php' ) );
1232        if (
1233            ! $available
1234            || array_diff( array_keys( $args ), array( 's', 'module_tag' ) )
1235            || array_filter( $args, 'is_string' ) !== $args
1236            // Keep links on Modules unless Features can show controls for this installation.
1237            || Main_Features::PLUGIN_ACTIVE !== Main_Features::get_plugin_status( Product::JETPACK_PLUGIN_SLUG )
1238            || ! current_user_can( 'jetpack_manage_modules' )
1239            || ! current_user_can( 'manage_options' )
1240            || ! self::current_user_can_access_page()
1241            || ( new Status() )->is_offline_mode()
1242            || ( new Status_Host() )->is_wpcom_simple()
1243            || is_network_admin()
1244            || ! self::should_initialize()
1245            || ! ( new Connection_Manager() )->is_connected()
1246            || null !== self::get_partner_coupon_screen()
1247            // Predict My Jetpack's setup redirect for a Features URL with no step; keep both decisions in sync.
1248            || null !== self::get_onboarding_redirect_args_for_step( '' )
1249            || ! self::is_modules_rest_api_enabled()
1250        ) {
1251            return $classic;
1252        }
1253
1254        if ( isset( $args['module_tag'] ) && '' !== $args['module_tag'] ) {
1255            if ( ! function_exists( 'jetpack_get_module_i18n_tag' ) ) {
1256                return $classic;
1257            }
1258            $known      = array();
1259            $modules    = new Modules();
1260            $hidden     = Main_Features::get_hidden_modules();
1261            $deprecated = Feature_Visibility::get_deprecated_modules();
1262            foreach ( $modules->get_available() as $slug ) {
1263                if ( in_array( $slug, $hidden, true ) || ( in_array( $slug, $deprecated, true ) && ! $modules->is_active( $slug ) ) ) {
1264                    continue;
1265                }
1266                $module = $modules->get( $slug );
1267                $known  = array_merge( $known, $module['module_tags'] ?? array() );
1268            }
1269            $known = array_map( array( Jetpack::class, 'translate_module_tag' ), $known );
1270            if ( ! in_array( $args['module_tag'], $known, true ) ) {
1271                return $classic;
1272            }
1273        }
1274
1275        if ( isset( $args['s'] ) && '' !== $args['s'] ) {
1276            require_once JETPACK__PLUGIN_DIR . 'class.jetpack-admin.php';
1277            $hidden        = Main_Features::get_hidden_modules();
1278            $deprecated    = Feature_Visibility::get_deprecated_modules();
1279            $hidden_match  = false;
1280            $visible_match = false;
1281            foreach ( Jetpack::get_translated_modules( \Jetpack_Admin::init()->get_modules() ) as $slug => $module ) {
1282                if ( ! empty( $args['module_tag'] ) && ! in_array( $args['module_tag'], $module['module_tags'], true ) ) {
1283                    continue;
1284                }
1285                $text  = $module['name'] . ' ' . $module['description'] . ' ' . $module['long_description'] . ' ' . $module['search_terms'] . ' ' . implode( ',', $module['module_tags'] );
1286                $match = function_exists( 'mb_stripos' ) ? mb_stripos( $text, $args['s'] ) : stripos( $text, $args['s'] );
1287                if ( false === $match ) {
1288                    continue;
1289                }
1290                if ( in_array( $slug, $hidden, true ) || ( in_array( $slug, $deprecated, true ) && ! $module['activated'] ) ) {
1291                    $hidden_match = true;
1292                } else {
1293                    $visible_match = true;
1294                    break;
1295                }
1296            }
1297            if ( $hidden_match && ! $visible_match ) {
1298                return $classic;
1299            }
1300        }
1301
1302        $eligible = true;
1303        $hash     = array();
1304        if ( isset( $args['s'] ) && '' !== $args['s'] ) {
1305            $hash['search'] = $args['s'];
1306        }
1307        if ( isset( $args['module_tag'] ) && '' !== $args['module_tag'] ) {
1308            $hash['module_tag'] = $args['module_tag'];
1309        }
1310        return add_query_arg(
1311            array_merge(
1312                urlencode_deep( $args ),
1313                array(
1314                    'page'             => 'my-jetpack',
1315                    'modules_fallback' => '1',
1316                )
1317            ),
1318            admin_url( 'admin.php' )
1319        )
1320            . '#/features' . ( $hash ? '?' . http_build_query( $hash, '', '&', PHP_QUERY_RFC3986 ) : '' );
1321    }
1322
1323    /**
1324     * With `my-jetpack-modules-to-features` on, send My Jetpack requests with `modules_fallback=1` back to classic Modules:
1325     * always without JavaScript, and for everyone when REST is unavailable.
1326     *
1327     * @since 6.11.0
1328     * @return void
1329     */
1330    public static function print_modules_fallback() {
1331        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only navigation fallback.
1332        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- Only the exact allowlisted marker is accepted.
1333        if ( ! self::is_modules_to_features_enabled() || 'my-jetpack' !== ( $_GET['page'] ?? null ) || '1' !== ( $_GET['modules_fallback'] ?? null ) || Main_Features::PLUGIN_ACTIVE !== Main_Features::get_plugin_status( Product::JETPACK_PLUGIN_SLUG ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
1334            return;
1335        }
1336        $args = array( 'page' => 'jetpack_modules' );
1337        foreach ( array( 's', 'module_tag' ) as $key ) {
1338            if ( isset( $_GET[ $key ] ) && is_string( $_GET[ $key ] ) ) {
1339                $args[ $key ] = sanitize_text_field( wp_unslash( $_GET[ $key ] ) );
1340            }
1341        }
1342        // phpcs:enable WordPress.Security.NonceVerification.Recommended
1343        $meta = '<meta http-equiv="refresh" content="0; url=' . esc_url( add_query_arg( urlencode_deep( $args ), admin_url( 'admin.php' ) ) ) . '">';
1344        echo '<noscript>' . $meta . '</noscript>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- URL escaped above.
1345        if ( ! self::is_modules_rest_api_enabled() ) {
1346            echo $meta; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- URL escaped above.
1347        }
1348    }
1349
1350    /**
1351     * Get the slug and label of the Features tab, for footer links to it.
1352     *
1353     * Kept for footers built before the Products tab was removed: Jetpack 16.3 calls this, and
1354     * older JS footers read it from script data. Without it they link to "Products".
1355     *
1356     * @since 6.4.0
1357     *
1358     * @return array{slug: string, label: string}
1359     */
1360    public static function get_products_section() {
1361        return array(
1362            'slug'  => 'features',
1363            'label' => _x( 'Features', 'Navigation item', 'jetpack-my-jetpack' ),
1364        );
1365    }
1366
1367    /**
1368     * Add My Jetpack's availability, image base URL and link targets to admin script data.
1369     *
1370     * Printed on every admin page by Script_Data, so the connection screen can resolve its
1371     * illustrations and Jetpack footers know whether to link to My Jetpack.
1372     *
1373     * @since 6.3.0
1374     *
1375     * @param array $data Script data.
1376     * @return array
1377     */
1378    public static function add_admin_script_data( $data ) {
1379        $data['myJetpack']['isAvailable']           = self::is_admin_page_available();
1380        $data['myJetpack']['isShownByHost']         = self::host_shows_my_jetpack();
1381        $data['myJetpack']['assetsUrl']             = self::get_assets_url();
1382        $data['myJetpack']['productsSection']       = self::get_products_section();
1383        $data['myJetpack']['settingsConsolidation'] = self::is_settings_consolidation_enabled();
1384        $data['myJetpack']['showsSettingsNotices']  = self::shows_settings_notices();
1385        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only selects which navigation data to seed.
1386        if ( in_array( $_GET['page'] ?? '', array( 'my-jetpack', 'jetpack-settings', 'jetpack' ), true ) ) {
1387            $data['myJetpack']['modulesManagementUrl'] = self::get_modules_management_url();
1388            $data['myJetpack']['googleAnalyticsPanel'] = Google_Analytics_Settings::is_available()
1389                ? self::get_settings_panel_url( Google_Analytics_Settings::SLUG )
1390                : false;
1391        }
1392
1393        // Only administrators can open the pages this points at, so spare everyone else the lookup.
1394        if ( current_user_can( 'manage_options' ) ) {
1395            $data['myJetpack']['aiManageUrl'] = esc_url_raw( Products\Jetpack_Ai::get_manage_url() );
1396        }
1397
1398        if (
1399            self::is_my_jetpack_admin_request()
1400            && self::is_offline_features_enabled()
1401            && self::should_initialize()
1402            && REST_Main_Features::permissions_callback()
1403        ) {
1404            $data['myJetpack']['offlineFeatures'] = array(
1405                'mainFeatures' => Main_Features::get_state( true ),
1406                'plugins'      => Plugins_Installer::get_plugins(),
1407            );
1408            $data['myJetpack']['offlineFeatures']['mainFeatures']['available_admin_pages'] = self::get_registered_admin_page_slugs();
1409        }
1410
1411        return $data;
1412    }
1413
1414    /**
1415     * Get the slugs of registered admin pages.
1416     *
1417     * Skip hooks containing `?`: they are `edit.php?post_type=...` style pages, not page slugs.
1418     *
1419     * @return string[]
1420     */
1421    private static function get_registered_admin_page_slugs() {
1422        global $_registered_pages;
1423
1424        $hooks = array_filter(
1425            array_keys( $_registered_pages ?? array() ),
1426            static fn( $hook ) => false !== strpos( $hook, '_page_' ) && false === strpos( $hook, '?' )
1427        );
1428
1429        return array_values(
1430            array_unique(
1431                array_map( static fn( $hook ) => substr( $hook, strpos( $hook, '_page_' ) + 6 ), $hooks )
1432            )
1433        );
1434    }
1435
1436    /**
1437     * Whether My Jetpack's admin page is available to the current user.
1438     *
1439     * Meaningful only after admin_menu has registered the page.
1440     *
1441     * @since 6.5.0
1442     *
1443     * @return bool
1444     */
1445    public static function is_admin_page_available() {
1446        global $_registered_pages;
1447
1448        return did_action( 'my_jetpack_init' ) > 0
1449            && isset( $_registered_pages[ get_plugin_page_hookname( 'my-jetpack', 'jetpack' ) ] )
1450            && current_user_can( 'edit_posts' );
1451    }
1452
1453    /**
1454     * Get the base URL of the package's built images, with a trailing slash.
1455     *
1456     * @since 6.3.0
1457     *
1458     * @return string
1459     */
1460    public static function get_assets_url() {
1461        return trailingslashit( Assets::normalize_path( plugins_url( '../build/images/', __FILE__ ) ) );
1462    }
1463
1464    /**
1465     * Get installed Jetpack plugins
1466     *
1467     * @return array
1468     */
1469    public static function get_installed_jetpack_plugins() {
1470        $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
1471        $plugin_slugs = array_map(
1472            static function ( $slug ) {
1473                $parts = explode( '/', $slug );
1474                // Return the last segment of the filepath without the PHP extension
1475                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
1476            },
1477            $plugin_slugs
1478        );
1479
1480        return array_values( array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs ) );
1481    }
1482
1483    /**
1484     * Get active modules (except ones enabled by default)
1485     *
1486     * @return array
1487     */
1488    public static function get_active_modules() {
1489        $modules        = new Modules();
1490        $active_modules = $modules->get_active();
1491
1492        // if the Jetpack plugin is active, filter out the modules that are active by default
1493        if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
1494            $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
1495        }
1496        return array_values( $active_modules );
1497    }
1498
1499    /**
1500     * Determine if the current user is "new" to Jetpack
1501     * This is used to vary some messaging in My Jetpack
1502     *
1503     * On the front-end, purchases are also taken into account
1504     *
1505     * @return bool
1506     */
1507    public static function is_jetpack_user_new() {
1508        // is the user connected?
1509        $connection = new Connection_Manager();
1510        if ( $connection->is_user_connected() ) {
1511            return false;
1512        }
1513
1514        // TODO: add a data point for the last known connection/ disconnection time
1515
1516        // are any modules active?
1517        $active_modules = self::get_active_modules();
1518        if ( ! empty( $active_modules ) ) {
1519            return false;
1520        }
1521
1522        // check for other Jetpack plugins that are installed on the site (active or not)
1523        // If there's more than one Jetpack plugin active, this user is not "new"
1524        $plugin_slugs              = array_keys( Plugins_Installer::get_plugins() );
1525        $plugin_slugs              = array_map(
1526            static function ( $slug ) {
1527                $parts = explode( '/', $slug );
1528                // Return the last segment of the filepath without the PHP extension
1529                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
1530            },
1531            $plugin_slugs
1532        );
1533        $installed_jetpack_plugins = array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs );
1534        if ( is_countable( $installed_jetpack_plugins ) && count( $installed_jetpack_plugins ) >= 2 ) {
1535            return false;
1536        }
1537
1538        // Does the site have any purchases?
1539        $purchases = Wpcom_Products::get_site_current_purchases();
1540        if ( ! empty( $purchases ) && ! is_wp_error( $purchases ) ) {
1541            return false;
1542        }
1543
1544        return true;
1545    }
1546
1547    /**
1548     * Register My Jetpack's feature flags.
1549     *
1550     * @since 6.11.0
1551     *
1552     * @return void
1553     */
1554    public static function register_feature_flags() {
1555        Feature_Flags::register(
1556            self::ACCOUNT_CONNECT_FLAG,
1557            array(
1558                'default'     => true,
1559                'description' => 'Connect the account from the Install or Connect button of Features cards that need one, turn the chosen module on once Install Jetpack or Activate Jetpack finishes setup, hide Active and Inactive where the control already shows the state, exclude features from Available when their only action is an install the user cannot make, and show host restrictions below card descriptions.',
1560                'owner'       => 'my-jetpack',
1561            )
1562        );
1563        Feature_Flags::register(
1564            self::HEADER_CONTROLS_FLAG,
1565            array(
1566                'default'     => true,
1567                'description' => 'Show the global controls in the shared header of My Jetpack and Boost.',
1568                'owner'       => 'my-jetpack',
1569            )
1570        );
1571        Feature_Flags::register(
1572            self::OVERVIEW_V1_FLAG,
1573            array(
1574                'default'     => false,
1575                'description' => 'Show Overview v1 in My Jetpack.',
1576                'owner'       => 'my-jetpack',
1577            )
1578        );
1579        Feature_Flags::register(
1580            self::MODULES_TO_FEATURES_FLAG,
1581            array(
1582                'default'     => true,
1583                'description' => 'Open supported classic Modules links in Features.',
1584                'owner'       => 'my-jetpack',
1585            )
1586        );
1587        Feature_Flags::register(
1588            self::SETTINGS_CONSOLIDATION_FLAG,
1589            array(
1590                'default'     => true,
1591                'description' => 'Move settings out of the Settings screen to their new homes: open small features\' settings in a panel from Configure in Features, remove or replace their Settings cards with pointers, and show settings in their new places.',
1592                'owner'       => 'my-jetpack',
1593            )
1594        );
1595
1596        // Without the Jetpack plugin, nothing else registers the shell flag on requests that build no admin menu (CLI, REST, AJAX).
1597        if ( method_exists( Admin_Shell::class, 'register_feature_flag' ) ) {
1598            Admin_Shell::register_feature_flag();
1599        }
1600    }
1601
1602    /**
1603     * Whether the shared header shows its controls: the flag is on, My Jetpack runs, and not in offline Features.
1604     *
1605     * Boost's dashboard gets My Jetpack's page state even where My Jetpack is off, hence the second check.
1606     * Offline Features prints no connection state for the controls to read, and has no connection to show.
1607     *
1608     * @return bool
1609     */
1610    private static function is_header_controls_enabled() {
1611        return Feature_Flags::is_enabled( self::HEADER_CONTROLS_FLAG )
1612            && self::should_initialize()
1613            && ! self::is_offline_features_enabled();
1614    }
1615
1616    /**
1617     * Give dashboards outside My Jetpack, such as Boost's, the header's controls as a shared script.
1618     *
1619     * Bundling them instead would ship a second copy of the connection package next to the page's own.
1620     *
1621     * @return void
1622     */
1623    private static function maybe_enqueue_header_controls_script() {
1624        if ( self::is_my_jetpack_admin_request() || ! self::is_header_controls_enabled() ) {
1625            return;
1626        }
1627
1628        Assets::register_script(
1629            self::HEADER_CONTROLS_SCRIPT_HANDLE,
1630            '../build/header-controls.js',
1631            __FILE__,
1632            array(
1633                'dependencies' => array( self::DATA_SCRIPT_HANDLE ),
1634                'enqueue'      => true,
1635                'in_footer'    => true,
1636                'textdomain'   => 'jetpack-my-jetpack',
1637            )
1638        );
1639    }
1640
1641    /**
1642     *  Build flags for My Jetpack UI
1643     *
1644     *  @return array
1645     */
1646    public static function get_my_jetpack_flags() {
1647        $flags = array(
1648            'videoPressStats'          => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
1649            'showFullJetpackStatsCard' => class_exists( 'Jetpack' ) || Products\Stats::is_standalone_plugin_active(),
1650            // Only says which destination `manage_url` is: the legacy Stats page
1651            // caches its report and wants a `force_refresh` hint the dashboard does not.
1652            'premiumAnalyticsEnabled'  => Products\Stats::is_premium_analytics_enabled(),
1653            'showAiModuleToggle'       => Products\Jetpack_Ai::is_feature_ui_enabled(),
1654            'headerControls'           => self::is_header_controls_enabled(),
1655            'accountConnect'           => Feature_Flags::is_enabled( self::ACCOUNT_CONNECT_FLAG ),
1656            'overviewV1'               => self::is_overview_v1_enabled(),
1657        );
1658
1659        if ( $flags['accountConnect'] ) {
1660            $flags['showAiModuleToggleOnceConnected'] = Products\Jetpack_Ai::is_feature_ui_waiting_for_owner();
1661        }
1662
1663        return $flags;
1664    }
1665
1666    /**
1667     * Whether My Jetpack shows Overview v1.
1668     *
1669     * @since 6.10.0
1670     * @return bool
1671     */
1672    public static function is_overview_v1_enabled() {
1673        return Feature_Flags::is_enabled( self::OVERVIEW_V1_FLAG );
1674    }
1675
1676    /**
1677     * Whether the host shows My Jetpack.
1678     *
1679     * @return bool
1680     */
1681    private static function host_shows_my_jetpack() {
1682        /**
1683         * Filters whether the host shows My Jetpack, which lets Modules links open Features and settings move to My Jetpack.
1684         *
1685         * @since 6.11.0
1686         * @since 6.17.1 False also keeps settings on the Settings screen.
1687         * @since 6.19.0 False also removes the links to My Jetpack from Jetpack admin headers and footers.
1688         * @param bool $available True to allow the Features tab; false keeps the classic Modules and Settings screens, for a host where My Jetpack is not shown.
1689         */
1690        return (bool) apply_filters( 'jetpack_my_jetpack_modules_management_available', true );
1691    }
1692
1693    /**
1694     * Whether settings move to My Jetpack on this site: the flag is on, My Jetpack initializes, and the host shows it.
1695     *
1696     * It needs no admin menu, so URL builders that also run in REST use it, while page loads use `is_settings_consolidation_enabled()`.
1697     *
1698     * @since 6.17.1
1699     *
1700     * @return bool
1701     */
1702    public static function is_settings_consolidation_on_for_site() {
1703        return Feature_Flags::is_enabled( self::SETTINGS_CONSOLIDATION_FLAG )
1704            && self::should_initialize()
1705            && self::host_shows_my_jetpack();
1706    }
1707
1708    /**
1709     * Whether settings move to My Jetpack: consolidation is on for the site and My Jetpack's page is available.
1710     *
1711     * Without the page, moved settings would have nowhere to go, so they stay on the Settings screen.
1712     *
1713     * @since 6.15.0
1714     *
1715     * @return bool
1716     */
1717    public static function is_settings_consolidation_enabled() {
1718        return self::is_settings_consolidation_on_for_site() && self::is_admin_page_available();
1719    }
1720
1721    /**
1722     * Whether My Jetpack shows the notices Jetpack â€º Settings used to show, which settings consolidation moves here.
1723     *
1724     * Plugins check that this method exists before sending a pending `Jetpack::state()` here instead of to Settings.
1725     *
1726     * @since 6.19.0
1727     *
1728     * @return bool
1729     */
1730    public static function shows_settings_notices() {
1731        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only reads which setup step is open.
1732        $step = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';
1733
1734        // Neither the offline Features page nor onboarding has the notice slot.
1735        return self::is_settings_consolidation_enabled()
1736            && ! self::is_offline_features_enabled()
1737            && 'onboarding' !== $step
1738            && null === self::get_onboarding_redirect_args_for_step( $step );
1739    }
1740
1741    /**
1742     * What the notices moved from Jetpack â€º Settings need, or null while they stay there, leaving the Jetpack state to Settings.
1743     *
1744     * @since 6.19.0
1745     *
1746     * @return array|null
1747     */
1748    public static function get_settings_notices_state() {
1749        if ( ! self::shows_settings_notices() ) {
1750            return null;
1751        }
1752
1753        $cookie_state = new CookieState();
1754
1755        return array(
1756            'jetpackState'         => array(
1757                'error'            => $cookie_state->state( 'error' ),
1758                'errorDescription' => $cookie_state->state( 'error_description' ),
1759                'message'          => $cookie_state->state( 'message' ),
1760            ),
1761            'jetpackVersion'       => defined( 'JETPACK__VERSION' ) ? constant( 'JETPACK__VERSION' ) : null,
1762            // Settings showed it only to admins, the users who can change it.
1763            'searchEnginesVisible' => current_user_can( 'manage_options' ) ? '0' !== (string) get_option( 'blog_public' ) : null,
1764        );
1765    }
1766
1767    /**
1768     * Point the module's configure URL at its settings panel while settings consolidation is on for the site.
1769     *
1770     * @since 6.16.0
1771     *
1772     * @return void
1773     */
1774    public static function register_settings_panel_urls() {
1775        foreach ( self::SETTINGS_PANEL_MODULES as $module ) {
1776            add_filter(
1777                'jetpack_module_configuration_url_' . $module,
1778                static function ( $url ) use ( $module ) {
1779                    // Only Jetpack's settings-search default: a module's own page, such as SEO's, is its real home.
1780                    return false === strpos( (string) $url, 'page=jetpack-settings#/settings?term=' )
1781                        ? $url
1782                        : self::resolve_settings_url( $module, $url );
1783                }
1784            );
1785        }
1786    }
1787
1788    /**
1789     * Where a module's settings live: its panel in Features while settings consolidation is on for the site, `$fallback` otherwise.
1790     *
1791     * @since 6.16.0
1792     *
1793     * @param string $module   The module slug.
1794     * @param string $fallback The URL to use when the settings stay where they were.
1795     * @return string
1796     */
1797    public static function resolve_settings_url( $module, $fallback ) {
1798        if ( ! in_array( $module, self::SETTINGS_PANEL_MODULES, true ) || ! self::is_settings_consolidation_on_for_site() ) {
1799            return $fallback;
1800        }
1801
1802        return self::get_settings_panel_url( $module );
1803    }
1804
1805    /**
1806     * The URL that opens a settings panel in Features.
1807     *
1808     * @since 6.18.0
1809     *
1810     * @param string $slug The module or settings entry slug.
1811     * @return string
1812     */
1813    public static function get_settings_panel_url( $slug ) {
1814        return add_query_arg(
1815            array(
1816                'page' => 'my-jetpack',
1817                'p'    => rawurlencode( '/features?configure=' . $slug ),
1818            ),
1819            admin_url( 'admin.php' )
1820        );
1821    }
1822
1823    /**
1824     * Whether Modules links may use Features.
1825     *
1826     * @return bool
1827     */
1828    private static function is_modules_to_features_enabled() {
1829        return Feature_Flags::is_enabled( self::MODULES_TO_FEATURES_FLAG );
1830    }
1831
1832    /**
1833     * Build the legacy SEO opt-in card state through the package availability API.
1834     *
1835     * @return array{showCard: bool, redirect: string}
1836     */
1837    public static function get_seo_opt_in_state() {
1838        // Guard with method_exists rather than class_exists: an older bundled SEO package can ship
1839        // the Initializer class without this method, and class_exists alone would still fatal.
1840        $seo_initializer = 'Automattic\Jetpack\SEO\Initializer';
1841        // @phan-suppress-next-line PhanUndeclaredClassReference -- optional SEO package, guarded by method_exists.
1842        $show_card = method_exists( $seo_initializer, 'is_optin_available' ) && $seo_initializer::is_optin_available();
1843
1844        return array(
1845            'showCard' => $show_card,
1846            'redirect' => admin_url( 'admin.php?page=jetpack-seo' ),
1847        );
1848    }
1849
1850    /**
1851     * Echoes the admin page content.
1852     *
1853     * @return void
1854     */
1855    public static function admin_page() {
1856        // Asked again here rather than inferred from the redirect: with the wizard on a
1857        // connected user is deliberately left on this screen to finish setup, and anyone
1858        // who cannot connect never reaches it.
1859        if ( self::is_onboarding_takeover() ) {
1860            echo '<div id="my-jetpack-container"></div>';
1861            return;
1862        }
1863
1864        if ( self::should_render_wp_build() ) {
1865            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.
1866        }
1867    }
1868
1869    /**
1870     * Register the REST API routes.
1871     *
1872     * @return void
1873     */
1874    public static function register_rest_endpoints() {
1875        if ( self::is_offline_features_enabled() ) {
1876            ( new REST_Main_Features() )->register_rest_routes();
1877            return;
1878        }
1879
1880        new REST_Products();
1881        new REST_Purchases();
1882        ( new REST_Jetpack_AI_JWT() )->register_rest_route();
1883        new REST_Recommendations_Evaluation();
1884
1885        ( new REST_Onboarding() )->register_rest_routes();
1886        ( new REST_Main_Features() )->register_rest_routes();
1887        Google_Analytics_Settings::register_rest_routes();
1888
1889        Products::register_product_endpoints();
1890        Historically_Active_Modules::register_rest_endpoints();
1891        Jetpack_Manage::register_rest_endpoints();
1892        Red_Bubble_Notifications::register_rest_endpoints();
1893
1894        if ( self::is_overview_v1_enabled() ) {
1895            REST_Blog_Posts::register_rest_endpoints();
1896        }
1897
1898        register_rest_route(
1899            'my-jetpack/v1',
1900            'site',
1901            array(
1902                'methods'             => \WP_REST_Server::READABLE,
1903                'callback'            => __CLASS__ . '::get_site',
1904                'permission_callback' => __CLASS__ . '::permissions_callback',
1905            )
1906        );
1907
1908        register_rest_route(
1909            'my-jetpack/v1',
1910            'site/dismiss-welcome-banner',
1911            array(
1912                'methods'             => \WP_REST_Server::EDITABLE,
1913                'callback'            => __CLASS__ . '::dismiss_welcome_banner',
1914                'permission_callback' => __CLASS__ . '::permissions_callback',
1915            )
1916        );
1917    }
1918
1919    /**
1920     * Check user capability to access the endpoint.
1921     *
1922     * @access public
1923     * @static
1924     *
1925     * @return true|WP_Error
1926     */
1927    public static function permissions_callback() {
1928        return current_user_can( 'manage_options' );
1929    }
1930
1931    /**
1932     * Return true if we should initialize the My Jetpack admin page.
1933     */
1934    public static function should_initialize() {
1935        $should = true;
1936
1937        if ( ( new Status() )->is_offline_mode() ) {
1938            $should = self::is_offline_features_enabled();
1939        }
1940
1941        /**
1942         * Allows filtering whether My Jetpack should be initialized.
1943         * Outside REST requests, once the user is set, this cannot enable offline Features for a user without access.
1944         *
1945         * @since 0.5.0-alpha
1946         *
1947         * @param bool $shoud_initialize Should we initialize My Jetpack?
1948         */
1949        $should = apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
1950
1951        // REST authenticates after route registration; its permission callbacks check access.
1952        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() ) {
1953            return false;
1954        }
1955
1956        return $should;
1957    }
1958
1959    /**
1960     * Whether the site uses the local Features entry instead of the connected dashboard.
1961     *
1962     * @since 6.10.0
1963     * @return bool
1964     */
1965    public static function is_offline_features_enabled() {
1966        if ( ! ( new Status() )->is_offline_mode() ) {
1967            return false;
1968        }
1969
1970        /**
1971         * Enable local Features data and entry in offline mode.
1972         *
1973         * @since 6.10.0
1974         * @since 6.15.0 Enabled by default.
1975         * @param bool $enabled Whether to enable offline Features. Default true.
1976         */
1977        return (bool) apply_filters( 'jetpack_my_jetpack_offline_features', true );
1978    }
1979
1980    /**
1981     * Hook into several connection-based actions to update the historically active Jetpack modules
1982     * If the transient that indicates the list needs to be synced, update it and delete the transient
1983     *
1984     * @return void
1985     */
1986    public static function setup_historically_active_jetpack_modules_sync() {
1987        // yummmm. ham.
1988        $ham = new Historically_Active_Modules();
1989        if ( get_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY ) && ! wp_doing_ajax() ) {
1990            $ham::update_historically_active_jetpack_modules();
1991            delete_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY );
1992        }
1993
1994        $actions = array(
1995            'jetpack_site_registered',
1996            'jetpack_user_authorized',
1997            'activated_plugin',
1998        );
1999
2000        foreach ( $actions as $action ) {
2001            add_action( $action, array( $ham, 'queue_historically_active_jetpack_modules_update' ), 5 );
2002        }
2003
2004        // Modules are often updated async, so we need to update them right away as there will sometimes be no page reload.
2005        add_action( 'jetpack_activate_module', array( $ham, 'update_historically_active_jetpack_modules' ), 5 );
2006    }
2007
2008    /**
2009     * Site full-data endpoint.
2010     *
2011     * @return object Site data.
2012     */
2013    public static function get_site() {
2014        $site_id           = \Jetpack_Options::get_option( 'id' );
2015        $wpcom_endpoint    = sprintf( '/sites/%d?force=wpcom', $site_id );
2016        $wpcom_api_version = '1.1';
2017        $response          = Client::wpcom_json_api_request_as_blog( $wpcom_endpoint, $wpcom_api_version );
2018        $response_code     = wp_remote_retrieve_response_code( $response );
2019        $body              = json_decode( wp_remote_retrieve_body( $response ) );
2020
2021        if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
2022            return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
2023        }
2024
2025        return rest_ensure_response( $body );
2026    }
2027
2028    /**
2029     * Populates the self::$site_info var with site data from the /sites/%d endpoint
2030     *
2031     * @return object|WP_Error
2032     */
2033    public static function get_site_info() {
2034        static $site_info = null;
2035
2036        if ( $site_info !== null ) {
2037            return $site_info;
2038        }
2039
2040        // Check for a cached value before doing lookup
2041        $stored_site_info = get_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY );
2042        if ( $stored_site_info !== false ) {
2043            return $stored_site_info;
2044        }
2045
2046        $response = self::get_site();
2047        if ( is_wp_error( $response ) ) {
2048            return $response;
2049        }
2050        $site_info = $response->data;
2051        set_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY, $site_info, DAY_IN_SECONDS );
2052
2053        return $site_info;
2054    }
2055
2056    /**
2057     * Returns whether a site has been determined "commercial" or not.
2058     *
2059     * @return bool|null
2060     */
2061    public static function is_commercial_site() {
2062        if ( is_wp_error( self::$site_info ) ) {
2063            return null;
2064        }
2065
2066        return empty( self::$site_info->options->is_commercial ) ? false : self::$site_info->options->is_commercial;
2067    }
2068
2069    /**
2070     * Check if site is registered (has been connected before).
2071     *
2072     * @return bool
2073     */
2074    public static function is_registered() {
2075        return (bool) \Jetpack_Options::get_option( 'id' );
2076    }
2077
2078    /**
2079     * Dismiss the welcome banner.
2080     *
2081     * @return \WP_REST_Response
2082     */
2083    public static function dismiss_welcome_banner() {
2084        \Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
2085        return rest_ensure_response( array( 'success' => true ) );
2086    }
2087
2088    /**
2089     * Returns "yes" if the site has file write access to the plugins folder, "no" otherwise.
2090     *
2091     * @return string
2092     **/
2093    public static function has_file_system_write_access() {
2094
2095        $cache = get_transient( 'my_jetpack_write_access' );
2096
2097        if ( false !== $cache ) {
2098            return $cache;
2099        }
2100
2101        if ( ! function_exists( 'get_filesystem_method' ) ) {
2102            require_once ABSPATH . 'wp-admin/includes/file.php';
2103        }
2104
2105        require_once ABSPATH . 'wp-admin/includes/template.php';
2106
2107        $write_access = 'no';
2108
2109        $filesystem_method = get_filesystem_method( array(), WP_PLUGIN_DIR );
2110        if ( 'direct' === $filesystem_method ) {
2111            $write_access = 'yes';
2112        }
2113
2114        if ( 'no' === $write_access ) {
2115            ob_start();
2116            $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
2117            ob_end_clean();
2118
2119            if ( $filesystem_credentials_are_stored ) {
2120                $write_access = 'yes';
2121            }
2122        }
2123
2124        set_transient( 'my_jetpack_write_access', $write_access, 30 * MINUTE_IN_SECONDS );
2125
2126        return $write_access;
2127    }
2128
2129    /**
2130     * Get container IDC for the IDC screen.
2131     *
2132     * @return string
2133     */
2134    public static function get_idc_container_id() {
2135        return static::IDC_CONTAINER_ID;
2136    }
2137
2138    /**
2139     * Conditionally append the red bubble notification to the "Jetpack" menu item if there are alerts to show.
2140     *
2141     * On My Jetpack page: Uses blocking behavior to fetch fresh data.
2142     * On other admin pages: Uses cached data only to avoid blocking, with async JS fetch if cache is empty.
2143     *
2144     * @return void
2145     */
2146    public static function maybe_show_red_bubble() {
2147        global $pagenow;
2148
2149        // Don't show red bubble alerts for non-admin users
2150        // These alerts are generally only actionable for admins
2151        if ( ! current_user_can( 'manage_options' ) ) {
2152            return;
2153        }
2154
2155        // Don't show any red bubbles when Jetpack is disconnected
2156        // Users can't act on most alerts without a connection
2157        $connection = new Connection_Manager();
2158        if ( ! $connection->is_connected() ) {
2159            return;
2160        }
2161
2162        // Check if we're on the My Jetpack page.
2163        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
2164        $page               = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
2165        $is_my_jetpack_page = $pagenow === 'admin.php' && $page === 'my-jetpack';
2166
2167        if ( $is_my_jetpack_page ) {
2168            // On My Jetpack page: use blocking behavior for fresh data.
2169            add_filter( 'my_jetpack_red_bubble_notification_slugs', array( Red_Bubble_Notifications::class, 'add_red_bubble_alerts' ) );
2170            $red_bubble_alerts = Red_Bubble_Notifications::get_red_bubble_alerts();
2171        } else {
2172            // On other pages: use cached data only to avoid blocking.
2173            $cached_alerts = Red_Bubble_Notifications::get_cached_alerts();
2174
2175            if ( false === $cached_alerts ) {
2176                // No cache: warm it asynchronously via JS. Register a hidden zero-count
2177                // placeholder so Menu_Renderer emits a `my-jetpack` badge element the
2178                // warmer can reveal (see async-notification-bubble.ts) without a reload.
2179                Menu_Badges::init(); // idempotent; wires the renderer.
2180                Notification_Counts::register(
2181                    'my-jetpack',
2182                    array(
2183                        'menu_slug' => 'my-jetpack',
2184                        'count'     => 0,
2185                        'type'      => 'count',
2186                    )
2187                );
2188                add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_red_bubble_script' ) );
2189                return;
2190            }
2191
2192            $red_bubble_alerts = $cached_alerts;
2193        }
2194
2195        // Filter out silent alerts.
2196        $red_bubble_alerts = array_filter(
2197            $red_bubble_alerts,
2198            function ( $alert ) {
2199                return empty( $alert['is_silent'] );
2200            }
2201        );
2202
2203        // Report each non-silent alert to the central menu-badges registry as an
2204        // attention entry (count 1). The registry + renderer own the badge.
2205        Menu_Badges::init(); // idempotent; wires the renderer.
2206
2207        // Connection errors are owned by the Error Handler (the single source of truth):
2208        // surface any it reports for this viewer as their own attention entry. Read live
2209        // rather than from the red-bubble transient, since that cache is not viewer-keyed.
2210        $has_connection_error = self::has_connection_error();
2211        if ( $has_connection_error ) {
2212            Notification_Counts::register(
2213                'my-jetpack-connection-error',
2214                array(
2215                    'menu_slug' => 'my-jetpack',
2216                    'type'      => 'attention',
2217                )
2218            );
2219        }
2220
2221        $counted_elsewhere = self::get_alerts_counted_elsewhere();
2222        foreach ( array_keys( $red_bubble_alerts ) as $slug ) {
2223            if ( in_array( $slug, $counted_elsewhere, true ) ) {
2224                continue;
2225            }
2226            // The missing-connection slug and a connection error describe the same broken
2227            // connection; count it once (the error, above, is the more specific signal).
2228            if ( $has_connection_error && 'missing-connection' === $slug ) {
2229                continue;
2230            }
2231            Notification_Counts::register(
2232                'my-jetpack-' . $slug,
2233                array(
2234                    'menu_slug' => 'my-jetpack',
2235                    'type'      => 'attention',
2236                )
2237            );
2238        }
2239    }
2240
2241    /**
2242     * Whether the Connection Error Handler reports a displayable connection error
2243     * for the current viewer.
2244     *
2245     * Read live (not via the red-bubble transient): get_displayable_errors() is a
2246     * cached option read that the Error Handler already scopes and caches per viewer.
2247     * Guarded for the mid-plugin-update window, where a stale connection package
2248     * predating the method can be loaded.
2249     *
2250     * @return bool
2251     */
2252    private static function has_connection_error() {
2253        if ( ! class_exists( Connection_Error_Handler::class ) || ! method_exists( Connection_Error_Handler::class, 'get_displayable_errors' ) ) {
2254            return false;
2255        }
2256        return ! empty( Connection_Error_Handler::get_instance()->get_displayable_errors() );
2257    }
2258
2259    /**
2260     * Alerts left out of the My Jetpack badge because another menu item already counts them.
2261     *
2262     * The Protect page reports its own count, from the standalone plugin (class-jetpack-protect.php::admin_page_init())
2263     * or the Protect package's dashboard; without either, nobody else counts the threats, so they must stay.
2264     *
2265     * @return string[] Alert slugs.
2266     */
2267    private static function get_alerts_counted_elsewhere() {
2268        // Without has_protect_page(), use the standalone plugin check this relied on before that method existed.
2269        $has_protect_page = method_exists( Products\Protect::class, 'has_protect_page' ) ? Products\Protect::has_protect_page() : Products\Protect::is_standalone_plugin_active();
2270        return $has_protect_page ? array( 'protect_has_threats' ) : array();
2271    }
2272
2273    /**
2274     * Enqueue the notification bubble script.
2275     * Fetches fresh alert data via REST API without blocking page load.
2276     *
2277     * @return void
2278     */
2279    public static function enqueue_red_bubble_script() {
2280        Assets::register_script(
2281            'my-jetpack-notification-bubble',
2282            '../build/async-notification-bubble.js',
2283            __FILE__,
2284            array(
2285                'enqueue'   => true,
2286                'in_footer' => true,
2287            )
2288        );
2289        wp_localize_script(
2290            'my-jetpack-notification-bubble',
2291            'myJetpackNotificationBubble',
2292            array( 'excludedAlerts' => self::get_alerts_counted_elsewhere() )
2293        );
2294    }
2295
2296    /**
2297     * Get list of module names sorted by their recommendation score
2298     *
2299     * @return array|null
2300     */
2301    public static function get_recommended_modules() {
2302        $recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );
2303
2304        if ( empty( $recommendations_evaluation ) || ! is_array( $recommendations_evaluation ) ) {
2305            return null;
2306        }
2307
2308        arsort( $recommendations_evaluation ); // Sort by scores in descending order
2309
2310        return array_keys( $recommendations_evaluation ); // Get only module names
2311    }
2312}