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