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