Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.89% covered (warning)
84.89%
736 / 867
73.75% covered (warning)
73.75%
59 / 80
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
84.89% covered (warning)
84.89%
736 / 867
73.75% covered (warning)
73.75%
59 / 80
650.94
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 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 require_wp_build_with_screen_alias
68.75% covered (warning)
68.75%
11 / 16
0.00% covered (danger)
0.00%
0 / 1
4.49
 enqueue_scripts
97.01% covered (success)
97.01%
130 / 134
0.00% covered (danger)
0.00%
0 / 1
12
 get_header_state
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_plan_urls
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 add_script_data
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 is_modules_rest_api_enabled
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 get_modules_management_url
51.43% covered (warning)
51.43%
36 / 70
0.00% covered (danger)
0.00%
0 / 1
244.13
 print_modules_fallback
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
10
 get_products_section
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 add_admin_script_data
100.00% covered (success)
100.00%
23 / 23
100.00% covered (success)
100.00%
1 / 1
8
 get_registered_admin_page_slugs
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 is_admin_page_available
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_assets_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_installed_jetpack_plugins
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 get_active_modules
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 is_jetpack_user_new
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
56
 register_feature_flags
100.00% covered (success)
100.00%
42 / 42
100.00% covered (success)
100.00%
1 / 1
2
 is_header_controls_enabled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 maybe_enqueue_header_controls_script
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 get_my_jetpack_flags
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 is_overview_v1_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 host_shows_my_jetpack
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_settings_consolidation_on_for_site
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_settings_consolidation_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 shows_settings_notices
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
 get_settings_notices_state
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
 register_settings_panel_urls
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 resolve_settings_url
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_settings_panel_url
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 is_modules_to_features_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_seo_opt_in_state
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 admin_page
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 register_rest_endpoints
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
3
 permissions_callback
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 should_initialize
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
7
 is_offline_features_enabled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 setup_historically_active_jetpack_modules_sync
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 get_site
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
3.01
 get_site_info
58.33% covered (warning)
58.33%
7 / 12
0.00% covered (danger)
0.00%
0 / 1
5.16
 is_commercial_site
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 is_registered
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 dismiss_welcome_banner
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 has_file_system_write_access
61.11% covered (warning)
61.11%
11 / 18
0.00% covered (danger)
0.00%
0 / 1
8.12
 get_idc_container_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 maybe_show_red_bubble
96.23% covered (success)
96.23%
51 / 53
0.00% covered (danger)
0.00%
0 / 1
12
 has_connection_error
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 get_alerts_counted_elsewhere
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 enqueue_red_bubble_script
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
 get_recommended_modules
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * WP Admin page with information and configuration shared among all Jetpack stand-alone plugins
4 *
5 * @package automattic/my-jetpack
6 */
7
8namespace Automattic\Jetpack\My_Jetpack;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Admin_UI\Admin_Shell;
12use Automattic\Jetpack\Assets;
13use Automattic\Jetpack\Boost_Speed_Score\Speed_Score;
14use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_History;
15use Automattic\Jetpack\Connection\Client;
16use Automattic\Jetpack\Connection\Error_Handler as Connection_Error_Handler;
17use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
18use Automattic\Jetpack\Connection\Manager as Connection_Manager;
19use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
20use Automattic\Jetpack\Connection\REST_Jetpack_AI_JWT;
21use Automattic\Jetpack\Constants as Jetpack_Constants;
22use Automattic\Jetpack\CookieState;
23use Automattic\Jetpack\ExPlat;
24use Automattic\Jetpack\Feature_Flags\Feature_Flags;
25use Automattic\Jetpack\JITMS\JITM;
26use Automattic\Jetpack\Licensing;
27use Automattic\Jetpack\Menu_Badges\Menu_Badges;
28use Automattic\Jetpack\Menu_Badges\Notification_Counts;
29use Automattic\Jetpack\Modules;
30use Automattic\Jetpack\Partner_Coupon;
31use Automattic\Jetpack\Plugins_Installer;
32use Automattic\Jetpack\Status;
33use Automattic\Jetpack\Status\Host as Status_Host;
34use Automattic\Jetpack\Sync\Functions as Sync_Functions;
35use Automattic\Jetpack\Terms_Of_Service;
36use Automattic\Jetpack\Tracking;
37use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
38use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
39use Jetpack;
40use WP_Error;
41
42/**
43 * The main Initializer class that registers the admin menu and eneuque the assets.
44 */
45class Initializer {
46
47    /**
48     * My Jetpack package version
49     *
50     * @var string
51     */
52    const PACKAGE_VERSION = '6.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        if ( class_exists( \Automattic\Jetpack\Admin_UI\Shared_Modules::class ) ) {
918            \Automattic\Jetpack\Admin_UI\Shared_Modules::init();
919        }
920
921        if ( function_exists( 'jetpack_my_jetpack_register_script_modules' ) ) {
922            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.
923        }
924        WP_Build_Polyfills::register(
925            'my-jetpack',
926            array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
927        );
928
929        // On the host page the shell removes this again; the guest endpoint runs it.
930        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
931    }
932
933    /**
934     * Require the generated build file with the screen ID aliased across its enqueue check.
935     *
936     * @see WP_Build_Screen_Id::load_with_alias()
937     * @param string $build_index Path to the generated `build.php`.
938     * @return void
939     */
940    private static function require_wp_build_with_screen_alias( $build_index ) {
941        // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
942        if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
943            WP_Build_Screen_Id::load_with_alias(
944                array( __CLASS__, 'alias_screen_id_for_wp_build' ),
945                array( __CLASS__, 'restore_screen_id_after_wp_build' ),
946                function () use ( $build_index ) {
947                    require_once $build_index;
948                    if ( class_exists( \Automattic\Jetpack\Admin_UI\Shared_Modules::class ) ) {
949                        \Automattic\Jetpack\Admin_UI\Shared_Modules::init();
950                    }
951                }
952            );
953            return;
954        }
955
956        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
957        require_once $build_index;
958        if ( class_exists( \Automattic\Jetpack\Admin_UI\Shared_Modules::class ) ) {
959            \Automattic\Jetpack\Admin_UI\Shared_Modules::init();
960        }
961        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
962    }
963
964    /**
965     * Enqueue admin page assets.
966     *
967     * @return void
968     */
969    public static function enqueue_scripts() {
970        if ( self::is_offline_features_enabled() ) {
971            $data_handle = self::DATA_SCRIPT_HANDLE;
972            wp_register_script( $data_handle, false, array(), self::PACKAGE_VERSION, true );
973            wp_enqueue_script( $data_handle );
974            add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );
975            wp_localize_script(
976                $data_handle,
977                'myJetpackInitialState',
978                array(
979                    'isOfflineFeatures'     => true,
980                    'products'              => array( 'items' => array() ),
981                    'adminUrl'              => esc_url( admin_url() ),
982                    'assetsUrl'             => self::get_assets_url(),
983                    'isJetpackPluginActive' => class_exists( 'Jetpack' ),
984                    'hiddenFeatures'        => Feature_Visibility::get_hidden(),
985                    'deprecatedModules'     => Feature_Visibility::get_deprecated_modules(),
986                    'myJetpackFlags'        => self::get_my_jetpack_flags(),
987                )
988            );
989            wp_localize_script(
990                $data_handle,
991                'myJetpackRest',
992                array(
993                    'apiRoot'  => esc_url_raw( rest_url() ),
994                    'apiNonce' => wp_create_nonce( 'wp_rest' ),
995                )
996            );
997            if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
998                wp_enqueue_script( 'wp-jp-i18n-loader' );
999            }
1000            self::maybe_enqueue_header_controls_script();
1001            return;
1002        }
1003
1004        /**
1005         * Fires after the My Jetpack page is initialized.
1006         * Allows for enqueuing additional scripts only on the My Jetpack page.
1007         *
1008         * @since 4.35.7
1009         */
1010        do_action( 'myjetpack_enqueue_scripts' );
1011        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );
1012
1013        // Script-less: it only prints the state below, before the dashboard's boot runs on DOMContentLoaded.
1014        $data_handle = self::DATA_SCRIPT_HANDLE;
1015        wp_register_script( $data_handle, false, array(), self::PACKAGE_VERSION, true );
1016        wp_enqueue_script( $data_handle );
1017        self::maybe_enqueue_header_controls_script();
1018
1019        if ( self::is_my_jetpack_admin_request() && self::is_onboarding_takeover() ) {
1020            Assets::register_script(
1021                self::ONBOARDING_SCRIPT_HANDLE,
1022                '../build/onboarding.js',
1023                __FILE__,
1024                array(
1025                    'dependencies' => array( $data_handle ),
1026                    'enqueue'      => true,
1027                    'in_footer'    => true,
1028                    'textdomain'   => 'jetpack-my-jetpack',
1029                )
1030            );
1031        } elseif ( self::should_render_wp_build() && wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
1032            // Registered on every admin page but only enqueued when depended on; the esbuild bundles don't pull it in.
1033            wp_enqueue_script( 'wp-jp-i18n-loader' );
1034        }
1035
1036        $modules             = new Modules();
1037        $connection          = new Connection_Manager();
1038        $speed_score_history = new Speed_Score_History( home_url() );
1039        $latest_score        = $speed_score_history->latest();
1040        $previous_score      = array();
1041        if ( $speed_score_history->count() > 1 ) {
1042            $previous_score = $speed_score_history->latest( 1 );
1043        }
1044        $latest_score['previousScores'] = $previous_score['scores'] ?? array();
1045
1046        $sandboxed_domain = '';
1047        $is_dev_version   = false;
1048        if ( class_exists( 'Jetpack' ) ) {
1049            $is_dev_version   = Jetpack::is_development_version();
1050            $sandboxed_domain = defined( 'JETPACK__SANDBOX_DOMAIN' ) ? JETPACK__SANDBOX_DOMAIN : '';
1051        }
1052
1053        wp_localize_script(
1054            $data_handle,
1055            'myJetpackInitialState',
1056            array(
1057                'products'               => array(
1058                    'items' => Products::get_products(),
1059                ),
1060                'mainFeatures'           => Main_Features::get_state(),
1061                'featuresBanner'         => array( 'isDismissed' => REST_Main_Features::is_banner_dismissed() ),
1062                'onboardingWizard'       => self::get_onboarding_wizard_state(),
1063                'header'                 => self::get_header_state(),
1064                'plugins'                => Plugins_Installer::get_plugins(),
1065                'themes'                 => Sync_Functions::get_themes(),
1066                'myJetpackUrl'           => admin_url( 'admin.php?page=my-jetpack' ),
1067                'myJetpackCheckoutUri'   => admin_url( 'admin.php?page=my-jetpack' ),
1068                'topJetpackMenuItemUrl'  => Admin_Menu::get_top_level_menu_item_url(),
1069                'siteSuffix'             => ( new Status() )->get_site_suffix(),
1070                'siteUrl'                => esc_url( get_site_url() ),
1071                'homeUrl'                => esc_url_raw( home_url() ),
1072                'blogID'                 => Connection_Manager::get_site_id( true ),
1073                'myJetpackVersion'       => self::PACKAGE_VERSION,
1074                'myJetpackFlags'         => self::get_my_jetpack_flags(),
1075                'fileSystemWriteAccess'  => self::has_file_system_write_access(),
1076                'loadAddLicenseScreen'   => self::is_licensing_ui_enabled(),
1077                'planUrls'               => self::get_plan_urls(),
1078                'adminUrl'               => esc_url( admin_url() ),
1079                'assetsUrl'              => self::get_assets_url(),
1080                'IDCContainerID'         => static::get_idc_container_id(),
1081                'userIsAdmin'            => current_user_can( 'manage_options' ),
1082                // wp_localize_script() decodes the HTML entities WordPress stores names with.
1083                'userFirstName'          => (string) wp_get_current_user()->first_name,
1084                'lifecycleStats'         => array(
1085                    'jetpackPlugins'                      => self::get_installed_jetpack_plugins(),
1086                    'historicallyActiveModules'           => \Jetpack_Options::get_option( 'historically_active_modules', array() ),
1087                    'historicallyActiveModulesRefreshDue' => Historically_Active_Modules::is_refresh_due(),
1088                    'brokenModules'                       => Red_Bubble_Notifications::check_for_broken_modules(),
1089                    'isSiteConnected'                     => $connection->is_connected(),
1090                    'isUserConnected'                     => $connection->is_user_connected(),
1091                    'modules'                             => self::get_active_modules(),
1092                ),
1093                'recommendedModules'     => array(
1094                    'modules'    => self::get_recommended_modules(),
1095                    'isFirstRun' => \Jetpack_Options::get_option( 'recommendations_first_run', true ),
1096                    'dismissed'  => \Jetpack_Options::get_option( 'dismissed_recommendations', false ),
1097                ),
1098                'isStatsModuleActive'    => $modules->is_active( 'stats' ),
1099                'canUserViewStats'       => current_user_can( 'manage_options' ) || current_user_can( 'view_stats' ),
1100                'hiddenFeatures'         => Feature_Visibility::get_hidden(),
1101                'deprecatedModules'      => Feature_Visibility::get_deprecated_modules(),
1102                'sandboxedDomain'        => $sandboxed_domain,
1103                'isDevVersion'           => $is_dev_version,
1104                'isAtomic'               => ( new Status_Host() )->is_woa_site(),
1105                'isJetpackPluginActive'  => class_exists( 'Jetpack' ),
1106                'latestBoostSpeedScores' => $latest_score,
1107                'seoOptIn'               => self::get_seo_opt_in_state(),
1108                'protectPageModuleUrls'  => (object) Products\Protect::get_protect_page_module_urls(),
1109                'partnerCoupon'          => self::get_partner_coupon_screen(),
1110                'settingsNotices'        => self::get_settings_notices_state(),
1111            )
1112        );
1113
1114        wp_localize_script(
1115            $data_handle,
1116            'myJetpackRest',
1117            array(
1118                'apiRoot'  => esc_url_raw( rest_url() ),
1119                'apiNonce' => wp_create_nonce( 'wp_rest' ),
1120            )
1121        );
1122
1123        // Connection Initial State.
1124        Connection_Initial_State::render_script( $data_handle );
1125
1126        // Required for Analytics.
1127        if ( self::can_use_analytics() ) {
1128            Tracking::register_tracks_functions_scripts( true );
1129        }
1130    }
1131
1132    /**
1133     * What the shared header needs beyond the rest of the state, so it renders without a request.
1134     *
1135     * @since 6.10.0
1136     *
1137     * @return array{connectorsUrl: string|null} The state.
1138     */
1139    public static function get_header_state() {
1140        return array(
1141            // The same probe the connection package uses: the core screen ships with WordPress 7.0.
1142            // `connector` names the connection package's card, which opens its details for it.
1143            'connectorsUrl' => file_exists( ABSPATH . 'wp-admin/options-connectors.php' ) ? admin_url( 'options-connectors.php?connector=wordpress_com' ) : null,
1144        );
1145    }
1146
1147    /**
1148     * Where a host sends the plan links, in place of Jetpack's own checkout and purchases.
1149     *
1150     * @since $$next-version$$
1151     *
1152     * @return array{purchase: string|false, manage: string|false} An empty string keeps Jetpack's own link; false hides the link.
1153     */
1154    public static function get_plan_urls() {
1155        $plan_urls = array(
1156            'purchase' => '',
1157            'manage'   => '',
1158        );
1159
1160        /**
1161         * Filters where My Jetpack's "Purchase a plan" and "Manage your plan" links go, for a host that sells its own plans.
1162         *
1163         * An answer that is neither an http or https URL nor false is discarded, keeping Jetpack's own link.
1164         *
1165         * @since $$next-version$$
1166         * @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.
1167         */
1168        $filtered = apply_filters( 'jetpack_my_jetpack_plan_urls', $plan_urls );
1169        $filtered = is_array( $filtered ) ? $filtered : array();
1170
1171        foreach ( array_keys( $plan_urls ) as $link ) {
1172            $answer = $filtered[ $link ] ?? null;
1173
1174            if ( is_string( $answer ) ) {
1175                $plan_urls[ $link ] = esc_url_raw( $answer, array( 'http', 'https' ) );
1176            } elseif ( false === $answer ) {
1177                $plan_urls[ $link ] = false;
1178            }
1179        }
1180
1181        return $plan_urls;
1182    }
1183
1184    /**
1185     * Add My Jetpack data to the unified script data object.
1186     *
1187     * @param array $data The script data.
1188     * @return array
1189     */
1190    public static function add_script_data( $data ) {
1191        $block_availability = ! self::is_offline_features_enabled() && class_exists( '\Jetpack_Gutenberg' )
1192            ? \Jetpack_Gutenberg::get_cached_availability()
1193            : array();
1194
1195        $data['myJetpack']['siteEditor'] = array(
1196            'isBlockTheme'            => function_exists( 'wp_is_block_theme' ) && wp_is_block_theme(),
1197            'isSharingBlockAvailable' => isset( $block_availability['sharing-buttons'] )
1198                && $block_availability['sharing-buttons']['available'],
1199            'isLikeBlockAvailable'    => isset( $block_availability['like'] )
1200                && $block_availability['like']['available'],
1201        );
1202
1203        return $data;
1204    }
1205
1206    /**
1207     * Whether module management can use the REST API.
1208     *
1209     * @since 6.11.0
1210     * @return bool
1211     */
1212    public static function is_modules_rest_api_enabled() {
1213        /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
1214        $enabled = apply_filters( 'rest_enabled', true );
1215        $user    = wp_get_current_user();
1216        $auth    = false;
1217        // Passing true skips WordPress's nonce check, which would sign the user out; restore the user if another filter clears it.
1218        try {
1219            /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */
1220            $auth = apply_filters( 'rest_authentication_errors', true );
1221        } finally {
1222            wp_set_current_user( $user->ID );
1223        }
1224        return $enabled && ! is_wp_error( $enabled ) && false !== $auth && ! is_wp_error( $auth );
1225    }
1226
1227    /**
1228     * Get a Features management link with a classic Modules fallback.
1229     *
1230     * @since 6.11.0
1231     * @param array     $args     Query arguments from a classic Modules screen link; only `s` and `module_tag` can carry over to Features.
1232     * @param bool|null $eligible Set to true when the URL points at the Features tab, false when it is the classic Modules screen.
1233     * @return string The management URL.
1234     */
1235    public static function get_modules_management_url( $args = array(), &$eligible = null ) {
1236        $eligible  = false;
1237        $available = self::host_shows_my_jetpack() && self::is_modules_to_features_enabled();
1238        $classic   = add_query_arg( array_merge( urlencode_deep( $args ), array( 'page' => 'jetpack_modules' ) ), admin_url( 'admin.php' ) );
1239        if (
1240            ! $available
1241            || array_diff( array_keys( $args ), array( 's', 'module_tag' ) )
1242            || array_filter( $args, 'is_string' ) !== $args
1243            // Keep links on Modules unless Features can show controls for this installation.
1244            || Main_Features::PLUGIN_ACTIVE !== Main_Features::get_plugin_status( Product::JETPACK_PLUGIN_SLUG )
1245            || ! current_user_can( 'jetpack_manage_modules' )
1246            || ! current_user_can( 'manage_options' )
1247            || ! self::current_user_can_access_page()
1248            || ( new Status() )->is_offline_mode()
1249            || ( new Status_Host() )->is_wpcom_simple()
1250            || is_network_admin()
1251            || ! self::should_initialize()
1252            || ! ( new Connection_Manager() )->is_connected()
1253            || null !== self::get_partner_coupon_screen()
1254            // Predict My Jetpack's setup redirect for a Features URL with no step; keep both decisions in sync.
1255            || null !== self::get_onboarding_redirect_args_for_step( '' )
1256            || ! self::is_modules_rest_api_enabled()
1257        ) {
1258            return $classic;
1259        }
1260
1261        if ( isset( $args['module_tag'] ) && '' !== $args['module_tag'] ) {
1262            if ( ! function_exists( 'jetpack_get_module_i18n_tag' ) ) {
1263                return $classic;
1264            }
1265            $known      = array();
1266            $modules    = new Modules();
1267            $hidden     = Main_Features::get_hidden_modules();
1268            $deprecated = Feature_Visibility::get_deprecated_modules();
1269            foreach ( $modules->get_available() as $slug ) {
1270                if ( in_array( $slug, $hidden, true ) || ( in_array( $slug, $deprecated, true ) && ! $modules->is_active( $slug ) ) ) {
1271                    continue;
1272                }
1273                $module = $modules->get( $slug );
1274                $known  = array_merge( $known, $module['module_tags'] ?? array() );
1275            }
1276            $known = array_map( array( Jetpack::class, 'translate_module_tag' ), $known );
1277            if ( ! in_array( $args['module_tag'], $known, true ) ) {
1278                return $classic;
1279            }
1280        }
1281
1282        if ( isset( $args['s'] ) && '' !== $args['s'] ) {
1283            require_once JETPACK__PLUGIN_DIR . 'class.jetpack-admin.php';
1284            $hidden        = Main_Features::get_hidden_modules();
1285            $deprecated    = Feature_Visibility::get_deprecated_modules();
1286            $hidden_match  = false;
1287            $visible_match = false;
1288            foreach ( Jetpack::get_translated_modules( \Jetpack_Admin::init()->get_modules() ) as $slug => $module ) {
1289                if ( ! empty( $args['module_tag'] ) && ! in_array( $args['module_tag'], $module['module_tags'], true ) ) {
1290                    continue;
1291                }
1292                $text  = $module['name'] . ' ' . $module['description'] . ' ' . $module['long_description'] . ' ' . $module['search_terms'] . ' ' . implode( ',', $module['module_tags'] );
1293                $match = function_exists( 'mb_stripos' ) ? mb_stripos( $text, $args['s'] ) : stripos( $text, $args['s'] );
1294                if ( false === $match ) {
1295                    continue;
1296                }
1297                if ( in_array( $slug, $hidden, true ) || ( in_array( $slug, $deprecated, true ) && ! $module['activated'] ) ) {
1298                    $hidden_match = true;
1299                } else {
1300                    $visible_match = true;
1301                    break;
1302                }
1303            }
1304            if ( $hidden_match && ! $visible_match ) {
1305                return $classic;
1306            }
1307        }
1308
1309        $eligible = true;
1310        $hash     = array();
1311        if ( isset( $args['s'] ) && '' !== $args['s'] ) {
1312            $hash['search'] = $args['s'];
1313        }
1314        if ( isset( $args['module_tag'] ) && '' !== $args['module_tag'] ) {
1315            $hash['module_tag'] = $args['module_tag'];
1316        }
1317        return add_query_arg(
1318            array_merge(
1319                urlencode_deep( $args ),
1320                array(
1321                    'page'             => 'my-jetpack',
1322                    'modules_fallback' => '1',
1323                )
1324            ),
1325            admin_url( 'admin.php' )
1326        )
1327            . '#/features' . ( $hash ? '?' . http_build_query( $hash, '', '&', PHP_QUERY_RFC3986 ) : '' );
1328    }
1329
1330    /**
1331     * With `my-jetpack-modules-to-features` on, send My Jetpack requests with `modules_fallback=1` back to classic Modules:
1332     * always without JavaScript, and for everyone when REST is unavailable.
1333     *
1334     * @since 6.11.0
1335     * @return void
1336     */
1337    public static function print_modules_fallback() {
1338        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only navigation fallback.
1339        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- Only the exact allowlisted marker is accepted.
1340        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' ) ) {
1341            return;
1342        }
1343        $args = array( 'page' => 'jetpack_modules' );
1344        foreach ( array( 's', 'module_tag' ) as $key ) {
1345            if ( isset( $_GET[ $key ] ) && is_string( $_GET[ $key ] ) ) {
1346                $args[ $key ] = sanitize_text_field( wp_unslash( $_GET[ $key ] ) );
1347            }
1348        }
1349        // phpcs:enable WordPress.Security.NonceVerification.Recommended
1350        $meta = '<meta http-equiv="refresh" content="0; url=' . esc_url( add_query_arg( urlencode_deep( $args ), admin_url( 'admin.php' ) ) ) . '">';
1351        echo '<noscript>' . $meta . '</noscript>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- URL escaped above.
1352        if ( ! self::is_modules_rest_api_enabled() ) {
1353            echo $meta; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- URL escaped above.
1354        }
1355    }
1356
1357    /**
1358     * Get the slug and label of the Features tab, for footer links to it.
1359     *
1360     * Kept for footers built before the Products tab was removed: Jetpack 16.3 calls this, and
1361     * older JS footers read it from script data. Without it they link to "Products".
1362     *
1363     * @since 6.4.0
1364     *
1365     * @return array{slug: string, label: string}
1366     */
1367    public static function get_products_section() {
1368        return array(
1369            'slug'  => 'features',
1370            'label' => _x( 'Features', 'Navigation item', 'jetpack-my-jetpack' ),
1371        );
1372    }
1373
1374    /**
1375     * Add My Jetpack's availability, image base URL and link targets to admin script data.
1376     *
1377     * Printed on every admin page by Script_Data, so the connection screen can resolve its
1378     * illustrations and Jetpack footers know whether to link to My Jetpack.
1379     *
1380     * @since 6.3.0
1381     *
1382     * @param array $data Script data.
1383     * @return array
1384     */
1385    public static function add_admin_script_data( $data ) {
1386        $data['myJetpack']['isAvailable']           = self::is_admin_page_available();
1387        $data['myJetpack']['isShownByHost']         = self::host_shows_my_jetpack();
1388        $data['myJetpack']['assetsUrl']             = self::get_assets_url();
1389        $data['myJetpack']['productsSection']       = self::get_products_section();
1390        $data['myJetpack']['settingsConsolidation'] = self::is_settings_consolidation_enabled();
1391        $data['myJetpack']['showsSettingsNotices']  = self::shows_settings_notices();
1392        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only selects which navigation data to seed.
1393        if ( in_array( $_GET['page'] ?? '', array( 'my-jetpack', 'jetpack-settings', 'jetpack' ), true ) ) {
1394            $data['myJetpack']['modulesManagementUrl'] = self::get_modules_management_url();
1395            $data['myJetpack']['googleAnalyticsPanel'] = Google_Analytics_Settings::is_available()
1396                ? self::get_settings_panel_url( Google_Analytics_Settings::SLUG )
1397                : false;
1398        }
1399
1400        // Only administrators can open the pages this points at, so spare everyone else the lookup.
1401        if ( current_user_can( 'manage_options' ) ) {
1402            $data['myJetpack']['aiManageUrl'] = esc_url_raw( Products\Jetpack_Ai::get_manage_url() );
1403        }
1404
1405        if (
1406            self::is_my_jetpack_admin_request()
1407            && self::is_offline_features_enabled()
1408            && self::should_initialize()
1409            && REST_Main_Features::permissions_callback()
1410        ) {
1411            $data['myJetpack']['offlineFeatures'] = array(
1412                'mainFeatures' => Main_Features::get_state( true ),
1413                'plugins'      => Plugins_Installer::get_plugins(),
1414            );
1415            $data['myJetpack']['offlineFeatures']['mainFeatures']['available_admin_pages'] = self::get_registered_admin_page_slugs();
1416        }
1417
1418        return $data;
1419    }
1420
1421    /**
1422     * Get the slugs of registered admin pages.
1423     *
1424     * Skip hooks containing `?`: they are `edit.php?post_type=...` style pages, not page slugs.
1425     *
1426     * @return string[]
1427     */
1428    private static function get_registered_admin_page_slugs() {
1429        global $_registered_pages;
1430
1431        $hooks = array_filter(
1432            array_keys( $_registered_pages ?? array() ),
1433            static fn( $hook ) => false !== strpos( $hook, '_page_' ) && false === strpos( $hook, '?' )
1434        );
1435
1436        return array_values(
1437            array_unique(
1438                array_map( static fn( $hook ) => substr( $hook, strpos( $hook, '_page_' ) + 6 ), $hooks )
1439            )
1440        );
1441    }
1442
1443    /**
1444     * Whether My Jetpack's admin page is available to the current user.
1445     *
1446     * Meaningful only after admin_menu has registered the page.
1447     *
1448     * @since 6.5.0
1449     *
1450     * @return bool
1451     */
1452    public static function is_admin_page_available() {
1453        global $_registered_pages;
1454
1455        return did_action( 'my_jetpack_init' ) > 0
1456            && isset( $_registered_pages[ get_plugin_page_hookname( 'my-jetpack', 'jetpack' ) ] )
1457            && current_user_can( 'edit_posts' );
1458    }
1459
1460    /**
1461     * Get the base URL of the package's built images, with a trailing slash.
1462     *
1463     * @since 6.3.0
1464     *
1465     * @return string
1466     */
1467    public static function get_assets_url() {
1468        return trailingslashit( Assets::normalize_path( plugins_url( '../build/images/', __FILE__ ) ) );
1469    }
1470
1471    /**
1472     * Get installed Jetpack plugins
1473     *
1474     * @return array
1475     */
1476    public static function get_installed_jetpack_plugins() {
1477        $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
1478        $plugin_slugs = array_map(
1479            static function ( $slug ) {
1480                $parts = explode( '/', $slug );
1481                // Return the last segment of the filepath without the PHP extension
1482                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
1483            },
1484            $plugin_slugs
1485        );
1486
1487        return array_values( array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs ) );
1488    }
1489
1490    /**
1491     * Get active modules (except ones enabled by default)
1492     *
1493     * @return array
1494     */
1495    public static function get_active_modules() {
1496        $modules        = new Modules();
1497        $active_modules = $modules->get_active();
1498
1499        // if the Jetpack plugin is active, filter out the modules that are active by default
1500        if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
1501            $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
1502        }
1503        return array_values( $active_modules );
1504    }
1505
1506    /**
1507     * Determine if the current user is "new" to Jetpack
1508     * This is used to vary some messaging in My Jetpack
1509     *
1510     * On the front-end, purchases are also taken into account
1511     *
1512     * @return bool
1513     */
1514    public static function is_jetpack_user_new() {
1515        // is the user connected?
1516        $connection = new Connection_Manager();
1517        if ( $connection->is_user_connected() ) {
1518            return false;
1519        }
1520
1521        // TODO: add a data point for the last known connection/ disconnection time
1522
1523        // are any modules active?
1524        $active_modules = self::get_active_modules();
1525        if ( ! empty( $active_modules ) ) {
1526            return false;
1527        }
1528
1529        // check for other Jetpack plugins that are installed on the site (active or not)
1530        // If there's more than one Jetpack plugin active, this user is not "new"
1531        $plugin_slugs              = array_keys( Plugins_Installer::get_plugins() );
1532        $plugin_slugs              = array_map(
1533            static function ( $slug ) {
1534                $parts = explode( '/', $slug );
1535                // Return the last segment of the filepath without the PHP extension
1536                return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
1537            },
1538            $plugin_slugs
1539        );
1540        $installed_jetpack_plugins = array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs );
1541        if ( is_countable( $installed_jetpack_plugins ) && count( $installed_jetpack_plugins ) >= 2 ) {
1542            return false;
1543        }
1544
1545        // Does the site have any purchases?
1546        $purchases = Wpcom_Products::get_site_current_purchases();
1547        if ( ! empty( $purchases ) && ! is_wp_error( $purchases ) ) {
1548            return false;
1549        }
1550
1551        return true;
1552    }
1553
1554    /**
1555     * Register My Jetpack's feature flags.
1556     *
1557     * @since 6.11.0
1558     *
1559     * @return void
1560     */
1561    public static function register_feature_flags() {
1562        Feature_Flags::register(
1563            self::ACCOUNT_CONNECT_FLAG,
1564            array(
1565                'default'     => true,
1566                '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.',
1567                'owner'       => 'my-jetpack',
1568            )
1569        );
1570        Feature_Flags::register(
1571            self::HEADER_CONTROLS_FLAG,
1572            array(
1573                'default'     => true,
1574                'description' => 'Show the global controls in the shared header of My Jetpack and Boost.',
1575                'owner'       => 'my-jetpack',
1576            )
1577        );
1578        Feature_Flags::register(
1579            self::OVERVIEW_V1_FLAG,
1580            array(
1581                'default'     => false,
1582                'description' => 'Show Overview v1 in My Jetpack.',
1583                'owner'       => 'my-jetpack',
1584            )
1585        );
1586        Feature_Flags::register(
1587            self::MODULES_TO_FEATURES_FLAG,
1588            array(
1589                'default'     => true,
1590                'description' => 'Open supported classic Modules links in Features.',
1591                'owner'       => 'my-jetpack',
1592            )
1593        );
1594        Feature_Flags::register(
1595            self::SETTINGS_CONSOLIDATION_FLAG,
1596            array(
1597                'default'     => false,
1598                '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.',
1599                'owner'       => 'my-jetpack',
1600            )
1601        );
1602
1603        // Without the Jetpack plugin, nothing else registers the shell flag on requests that build no admin menu (CLI, REST, AJAX).
1604        if ( method_exists( Admin_Shell::class, 'register_feature_flag' ) ) {
1605            Admin_Shell::register_feature_flag();
1606        }
1607    }
1608
1609    /**
1610     * Whether the shared header shows its controls: the flag is on, My Jetpack runs, and not in offline Features.
1611     *
1612     * Boost's dashboard gets My Jetpack's page state even where My Jetpack is off, hence the second check.
1613     * Offline Features prints no connection state for the controls to read, and has no connection to show.
1614     *
1615     * @return bool
1616     */
1617    private static function is_header_controls_enabled() {
1618        return Feature_Flags::is_enabled( self::HEADER_CONTROLS_FLAG )
1619            && self::should_initialize()
1620            && ! self::is_offline_features_enabled();
1621    }
1622
1623    /**
1624     * Give dashboards outside My Jetpack, such as Boost's, the header's controls as a shared script.
1625     *
1626     * Bundling them instead would ship a second copy of the connection package next to the page's own.
1627     *
1628     * @return void
1629     */
1630    private static function maybe_enqueue_header_controls_script() {
1631        if ( self::is_my_jetpack_admin_request() || ! self::is_header_controls_enabled() ) {
1632            return;
1633        }
1634
1635        Assets::register_script(
1636            self::HEADER_CONTROLS_SCRIPT_HANDLE,
1637            '../build/header-controls.js',
1638            __FILE__,
1639            array(
1640                'dependencies' => array( self::DATA_SCRIPT_HANDLE ),
1641                'enqueue'      => true,
1642                'in_footer'    => true,
1643                'textdomain'   => 'jetpack-my-jetpack',
1644            )
1645        );
1646    }
1647
1648    /**
1649     *  Build flags for My Jetpack UI
1650     *
1651     *  @return array
1652     */
1653    public static function get_my_jetpack_flags() {
1654        $flags = array(
1655            'videoPressStats'          => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
1656            'showFullJetpackStatsCard' => class_exists( 'Jetpack' ) || Products\Stats::is_standalone_plugin_active(),
1657            // Only says which destination `manage_url` is: the legacy Stats page
1658            // caches its report and wants a `force_refresh` hint the dashboard does not.
1659            'premiumAnalyticsEnabled'  => Products\Stats::is_premium_analytics_enabled(),
1660            'showAiModuleToggle'       => Products\Jetpack_Ai::is_feature_ui_enabled(),
1661            'headerControls'           => self::is_header_controls_enabled(),
1662            'accountConnect'           => Feature_Flags::is_enabled( self::ACCOUNT_CONNECT_FLAG ),
1663            'overviewV1'               => self::is_overview_v1_enabled(),
1664        );
1665
1666        if ( $flags['accountConnect'] ) {
1667            $flags['showAiModuleToggleOnceConnected'] = Products\Jetpack_Ai::is_feature_ui_waiting_for_owner();
1668        }
1669
1670        return $flags;
1671    }
1672
1673    /**
1674     * Whether My Jetpack shows Overview v1.
1675     *
1676     * @since 6.10.0
1677     * @return bool
1678     */
1679    public static function is_overview_v1_enabled() {
1680        return Feature_Flags::is_enabled( self::OVERVIEW_V1_FLAG );
1681    }
1682
1683    /**
1684     * Whether the host shows My Jetpack.
1685     *
1686     * @return bool
1687     */
1688    private static function host_shows_my_jetpack() {
1689        /**
1690         * Filters whether the host shows My Jetpack, which lets Modules links open Features and settings move to My Jetpack.
1691         *
1692         * @since 6.11.0
1693         * @since 6.17.1 False also keeps settings on the Settings screen.
1694         * @since $$next-version$$ False also removes the links to My Jetpack from Jetpack admin headers and footers.
1695         * @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.
1696         */
1697        return (bool) apply_filters( 'jetpack_my_jetpack_modules_management_available', true );
1698    }
1699
1700    /**
1701     * Whether settings move to My Jetpack on this site: the flag is on, My Jetpack initializes, and the host shows it.
1702     *
1703     * It needs no admin menu, so URL builders that also run in REST use it, while page loads use `is_settings_consolidation_enabled()`.
1704     *
1705     * @since 6.17.1
1706     *
1707     * @return bool
1708     */
1709    public static function is_settings_consolidation_on_for_site() {
1710        return Feature_Flags::is_enabled( self::SETTINGS_CONSOLIDATION_FLAG )
1711            && self::should_initialize()
1712            && self::host_shows_my_jetpack();
1713    }
1714
1715    /**
1716     * Whether settings move to My Jetpack: consolidation is on for the site and My Jetpack's page is available.
1717     *
1718     * Without the page, moved settings would have nowhere to go, so they stay on the Settings screen.
1719     *
1720     * @since 6.15.0
1721     *
1722     * @return bool
1723     */
1724    public static function is_settings_consolidation_enabled() {
1725        return self::is_settings_consolidation_on_for_site() && self::is_admin_page_available();
1726    }
1727
1728    /**
1729     * Whether My Jetpack shows the notices Jetpack â€º Settings used to show, which settings consolidation moves here.
1730     *
1731     * Plugins check that this method exists before sending a pending `Jetpack::state()` here instead of to Settings.
1732     *
1733     * @since $$next-version$$
1734     *
1735     * @return bool
1736     */
1737    public static function shows_settings_notices() {
1738        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only reads which setup step is open.
1739        $step = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';
1740
1741        // Neither the offline Features page nor onboarding has the notice slot.
1742        return self::is_settings_consolidation_enabled()
1743            && ! self::is_offline_features_enabled()
1744            && 'onboarding' !== $step
1745            && null === self::get_onboarding_redirect_args_for_step( $step );
1746    }
1747
1748    /**
1749     * What the notices moved from Jetpack â€º Settings need, or null while they stay there, leaving the Jetpack state to Settings.
1750     *
1751     * @since $$next-version$$
1752     *
1753     * @return array|null
1754     */
1755    public static function get_settings_notices_state() {
1756        if ( ! self::shows_settings_notices() ) {
1757            return null;
1758        }
1759
1760        $cookie_state = new CookieState();
1761
1762        return array(
1763            'jetpackState'         => array(
1764                'error'            => $cookie_state->state( 'error' ),
1765                'errorDescription' => $cookie_state->state( 'error_description' ),
1766                'message'          => $cookie_state->state( 'message' ),
1767            ),
1768            'jetpackVersion'       => defined( 'JETPACK__VERSION' ) ? constant( 'JETPACK__VERSION' ) : null,
1769            // Settings showed it only to admins, the users who can change it.
1770            'searchEnginesVisible' => current_user_can( 'manage_options' ) ? '0' !== (string) get_option( 'blog_public' ) : null,
1771        );
1772    }
1773
1774    /**
1775     * Point the module's configure URL at its settings panel while settings consolidation is on for the site.
1776     *
1777     * @since 6.16.0
1778     *
1779     * @return void
1780     */
1781    public static function register_settings_panel_urls() {
1782        foreach ( self::SETTINGS_PANEL_MODULES as $module ) {
1783            add_filter(
1784                'jetpack_module_configuration_url_' . $module,
1785                static function ( $url ) use ( $module ) {
1786                    // Only Jetpack's settings-search default: a module's own page, such as SEO's, is its real home.
1787                    return false === strpos( (string) $url, 'page=jetpack-settings#/settings?term=' )
1788                        ? $url
1789                        : self::resolve_settings_url( $module, $url );
1790                }
1791            );
1792        }
1793    }
1794
1795    /**
1796     * Where a module's settings live: its panel in Features while settings consolidation is on for the site, `$fallback` otherwise.
1797     *
1798     * @since 6.16.0
1799     *
1800     * @param string $module   The module slug.
1801     * @param string $fallback The URL to use when the settings stay where they were.
1802     * @return string
1803     */
1804    public static function resolve_settings_url( $module, $fallback ) {
1805        if ( ! in_array( $module, self::SETTINGS_PANEL_MODULES, true ) || ! self::is_settings_consolidation_on_for_site() ) {
1806            return $fallback;
1807        }
1808
1809        return self::get_settings_panel_url( $module );
1810    }
1811
1812    /**
1813     * The URL that opens a settings panel in Features.
1814     *
1815     * @since 6.18.0
1816     *
1817     * @param string $slug The module or settings entry slug.
1818     * @return string
1819     */
1820    public static function get_settings_panel_url( $slug ) {
1821        return add_query_arg(
1822            array(
1823                'page' => 'my-jetpack',
1824                'p'    => rawurlencode( '/features?configure=' . $slug ),
1825            ),
1826            admin_url( 'admin.php' )
1827        );
1828    }
1829
1830    /**
1831     * Whether Modules links may use Features.
1832     *
1833     * @return bool
1834     */
1835    private static function is_modules_to_features_enabled() {
1836        return Feature_Flags::is_enabled( self::MODULES_TO_FEATURES_FLAG );
1837    }
1838
1839    /**
1840     * Build the legacy SEO opt-in card state through the package availability API.
1841     *
1842     * @return array{showCard: bool, redirect: string}
1843     */
1844    public static function get_seo_opt_in_state() {
1845        // Guard with method_exists rather than class_exists: an older bundled SEO package can ship
1846        // the Initializer class without this method, and class_exists alone would still fatal.
1847        $seo_initializer = 'Automattic\Jetpack\SEO\Initializer';
1848        // @phan-suppress-next-line PhanUndeclaredClassReference -- optional SEO package, guarded by method_exists.
1849        $show_card = method_exists( $seo_initializer, 'is_optin_available' ) && $seo_initializer::is_optin_available();
1850
1851        return array(
1852            'showCard' => $show_card,
1853            'redirect' => admin_url( 'admin.php?page=jetpack-seo' ),
1854        );
1855    }
1856
1857    /**
1858     * Echoes the admin page content.
1859     *
1860     * @return void
1861     */
1862    public static function admin_page() {
1863        // Asked again here rather than inferred from the redirect: with the wizard on a
1864        // connected user is deliberately left on this screen to finish setup, and anyone
1865        // who cannot connect never reaches it.
1866        if ( self::is_onboarding_takeover() ) {
1867            echo '<div id="my-jetpack-container"></div>';
1868            return;
1869        }
1870
1871        if ( self::should_render_wp_build() ) {
1872            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.
1873        }
1874    }
1875
1876    /**
1877     * Register the REST API routes.
1878     *
1879     * @return void
1880     */
1881    public static function register_rest_endpoints() {
1882        if ( self::is_offline_features_enabled() ) {
1883            ( new REST_Main_Features() )->register_rest_routes();
1884            return;
1885        }
1886
1887        new REST_Products();
1888        new REST_Purchases();
1889        ( new REST_Jetpack_AI_JWT() )->register_rest_route();
1890        new REST_Recommendations_Evaluation();
1891
1892        ( new REST_Onboarding() )->register_rest_routes();
1893        ( new REST_Main_Features() )->register_rest_routes();
1894        Google_Analytics_Settings::register_rest_routes();
1895
1896        Products::register_product_endpoints();
1897        Historically_Active_Modules::register_rest_endpoints();
1898        Jetpack_Manage::register_rest_endpoints();
1899        Red_Bubble_Notifications::register_rest_endpoints();
1900
1901        if ( self::is_overview_v1_enabled() ) {
1902            REST_Blog_Posts::register_rest_endpoints();
1903        }
1904
1905        register_rest_route(
1906            'my-jetpack/v1',
1907            'site',
1908            array(
1909                'methods'             => \WP_REST_Server::READABLE,
1910                'callback'            => __CLASS__ . '::get_site',
1911                'permission_callback' => __CLASS__ . '::permissions_callback',
1912            )
1913        );
1914
1915        register_rest_route(
1916            'my-jetpack/v1',
1917            'site/dismiss-welcome-banner',
1918            array(
1919                'methods'             => \WP_REST_Server::EDITABLE,
1920                'callback'            => __CLASS__ . '::dismiss_welcome_banner',
1921                'permission_callback' => __CLASS__ . '::permissions_callback',
1922            )
1923        );
1924    }
1925
1926    /**
1927     * Check user capability to access the endpoint.
1928     *
1929     * @access public
1930     * @static
1931     *
1932     * @return true|WP_Error
1933     */
1934    public static function permissions_callback() {
1935        return current_user_can( 'manage_options' );
1936    }
1937
1938    /**
1939     * Return true if we should initialize the My Jetpack admin page.
1940     */
1941    public static function should_initialize() {
1942        $should = true;
1943
1944        if ( ( new Status() )->is_offline_mode() ) {
1945            $should = self::is_offline_features_enabled();
1946        }
1947
1948        /**
1949         * Allows filtering whether My Jetpack should be initialized.
1950         * Outside REST requests, once the user is set, this cannot enable offline Features for a user without access.
1951         *
1952         * @since 0.5.0-alpha
1953         *
1954         * @param bool $shoud_initialize Should we initialize My Jetpack?
1955         */
1956        $should = apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
1957
1958        // REST authenticates after route registration; its permission callbacks check access.
1959        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() ) {
1960            return false;
1961        }
1962
1963        return $should;
1964    }
1965
1966    /**
1967     * Whether the site uses the local Features entry instead of the connected dashboard.
1968     *
1969     * @since 6.10.0
1970     * @return bool
1971     */
1972    public static function is_offline_features_enabled() {
1973        if ( ! ( new Status() )->is_offline_mode() ) {
1974            return false;
1975        }
1976
1977        /**
1978         * Enable local Features data and entry in offline mode.
1979         *
1980         * @since 6.10.0
1981         * @since 6.15.0 Enabled by default.
1982         * @param bool $enabled Whether to enable offline Features. Default true.
1983         */
1984        return (bool) apply_filters( 'jetpack_my_jetpack_offline_features', true );
1985    }
1986
1987    /**
1988     * Hook into several connection-based actions to update the historically active Jetpack modules
1989     * If the transient that indicates the list needs to be synced, update it and delete the transient
1990     *
1991     * @return void
1992     */
1993    public static function setup_historically_active_jetpack_modules_sync() {
1994        // yummmm. ham.
1995        $ham = new Historically_Active_Modules();
1996        if ( get_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY ) && ! wp_doing_ajax() ) {
1997            $ham::update_historically_active_jetpack_modules();
1998            delete_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY );
1999        }
2000
2001        $actions = array(
2002            'jetpack_site_registered',
2003            'jetpack_user_authorized',
2004            'activated_plugin',
2005        );
2006
2007        foreach ( $actions as $action ) {
2008            add_action( $action, array( $ham, 'queue_historically_active_jetpack_modules_update' ), 5 );
2009        }
2010
2011        // Modules are often updated async, so we need to update them right away as there will sometimes be no page reload.
2012        add_action( 'jetpack_activate_module', array( $ham, 'update_historically_active_jetpack_modules' ), 5 );
2013    }
2014
2015    /**
2016     * Site full-data endpoint.
2017     *
2018     * @return object Site data.
2019     */
2020    public static function get_site() {
2021        $site_id           = \Jetpack_Options::get_option( 'id' );
2022        $wpcom_endpoint    = sprintf( '/sites/%d?force=wpcom', $site_id );
2023        $wpcom_api_version = '1.1';
2024        $response          = Client::wpcom_json_api_request_as_blog( $wpcom_endpoint, $wpcom_api_version );
2025        $response_code     = wp_remote_retrieve_response_code( $response );
2026        $body              = json_decode( wp_remote_retrieve_body( $response ) );
2027
2028        if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
2029            return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
2030        }
2031
2032        return rest_ensure_response( $body );
2033    }
2034
2035    /**
2036     * Populates the self::$site_info var with site data from the /sites/%d endpoint
2037     *
2038     * @return object|WP_Error
2039     */
2040    public static function get_site_info() {
2041        static $site_info = null;
2042
2043        if ( $site_info !== null ) {
2044            return $site_info;
2045        }
2046
2047        // Check for a cached value before doing lookup
2048        $stored_site_info = get_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY );
2049        if ( $stored_site_info !== false ) {
2050            return $stored_site_info;
2051        }
2052
2053        $response = self::get_site();
2054        if ( is_wp_error( $response ) ) {
2055            return $response;
2056        }
2057        $site_info = $response->data;
2058        set_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY, $site_info, DAY_IN_SECONDS );
2059
2060        return $site_info;
2061    }
2062
2063    /**
2064     * Returns whether a site has been determined "commercial" or not.
2065     *
2066     * @return bool|null
2067     */
2068    public static function is_commercial_site() {
2069        if ( is_wp_error( self::$site_info ) ) {
2070            return null;
2071        }
2072
2073        return empty( self::$site_info->options->is_commercial ) ? false : self::$site_info->options->is_commercial;
2074    }
2075
2076    /**
2077     * Check if site is registered (has been connected before).
2078     *
2079     * @return bool
2080     */
2081    public static function is_registered() {
2082        return (bool) \Jetpack_Options::get_option( 'id' );
2083    }
2084
2085    /**
2086     * Dismiss the welcome banner.
2087     *
2088     * @return \WP_REST_Response
2089     */
2090    public static function dismiss_welcome_banner() {
2091        \Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
2092        return rest_ensure_response( array( 'success' => true ) );
2093    }
2094
2095    /**
2096     * Returns "yes" if the site has file write access to the plugins folder, "no" otherwise.
2097     *
2098     * @return string
2099     **/
2100    public static function has_file_system_write_access() {
2101
2102        $cache = get_transient( 'my_jetpack_write_access' );
2103
2104        if ( false !== $cache ) {
2105            return $cache;
2106        }
2107
2108        if ( ! function_exists( 'get_filesystem_method' ) ) {
2109            require_once ABSPATH . 'wp-admin/includes/file.php';
2110        }
2111
2112        require_once ABSPATH . 'wp-admin/includes/template.php';
2113
2114        $write_access = 'no';
2115
2116        $filesystem_method = get_filesystem_method( array(), WP_PLUGIN_DIR );
2117        if ( 'direct' === $filesystem_method ) {
2118            $write_access = 'yes';
2119        }
2120
2121        if ( 'no' === $write_access ) {
2122            ob_start();
2123            $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
2124            ob_end_clean();
2125
2126            if ( $filesystem_credentials_are_stored ) {
2127                $write_access = 'yes';
2128            }
2129        }
2130
2131        set_transient( 'my_jetpack_write_access', $write_access, 30 * MINUTE_IN_SECONDS );
2132
2133        return $write_access;
2134    }
2135
2136    /**
2137     * Get container IDC for the IDC screen.
2138     *
2139     * @return string
2140     */
2141    public static function get_idc_container_id() {
2142        return static::IDC_CONTAINER_ID;
2143    }
2144
2145    /**
2146     * Conditionally append the red bubble notification to the "Jetpack" menu item if there are alerts to show.
2147     *
2148     * On My Jetpack page: Uses blocking behavior to fetch fresh data.
2149     * On other admin pages: Uses cached data only to avoid blocking, with async JS fetch if cache is empty.
2150     *
2151     * @return void
2152     */
2153    public static function maybe_show_red_bubble() {
2154        global $pagenow;
2155
2156        // Don't show red bubble alerts for non-admin users
2157        // These alerts are generally only actionable for admins
2158        if ( ! current_user_can( 'manage_options' ) ) {
2159            return;
2160        }
2161
2162        // Don't show any red bubbles when Jetpack is disconnected
2163        // Users can't act on most alerts without a connection
2164        $connection = new Connection_Manager();
2165        if ( ! $connection->is_connected() ) {
2166            return;
2167        }
2168
2169        // Check if we're on the My Jetpack page.
2170        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
2171        $page               = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
2172        $is_my_jetpack_page = $pagenow === 'admin.php' && $page === 'my-jetpack';
2173
2174        if ( $is_my_jetpack_page ) {
2175            // On My Jetpack page: use blocking behavior for fresh data.
2176            add_filter( 'my_jetpack_red_bubble_notification_slugs', array( Red_Bubble_Notifications::class, 'add_red_bubble_alerts' ) );
2177            $red_bubble_alerts = Red_Bubble_Notifications::get_red_bubble_alerts();
2178        } else {
2179            // On other pages: use cached data only to avoid blocking.
2180            $cached_alerts = Red_Bubble_Notifications::get_cached_alerts();
2181
2182            if ( false === $cached_alerts ) {
2183                // No cache: warm it asynchronously via JS. Register a hidden zero-count
2184                // placeholder so Menu_Renderer emits a `my-jetpack` badge element the
2185                // warmer can reveal (see async-notification-bubble.ts) without a reload.
2186                Menu_Badges::init(); // idempotent; wires the renderer.
2187                Notification_Counts::register(
2188                    'my-jetpack',
2189                    array(
2190                        'menu_slug' => 'my-jetpack',
2191                        'count'     => 0,
2192                        'type'      => 'count',
2193                    )
2194                );
2195                add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_red_bubble_script' ) );
2196                return;
2197            }
2198
2199            $red_bubble_alerts = $cached_alerts;
2200        }
2201
2202        // Filter out silent alerts.
2203        $red_bubble_alerts = array_filter(
2204            $red_bubble_alerts,
2205            function ( $alert ) {
2206                return empty( $alert['is_silent'] );
2207            }
2208        );
2209
2210        // Report each non-silent alert to the central menu-badges registry as an
2211        // attention entry (count 1). The registry + renderer own the badge.
2212        Menu_Badges::init(); // idempotent; wires the renderer.
2213
2214        // Connection errors are owned by the Error Handler (the single source of truth):
2215        // surface any it reports for this viewer as their own attention entry. Read live
2216        // rather than from the red-bubble transient, since that cache is not viewer-keyed.
2217        $has_connection_error = self::has_connection_error();
2218        if ( $has_connection_error ) {
2219            Notification_Counts::register(
2220                'my-jetpack-connection-error',
2221                array(
2222                    'menu_slug' => 'my-jetpack',
2223                    'type'      => 'attention',
2224                )
2225            );
2226        }
2227
2228        $counted_elsewhere = self::get_alerts_counted_elsewhere();
2229        foreach ( array_keys( $red_bubble_alerts ) as $slug ) {
2230            if ( in_array( $slug, $counted_elsewhere, true ) ) {
2231                continue;
2232            }
2233            // The missing-connection slug and a connection error describe the same broken
2234            // connection; count it once (the error, above, is the more specific signal).
2235            if ( $has_connection_error && 'missing-connection' === $slug ) {
2236                continue;
2237            }
2238            Notification_Counts::register(
2239                'my-jetpack-' . $slug,
2240                array(
2241                    'menu_slug' => 'my-jetpack',
2242                    'type'      => 'attention',
2243                )
2244            );
2245        }
2246    }
2247
2248    /**
2249     * Whether the Connection Error Handler reports a displayable connection error
2250     * for the current viewer.
2251     *
2252     * Read live (not via the red-bubble transient): get_displayable_errors() is a
2253     * cached option read that the Error Handler already scopes and caches per viewer.
2254     * Guarded for the mid-plugin-update window, where a stale connection package
2255     * predating the method can be loaded.
2256     *
2257     * @return bool
2258     */
2259    private static function has_connection_error() {
2260        if ( ! class_exists( Connection_Error_Handler::class ) || ! method_exists( Connection_Error_Handler::class, 'get_displayable_errors' ) ) {
2261            return false;
2262        }
2263        return ! empty( Connection_Error_Handler::get_instance()->get_displayable_errors() );
2264    }
2265
2266    /**
2267     * Alerts left out of the My Jetpack badge because another menu item already counts them.
2268     *
2269     * The Protect page reports its own count, from the standalone plugin (class-jetpack-protect.php::admin_page_init())
2270     * or the Protect package's dashboard; without either, nobody else counts the threats, so they must stay.
2271     *
2272     * @return string[] Alert slugs.
2273     */
2274    private static function get_alerts_counted_elsewhere() {
2275        // Without has_protect_page(), use the standalone plugin check this relied on before that method existed.
2276        $has_protect_page = method_exists( Products\Protect::class, 'has_protect_page' ) ? Products\Protect::has_protect_page() : Products\Protect::is_standalone_plugin_active();
2277        return $has_protect_page ? array( 'protect_has_threats' ) : array();
2278    }
2279
2280    /**
2281     * Enqueue the notification bubble script.
2282     * Fetches fresh alert data via REST API without blocking page load.
2283     *
2284     * @return void
2285     */
2286    public static function enqueue_red_bubble_script() {
2287        Assets::register_script(
2288            'my-jetpack-notification-bubble',
2289            '../build/async-notification-bubble.js',
2290            __FILE__,
2291            array(
2292                'enqueue'   => true,
2293                'in_footer' => true,
2294            )
2295        );
2296        wp_localize_script(
2297            'my-jetpack-notification-bubble',
2298            'myJetpackNotificationBubble',
2299            array( 'excludedAlerts' => self::get_alerts_counted_elsewhere() )
2300        );
2301    }
2302
2303    /**
2304     * Get list of module names sorted by their recommendation score
2305     *
2306     * @return array|null
2307     */
2308    public static function get_recommended_modules() {
2309        $recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );
2310
2311        if ( empty( $recommendations_evaluation ) || ! is_array( $recommendations_evaluation ) ) {
2312            return null;
2313        }
2314
2315        arsort( $recommendations_evaluation ); // Sort by scores in descending order
2316
2317        return array_keys( $recommendations_evaluation ); // Get only module names
2318    }
2319}