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