PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3-beta
Jetpack – WP Security, Backup, Speed, & Growth v16.3-beta
16.3-beta 16.3-a.5 16.3-a.7 16.3-a.3 16.3-a.1 16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 All 507 releases
← All changes | jetpack_vendor/automattic/jetpack-my-jetpack/src/class-initializer.php +754 -267 13.6.2 → 16.3-beta View file →
@@ -11,20 +11,30 @@
11 11 use Automattic\Jetpack\Assets;
12 12 use Automattic\Jetpack\Boost_Speed_Score\Speed_Score;
13 13 use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_History;
14 14 use Automattic\Jetpack\Connection\Client;
15 +use Automattic\Jetpack\Connection\Error_Handler as Connection_Error_Handler;
15 16 use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
16 17 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
17 18 use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
19 +use Automattic\Jetpack\Connection\REST_Jetpack_AI_JWT;
18 20 use Automattic\Jetpack\Constants as Jetpack_Constants;
21 +use Automattic\Jetpack\ExPlat;
22 +use Automattic\Jetpack\Feature_Flags\Feature_Flags;
19 23 use Automattic\Jetpack\JITMS\JITM;
20 24 use Automattic\Jetpack\Licensing;
25 +use Automattic\Jetpack\Menu_Badges\Menu_Badges;
26 +use Automattic\Jetpack\Menu_Badges\Notification_Counts;
21 27 use Automattic\Jetpack\Modules;
28 +use Automattic\Jetpack\Partner_Coupon;
22 29 use Automattic\Jetpack\Plugins_Installer;
23 30 use Automattic\Jetpack\Status;
24 31 use Automattic\Jetpack\Status\Host as Status_Host;
32 +use Automattic\Jetpack\Sync\Functions as Sync_Functions;
25 33 use Automattic\Jetpack\Terms_Of_Service;
26 34 use Automattic\Jetpack\Tracking;
35 +use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
36 +use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
27 37 use Jetpack;
28 38 use WP_Error;
29 39
30 40 /**
@@ -36,16 +46,38 @@
36 46 * My Jetpack package version
37 47 *
38 48 * @var string
39 49 */
40 - const PACKAGE_VERSION = '4.27.0';
50 + const PACKAGE_VERSION = '6.8.0';
41 51
42 52 /**
53 + * Feature flag that swaps the My Jetpack Products tab for a Features tab.
54 + */
55 + const FEATURES_TAB_FEATURE_FLAG = 'my-jetpack-features-tab';
56 +
57 + /**
58 + * Handle for the classic script that carries the React initial state.
59 + *
60 + * Plugins that render My Jetpack components on their own pages (Boost) depend on this name.
61 + */
62 + const DATA_SCRIPT_HANDLE = 'my_jetpack_main_app';
63 +
64 + /**
65 + * Handle for the webpack bundle that renders the onboarding takeover.
66 + */
67 + const ONBOARDING_SCRIPT_HANDLE = 'my_jetpack_onboarding';
68 +
69 + /**
70 + * The wp-build page ID, which the generated enqueue check expects as the screen ID.
71 + */
72 + const WP_BUILD_PAGE_ID = 'my-jetpack-dashboard';
73 +
74 + /**
43 75 * HTML container ID for the IDC screen on My Jetpack page.
44 76 */
45 - const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
77 + private const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
46 78
47 - const JETPACK_PLUGIN_SLUGS = array(
79 + public const JETPACK_PLUGIN_SLUGS = array(
48 80 'jetpack-backup',
49 81 'jetpack-boost',
50 82 'zerobscrm',
51 83 'jetpack',
@@ -52,16 +84,13 @@
52 84 'jetpack-protect',
53 85 'jetpack-social',
54 86 'jetpack-videopress',
55 87 'jetpack-search',
88 + 'jetpack-stats',
56 89 );
57 90
58 - const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
91 + private const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
59 92
60 - const UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY = 'update-historically-active-jetpack-modules';
61 -
62 - const MISSING_CONNECTION_NOTIFICATION_KEY = 'missing-connection';
63 -
64 93 /**
65 94 * Holds info/data about the site (from the /sites/%d endpoint)
66 95 *
67 96 * @var object
@@ -68,17 +97,34 @@
68 97 */
69 98 public static $site_info;
70 99
71 100 /**
101 + * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
102 + *
103 + * @var string|null
104 + */
105 + private static $wp_build_original_screen_id = null;
106 +
107 + /**
72 108 * Initialize My Jetpack
73 109 *
74 110 * @return void
75 111 */
76 112 public static function init() {
113 + // Before the gate, so the flag stays listed while diagnosing why My Jetpack is off.
114 + self::register_feature_flags();
115 +
116 + // Before the gate: the Jetpack plugin renders this package's connection screen and footer
117 + // links even where My Jetpack is off, and `myJetpackInitialState` only exists on its own page.
118 + add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_admin_script_data' ) );
119 +
77 120 if ( ! self::should_initialize() || did_action( 'my_jetpack_init' ) ) {
78 121 return;
79 122 }
80 123
124 + // Answer "is this product on?" for admin menu registration.
125 + Menu_Visibility::init();
126 +
81 127 // Extend jetpack plugins action links.
82 128 Products::extend_plugins_action_links();
83 129
84 130 // Set up the REST authentication hooks.
@@ -93,28 +139,26 @@
93 139
94 140 // Add custom WP REST API endoints.
95 141 add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );
96 142
97 - $page_suffix = Admin_Menu::add_menu(
98 - __( 'My Jetpack', 'jetpack-my-jetpack' ),
99 - __( 'My Jetpack', 'jetpack-my-jetpack' ),
100 - 'edit_posts',
101 - 'my-jetpack',
102 - array( __CLASS__, 'admin_page' ),
103 - -1
104 - );
143 + // Both of wp-build's deadlines fall later in this request: its enqueue check must be
144 + // hooked before `admin_enqueue_scripts`, and its render function defined before
145 + // the page callback.
146 + add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
105 147
106 - add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
148 + add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );
149 +
107 150 add_action( 'admin_init', array( __CLASS__, 'setup_historically_active_jetpack_modules_sync' ) );
108 - // This is later than the admin-ui package, which runs on 1000
109 - add_action( 'admin_init', array( __CLASS__, 'maybe_show_red_bubble' ), 1001 );
151 + // Registered on admin_menu (not admin_init) and well before priority 100000, so the
152 + // counts it registers exist before the menu-badges renderer runs on admin_menu 100000.
153 + add_action( 'admin_menu', array( __CLASS__, 'maybe_show_red_bubble' ), 30 );
110 154
155 + // Set up the ExPlat package endpoints
156 + ExPlat::init();
157 +
111 158 // Sets up JITMS.
112 159 JITM::configure();
113 160
114 - // Add "Activity Log" menu item.
115 - Activitylog::init();
116 -
117 161 // Add "Jetpack Manage" menu item.
118 162 Jetpack_Manage::init();
119 163
120 164 /**
@@ -158,23 +202,157 @@
158 202 );
159 203 }
160 204
161 205 /**
206 + * Add My Jetpack menu item to the admin menu.
207 + *
208 + * @return void
209 + */
210 + public static function add_my_jetpack_menu_item() {
211 + $position = defined( Admin_Menu::class . '::POSITION_FIRST' ) ? Admin_Menu::POSITION_FIRST : -10;
212 + $menu_slug = 'my-jetpack';
213 + $page_suffix = Admin_Menu::add_menu(
214 + __( 'My Jetpack', 'jetpack-my-jetpack' ),
215 + __( 'My Jetpack', 'jetpack-my-jetpack' ),
216 + 'edit_posts',
217 + $menu_slug,
218 + array( __CLASS__, 'admin_page' ),
219 + $position
220 + );
221 + add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
222 + // Users who can edit posts but have no Jetpack menu get an admin_page_ hook instead.
223 + add_action( 'load-admin_page_' . $menu_slug, array( __CLASS__, 'admin_init' ) );
224 + }
225 +
226 + /**
162 227 * Callback for the load my jetpack page hook.
163 228 *
164 229 * @return void
165 230 */
166 231 public static function admin_init() {
232 + $connection = new Connection_Manager();
233 +
234 + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No nonce needed for redirect flow control
235 + $step = isset( $_GET['step'] ) ? sanitize_text_field( wp_unslash( $_GET['step'] ) ) : '';
236 +
237 + // Handle onboarding redirects based on connection status. Onboarding's only action is the
238 + // connect request, which answers a user without `jetpack_connect` with a 403.
239 + $redirect_args = self::get_onboarding_redirect_args(
240 + $step,
241 + $connection->is_connected(),
242 + self::is_onboarding_available() && current_user_can( 'jetpack_connect' )
243 + );
244 +
245 + if ( null !== $redirect_args ) {
246 + $admin_page = add_query_arg( $redirect_args, admin_url( 'admin.php' ) );
247 + $location = wp_sanitize_redirect( $admin_page );
248 +
249 + // Remove wp_get_referer filter applied in `fix_redirect` method of `Jetpack_Admin` class
250 + remove_filter( 'wp_redirect', 'wp_get_referer' );
251 + wp_safe_redirect( $location );
252 +
253 + exit( 0 );
254 + }
255 +
256 + // If the user reaches the onboarding page, add a class to the body
257 + if ( $step === 'onboarding' ) {
258 + add_filter( 'admin_body_class', array( __CLASS__, 'add_onboarding_admin_body_class' ) );
259 + }
260 +
167 261 self::$site_info = self::get_site_info();
168 262 add_filter( 'identity_crisis_container_id', array( static::class, 'get_idc_container_id' ) );
169 263 add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
170 - // Product statuses are constantly changing, so we never want to cache the page.
171 - header( 'Cache-Control: no-cache, no-store, must-revalidate' );
172 - header( 'Pragma: no-cache' );
173 - header( 'Expires: 0' );
174 264 }
175 265
176 266 /**
267 + * Whether the My Jetpack onboarding flow is available on this site.
268 + *
269 + * WordPress.com Simple sites are connected by definition and don't manage their
270 + * connection through My Jetpack, so the onboarding flow (which asks the user to
271 + * connect) never applies there. A pending partner coupon brings its own connect screen.
272 + *
273 + * @internal Not part of the package's public API.
274 + *
275 + * @return bool
276 + */
277 + public static function is_onboarding_available() {
278 + return ! ( new Status_Host() )->is_wpcom_simple() && null === self::get_partner_coupon_screen();
279 + }
280 +
281 + /**
282 + * The partner coupon screen's data, when it should replace the dashboard.
283 + *
284 + * Coupons exist only with the Jetpack plugin, which supplies their products and images.
285 + *
286 + * @since 6.5.0
287 + *
288 + * @return array{coupon: array, assetBaseUrl: string}|null
289 + */
290 + public static function get_partner_coupon_screen() {
291 + if (
292 + ! self::should_initialize()
293 + || ! current_user_can( 'manage_options' )
294 + || ! Jetpack_Constants::is_defined( 'JETPACK__PLUGIN_FILE' )
295 + ) {
296 + return null;
297 + }
298 +
299 + $coupon = Partner_Coupon::get_coupon();
300 + if ( ! $coupon ) {
301 + return null;
302 + }
303 +
304 + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only picks which screen renders.
305 + if ( ! isset( $_GET['showCouponRedemption'] ) && ( new Connection_Manager() )->has_connected_owner() ) {
306 + return null;
307 + }
308 +
309 + return array(
310 + 'coupon' => $coupon,
311 + 'assetBaseUrl' => plugins_url( '', Jetpack_Constants::get_constant( 'JETPACK__PLUGIN_FILE' ) ),
312 + );
313 + }
314 +
315 + /**
316 + * Decide whether the current My Jetpack request should redirect, and where to.
317 + *
318 + * @internal Not part of the package's public API.
319 + *
320 + * @param string $step The current `step` query param.
321 + * @param bool $is_connected Whether the site is connected to WordPress.com.
322 + * @param bool $onboarding_available Whether the onboarding flow is available on this site.
323 + * @return array|null Query args for the redirect, or null to stay on the current page.
324 + */
325 + public static function get_onboarding_redirect_args( $step, $is_connected, $onboarding_available ) {
326 + if ( $onboarding_available && ! $is_connected && $step !== 'onboarding' ) {
327 + // Redirect to onboarding if not connected
328 + return array(
329 + 'page' => 'my-jetpack',
330 + 'step' => 'onboarding',
331 + );
332 + }
333 +
334 + if ( $step === 'onboarding' && ( ! $onboarding_available || $is_connected ) ) {
335 + // Redirect away from onboarding if already connected or onboarding is not available on this site
336 + return array( 'page' => 'my-jetpack' );
337 + }
338 +
339 + return null;
340 + }
341 +
342 + /**
343 + * Add a body class to the My Jetpack onboarding page.
344 + * This class hides the WP Admin toolbar and the sidebar menu.
345 + *
346 + * @param string $classes The body classes.
347 + * @return string The modified body classes.
348 + */
349 + public static function add_onboarding_admin_body_class( $classes ) {
350 + $classes .= 'jetpack-admin-full-screen';
351 + return $classes;
352 + }
353 +
354 + /**
177 355 * Returns whether we are in condition to track to use
178 356 * Analytics functionality like Tracks, MC, or GA.
179 357 */
180 358 public static function can_use_analytics() {
@@ -183,24 +361,272 @@
183 361 $tracking = new Tracking( 'jetpack', $connection );
184 362
185 363 return $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
186 364 }
365 +
187 366 /**
188 - * Enqueue admin page assets.
367 + * Register the package's feature flags.
189 368 *
369 + * @since 6.3.0
370 + *
190 371 * @return void
191 372 */
192 - public static function enqueue_scripts() {
193 - Assets::register_script(
194 - 'my_jetpack_main_app',
195 - '../build/index.js',
196 - __FILE__,
373 + public static function register_feature_flags() {
374 + Feature_Flags::register(
375 + self::FEATURES_TAB_FEATURE_FLAG,
197 376 array(
198 - 'enqueue' => true,
199 - 'in_footer' => true,
200 - 'textdomain' => 'jetpack-my-jetpack',
377 + 'default' => true,
378 + 'description' => 'Replace the My Jetpack Products tab with a Features tab.',
379 + 'owner' => 'my-jetpack',
201 380 )
202 381 );
382 + }
383 +
384 + /**
385 + * Whether the dashboard shows a Features tab in place of the Products tab.
386 + *
387 + * @since 6.4.0
388 + *
389 + * @return bool
390 + */
391 + public static function is_features_tab_enabled() {
392 + return Feature_Flags::is_enabled( self::FEATURES_TAB_FEATURE_FLAG );
393 + }
394 +
395 + /**
396 + * Get the slug and label that replace the Products tab, for links to it.
397 + *
398 + * Null while the tab is unchanged, so links keep their own translated "Products" label.
399 + *
400 + * @since 6.4.0
401 + *
402 + * @return array{slug: string, label: string}|null
403 + */
404 + public static function get_products_section() {
405 + if ( ! self::is_features_tab_enabled() ) {
406 + return null;
407 + }
408 +
409 + return array(
410 + 'slug' => 'features',
411 + 'label' => _x( 'Features', 'Navigation item', 'jetpack-my-jetpack' ),
412 + );
413 + }
414 +
415 + /**
416 + * Whether the current request targets the My Jetpack admin page.
417 + *
418 + * @since 6.3.0
419 + *
420 + * @return bool
421 + */
422 + public static function is_my_jetpack_admin_request() {
423 + if ( ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
424 + return false;
425 + }
426 +
427 + return sanitize_text_field( wp_unslash( $_GET['page'] ) ) === 'my-jetpack'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
428 + }
429 +
430 + /**
431 + * Whether the current request is the full-viewport onboarding takeover.
432 + *
433 + * Onboarding hides all wp-admin chrome and never renders through wp-build.
434 + *
435 + * @since 6.3.0
436 + *
437 + * @return bool
438 + */
439 + public static function is_onboarding_request() {
440 + if ( ! isset( $_GET['step'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
441 + return false;
442 + }
443 +
444 + return sanitize_text_field( wp_unslash( $_GET['step'] ) ) === 'onboarding'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
445 + }
446 +
447 + /**
448 + * Whether this request is the onboarding takeover rather than the dashboard.
449 + *
450 + * Loading wp-build, enqueueing scripts and rendering the page must all agree,
451 + * so they share this one expression.
452 + *
453 + * @since 6.3.0
454 + *
455 + * @return bool
456 + */
457 + public static function is_onboarding_takeover() {
458 + return self::is_onboarding_request() && self::is_onboarding_available();
459 + }
460 +
461 + /**
462 + * Alias the screen ID to satisfy wp-build's generated enqueue check.
463 + *
464 + * @since 6.3.0
465 + *
466 + * @return void
467 + */
468 + public static function alias_screen_id_for_wp_build() {
469 + $screen = get_current_screen();
470 +
471 + if ( ! $screen ) {
472 + return;
473 + }
474 +
475 + self::$wp_build_original_screen_id = $screen->id;
476 + $screen->id = self::WP_BUILD_PAGE_ID;
477 + }
478 +
479 + /**
480 + * Undo alias_screen_id_for_wp_build(), since JITM builds its message path from the screen ID.
481 + *
482 + * @since 6.3.0
483 + *
484 + * @return void
485 + */
486 + public static function restore_screen_id_after_wp_build() {
487 + $screen = get_current_screen();
488 +
489 + if ( ! $screen || null === self::$wp_build_original_screen_id ) {
490 + return;
491 + }
492 +
493 + $screen->id = self::$wp_build_original_screen_id;
494 + self::$wp_build_original_screen_id = null;
495 + }
496 +
497 + /**
498 + * Whether this request should load wp-build at all.
499 + *
500 + * Also what keeps WP_Build_Polyfills from replacing core scripts on every other admin page.
501 + *
502 + * @since 6.3.0
503 + *
504 + * @return bool
505 + */
506 + public static function should_load_wp_build() {
507 + return self::is_my_jetpack_admin_request() && ! self::is_onboarding_takeover();
508 + }
509 +
510 + /**
511 + * Whether this request renders the dashboard through wp-build.
512 + *
513 + * The generated render function is missing where the package was never built.
514 + *
515 + * @since 6.3.0
516 + *
517 + * @return bool
518 + */
519 + public static function should_render_wp_build() {
520 + return ! self::is_onboarding_takeover()
521 + && function_exists( 'jetpack_my_jetpack_my_jetpack_dashboard_wp_admin_render_page' );
522 + }
523 +
524 + /**
525 + * Load wp-build for the My Jetpack dashboard.
526 + *
527 + * @since 6.3.0
528 + *
529 + * @return void
530 + */
531 + public static function maybe_load_wp_build() {
532 + if ( ! self::should_load_wp_build() ) {
533 + return;
534 + }
535 +
536 + $build_index = dirname( __DIR__ ) . '/build/build.php';
537 +
538 + if ( file_exists( $build_index ) ) {
539 + self::load_wp_build( $build_index );
540 + }
541 + }
542 +
543 + /**
544 + * Require the generated wp-build index and wire it into this request.
545 + *
546 + * @since 6.3.0
547 + *
548 + * @param string $build_index Path to the generated `build.php`.
549 + * @return void
550 + */
551 + public static function load_wp_build( $build_index ) {
552 + self::require_wp_build_with_screen_alias( $build_index );
553 +
554 + // wp-build hooks module registration to wp_default_scripts, which has
555 + // already fired by admin_menu — call it directly or the init module
556 + // never reaches the import map.
557 + if ( function_exists( 'jetpack_my_jetpack_register_script_modules' ) ) {
558 + 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.
559 + }
560 +
561 + WP_Build_Polyfills::register(
562 + 'my-jetpack',
563 + array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
564 + );
565 + }
566 +
567 + /**
568 + * Require the generated build file with the screen ID aliased across its enqueue check.
569 + *
570 + * @see WP_Build_Screen_Id::load_with_alias()
571 + * @param string $build_index Path to the generated `build.php`.
572 + * @return void
573 + */
574 + private static function require_wp_build_with_screen_alias( $build_index ) {
575 + // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
576 + if ( method_exists( WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
577 + WP_Build_Screen_Id::load_with_alias(
578 + array( __CLASS__, 'alias_screen_id_for_wp_build' ),
579 + array( __CLASS__, 'restore_screen_id_after_wp_build' ),
580 + function () use ( $build_index ) {
581 + require_once $build_index;
582 + }
583 + );
584 + return;
585 + }
586 +
587 + add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
588 + require_once $build_index;
589 + add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
590 + }
591 +
592 + /**
593 + * Enqueue admin page assets.
594 + *
595 + * @return void
596 + */
597 + public static function enqueue_scripts() {
598 + /**
599 + * Fires after the My Jetpack page is initialized.
600 + * Allows for enqueuing additional scripts only on the My Jetpack page.
601 + *
602 + * @since 4.35.7
603 + */
604 + do_action( 'myjetpack_enqueue_scripts' );
605 + add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ) );
606 +
607 + // Script-less: it only prints the state below, before the dashboard's boot runs on DOMContentLoaded.
608 + $data_handle = self::DATA_SCRIPT_HANDLE;
609 + wp_register_script( $data_handle, false, array(), self::PACKAGE_VERSION, true );
610 + wp_enqueue_script( $data_handle );
611 +
612 + if ( self::is_my_jetpack_admin_request() && self::is_onboarding_takeover() ) {
613 + Assets::register_script(
614 + self::ONBOARDING_SCRIPT_HANDLE,
615 + '../build/onboarding.js',
616 + __FILE__,
617 + array(
618 + 'dependencies' => array( $data_handle ),
619 + 'enqueue' => true,
620 + 'in_footer' => true,
621 + 'textdomain' => 'jetpack-my-jetpack',
622 + )
623 + );
624 + } elseif ( self::should_render_wp_build() && wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
625 + // Registered on every admin page but only enqueued when depended on; the esbuild bundles don't pull it in.
626 + wp_enqueue_script( 'wp-jp-i18n-loader' );
627 + }
628 +
203 629 $modules = new Modules();
204 630 $connection = new Connection_Manager();
205 631 $speed_score_history = new Speed_Score_History( get_site_url() );
206 632 $latest_score = $speed_score_history->latest();
@@ -208,21 +634,29 @@
208 634 if ( $speed_score_history->count() > 1 ) {
209 635 $previous_score = $speed_score_history->latest( 1 );
210 636 }
211 637 $latest_score['previousScores'] = $previous_score['scores'] ?? array();
212 - self::update_historically_active_jetpack_modules();
213 638
639 + $sandboxed_domain = '';
640 + $is_dev_version = false;
641 + if ( class_exists( 'Jetpack' ) ) {
642 + $is_dev_version = Jetpack::is_development_version();
643 + $sandboxed_domain = defined( 'JETPACK__SANDBOX_DOMAIN' ) ? JETPACK__SANDBOX_DOMAIN : '';
644 + }
645 +
646 + $features_tab_enabled = self::is_features_tab_enabled();
647 +
214 648 wp_localize_script(
215 - 'my_jetpack_main_app',
649 + $data_handle,
216 650 'myJetpackInitialState',
217 651 array(
218 652 'products' => array(
219 653 'items' => Products::get_products(),
220 654 ),
221 - 'purchases' => array(
222 - 'items' => array(),
223 - ),
655 + 'mainFeatures' => $features_tab_enabled ? Main_Features::get_state() : null,
656 + 'featuresBanner' => $features_tab_enabled ? array( 'isDismissed' => REST_Main_Features::is_banner_dismissed() ) : null,
224 657 'plugins' => Plugins_Installer::get_plugins(),
658 + 'themes' => Sync_Functions::get_themes(),
225 659 'myJetpackUrl' => admin_url( 'admin.php?page=my-jetpack' ),
226 660 'myJetpackCheckoutUri' => admin_url( 'admin.php?page=my-jetpack' ),
227 661 'topJetpackMenuItemUrl' => Admin_Menu::get_top_level_menu_item_url(),
228 662 'siteSuffix' => ( new Status() )->get_site_suffix(),
@@ -232,35 +666,39 @@
232 666 'myJetpackFlags' => self::get_my_jetpack_flags(),
233 667 'fileSystemWriteAccess' => self::has_file_system_write_access(),
234 668 'loadAddLicenseScreen' => self::is_licensing_ui_enabled(),
235 669 'adminUrl' => esc_url( admin_url() ),
670 + 'assetsUrl' => self::get_assets_url(),
236 671 'IDCContainerID' => static::get_idc_container_id(),
237 672 'userIsAdmin' => current_user_can( 'manage_options' ),
238 - 'userIsNewToJetpack' => self::is_jetpack_user_new(),
239 673 'lifecycleStats' => array(
240 674 'jetpackPlugins' => self::get_installed_jetpack_plugins(),
241 675 'historicallyActiveModules' => \Jetpack_Options::get_option( 'historically_active_modules', array() ),
242 - 'brokenModules' => self::check_for_broken_modules(),
676 + 'brokenModules' => Red_Bubble_Notifications::check_for_broken_modules(),
243 677 'isSiteConnected' => $connection->is_connected(),
244 678 'isUserConnected' => $connection->is_user_connected(),
245 - 'purchases' => self::get_purchases(),
246 679 'modules' => self::get_active_modules(),
247 680 ),
248 - 'redBubbleAlerts' => self::get_red_bubble_alerts(),
681 + 'recommendedModules' => array(
682 + 'modules' => self::get_recommended_modules(),
683 + 'isFirstRun' => \Jetpack_Options::get_option( 'recommendations_first_run', true ),
684 + 'dismissed' => \Jetpack_Options::get_option( 'dismissed_recommendations', false ),
685 + ),
249 686 'isStatsModuleActive' => $modules->is_active( 'stats' ),
250 - 'isUserFromKnownHost' => self::is_user_from_known_host(),
251 - 'isCommercial' => self::is_commercial_site(),
687 + 'canUserViewStats' => current_user_can( 'manage_options' ) || current_user_can( 'view_stats' ),
688 + 'hiddenFeatures' => Feature_Visibility::get_hidden(),
689 + 'sandboxedDomain' => $sandboxed_domain,
690 + 'isDevVersion' => $is_dev_version,
252 691 'isAtomic' => ( new Status_Host() )->is_woa_site(),
253 - 'jetpackManage' => array(
254 - 'isEnabled' => Jetpack_Manage::could_use_jp_manage(),
255 - 'isAgencyAccount' => Jetpack_Manage::is_agency_account(),
256 - ),
692 + 'isJetpackPluginActive' => class_exists( 'Jetpack' ),
257 693 'latestBoostSpeedScores' => $latest_score,
694 + 'seoOptIn' => self::get_seo_opt_in_state(),
695 + 'partnerCoupon' => self::get_partner_coupon_screen(),
258 696 )
259 697 );
260 698
261 699 wp_localize_script(
262 - 'my_jetpack_main_app',
700 + $data_handle,
263 701 'myJetpackRest',
264 702 array(
265 703 'apiRoot' => esc_url_raw( rest_url() ),
266 704 'apiNonce' => wp_create_nonce( 'wp_rest' ),
@@ -267,9 +705,9 @@
267 705 )
268 706 );
269 707
270 708 // Connection Initial State.
271 - Connection_Initial_State::render_script( 'my_jetpack_main_app' );
709 + Connection_Initial_State::render_script( $data_handle );
272 710
273 711 // Required for Analytics.
274 712 if ( self::can_use_analytics() ) {
275 713 Tracking::register_tracks_functions_scripts( true );
@@ -276,27 +714,78 @@
276 714 }
277 715 }
278 716
279 717 /**
280 - * Get product slugs of the active purchases
718 + * Add My Jetpack data to the unified script data object.
281 719 *
720 + * @param array $data The script data.
282 721 * @return array
283 722 */
284 - public static function get_purchases() {
285 - $purchases = Wpcom_Products::get_site_current_purchases();
286 - if ( is_wp_error( $purchases ) ) {
287 - return array();
288 - }
723 + public static function add_script_data( $data ) {
724 + $block_availability = class_exists( '\Jetpack_Gutenberg' )
725 + ? \Jetpack_Gutenberg::get_cached_availability()
726 + : array();
289 727
290 - return array_map(
291 - function ( $purchase ) {
292 - return $purchase->product_slug;
293 - },
294 - $purchases
728 + $data['myJetpack']['siteEditor'] = array(
729 + 'isBlockTheme' => function_exists( 'wp_is_block_theme' ) && wp_is_block_theme(),
730 + 'isSharingBlockAvailable' => isset( $block_availability['sharing-buttons'] )
731 + && $block_availability['sharing-buttons']['available'],
732 + 'isLikeBlockAvailable' => isset( $block_availability['like'] )
733 + && $block_availability['like']['available'],
734 + 'activeThemeStylesheet' => get_stylesheet(),
295 735 );
736 +
737 + return $data;
296 738 }
297 739
298 740 /**
741 + * Add My Jetpack availability, image base URL, and products tab to admin script data.
742 + *
743 + * Printed on every admin page by Script_Data, so the connection screen can resolve its
744 + * illustrations and Jetpack footers can link to the products tab off the My Jetpack page.
745 + *
746 + * @since 6.3.0
747 + *
748 + * @param array $data Script data.
749 + * @return array
750 + */
751 + public static function add_admin_script_data( $data ) {
752 + $data['myJetpack']['isAvailable'] = self::is_admin_page_available();
753 + $data['myJetpack']['assetsUrl'] = self::get_assets_url();
754 + $data['myJetpack']['productsSection'] = self::get_products_section();
755 +
756 + return $data;
757 + }
758 +
759 + /**
760 + * Whether My Jetpack's admin page is available to the current user.
761 + *
762 + * Meaningful only after admin_menu has registered the page.
763 + *
764 + * @since 6.5.0
765 + *
766 + * @return bool
767 + */
768 + public static function is_admin_page_available() {
769 + global $_registered_pages;
770 +
771 + return did_action( 'my_jetpack_init' ) > 0
772 + && isset( $_registered_pages[ get_plugin_page_hookname( 'my-jetpack', 'jetpack' ) ] )
773 + && current_user_can( 'edit_posts' );
774 + }
775 +
776 + /**
777 + * Get the base URL of the package's built images, with a trailing slash.
778 + *
779 + * @since 6.3.0
780 + *
781 + * @return string
782 + */
783 + public static function get_assets_url() {
784 + return trailingslashit( Assets::normalize_path( plugins_url( '../build/images/', __FILE__ ) ) );
785 + }
786 +
787 + /**
299 788 * Get installed Jetpack plugins
300 789 *
301 790 * @return array
302 791 */
@@ -304,11 +793,8 @@
304 793 $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
305 794 $plugin_slugs = array_map(
306 795 static function ( $slug ) {
307 796 $parts = explode( '/', $slug );
308 - if ( empty( $parts ) ) {
309 - return '';
310 - }
311 797 // Return the last segment of the filepath without the PHP extension
312 798 return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
313 799 },
314 800 $plugin_slugs
@@ -329,9 +815,9 @@
329 815 // if the Jetpack plugin is active, filter out the modules that are active by default
330 816 if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
331 817 $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
332 818 }
333 - return $active_modules;
819 + return array_values( $active_modules );
334 820 }
335 821
336 822 /**
337 823 * Determine if the current user is "new" to Jetpack
@@ -350,14 +836,9 @@
350 836
351 837 // TODO: add a data point for the last known connection/ disconnection time
352 838
353 839 // are any modules active?
354 - $modules = new Modules();
355 - $active_modules = $modules->get_active();
356 - // if the Jetpack plugin is active, filter out the modules that are active by default
357 - if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
358 - $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
359 - }
840 + $active_modules = self::get_active_modules();
360 841 if ( ! empty( $active_modules ) ) {
361 842 return false;
362 843 }
363 844
@@ -366,11 +847,8 @@
366 847 $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
367 848 $plugin_slugs = array_map(
368 849 static function ( $slug ) {
369 850 $parts = explode( '/', $slug );
370 - if ( empty( $parts ) ) {
371 - return '';
372 - }
373 851 // Return the last segment of the filepath without the PHP extension
374 852 return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
375 853 },
376 854 $plugin_slugs
@@ -389,18 +867,8 @@
389 867 return true;
390 868 }
391 869
392 870 /**
393 - * Determines whether the user has come from a host we can recognize.
394 - *
395 - * @return string
396 - */
397 - public static function is_user_from_known_host() {
398 - // Known (external) host is the one that has been determined and is not dotcom.
399 - return ! in_array( ( new Status_Host() )->get_known_host_guess(), array( 'unknown', 'wpcom' ), true );
400 - }
401 -
402 - /**
403 871 * Build flags for My Jetpack UI
404 872 *
405 873 * @return array
406 874 */
@@ -406,9 +874,13 @@
406 874 */
407 875 public static function get_my_jetpack_flags() {
408 876 $flags = array(
409 877 'videoPressStats' => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
410 - 'showFullJetpackStatsCard' => class_exists( 'Jetpack' ),
878 + 'showFullJetpackStatsCard' => class_exists( 'Jetpack' ) || Products\Stats::is_standalone_plugin_active(),
879 + // Only says which destination `manage_url` is: the legacy Stats page
880 + // caches its report and wants a `force_refresh` hint the dashboard does not.
881 + 'premiumAnalyticsEnabled' => Products\Stats::is_premium_analytics_enabled(),
882 + 'showAiModuleToggle' => Products\Jetpack_Ai::is_feature_ui_enabled(),
411 883 );
412 884
413 885 return $flags;
414 886 }
@@ -413,14 +885,63 @@
413 885 return $flags;
414 886 }
415 887
416 888 /**
889 + * Build the state the My Jetpack "try the new SEO experience" opt-in card hydrates from.
890 + *
891 + * The card invites an existing self-hosted install to switch over to the new Jetpack SEO
892 + * dashboard (JETPACK-1700). Gating lives server-side, where the signals actually are. The
893 + * card shows only when all of:
894 + *
895 + * - the new SEO product is available — the `rsm_jetpack_seo` feature filter is on (the SEO
896 + * package autoloads regardless, so `class_exists()` alone isn't enough; the filter is the
897 + * real availability switch and the same one the SEO package gates its own surface behind);
898 + * - the site is self-hosted — WordPress.com (Simple + Atomic) decides its own SEO surface, so
899 + * the opt-in card is for self-hosted installs only;
900 + * - the install hasn't opted in yet — `jetpack_seo_surface_visible` is still false. On wpcom
901 + * the SEO package's `is_seo_surface_visible()` short-circuits to `true`, so the
902 + * "not visible yet" check also doubles as the self-hosted guard, but we check the platform
903 + * explicitly for clarity.
904 + *
905 + * Referenced through `class_exists()` rather than a hard composer dependency: both packages
906 + * ship inside the Jetpack plugin and the SEO surface is feature-flagged, so a guarded read of
907 + * its public API keeps this from adding plumbing to consumers that don't load SEO.
908 + *
909 + * The on-success destination is computed by the opt-in endpoint itself; we only seed the card
910 + * with the same admin URL so the button has a sensible fallback before the request resolves.
911 + *
912 + * @return array{showCard: bool, redirect: string}
913 + */
914 + public static function get_seo_opt_in_state() {
915 + // Guard with method_exists rather than class_exists: an older bundled SEO package can ship
916 + // the Initializer class without this method, and class_exists alone would still fatal.
917 + $seo_initializer = 'Automattic\Jetpack\SEO\Initializer';
918 + // @phan-suppress-next-line PhanUndeclaredClassReference -- optional SEO package, guarded by method_exists.
919 + $show_card = method_exists( $seo_initializer, 'is_optin_available' ) && $seo_initializer::is_optin_available();
920 +
921 + return array(
922 + 'showCard' => $show_card,
923 + 'redirect' => admin_url( 'admin.php?page=jetpack-seo' ),
924 + );
925 + }
926 +
927 + /**
417 928 * Echoes the admin page content.
418 929 *
419 930 * @return void
420 931 */
421 932 public static function admin_page() {
422 - echo '<div id="my-jetpack-container"></div>';
933 + // No connection check needed here: admin_init() has already redirected connected users
934 + // away from onboarding. Availability is re-checked inside the helper on purpose — this
935 + // render can run even when that redirect did not.
936 + if ( self::is_onboarding_takeover() ) {
937 + echo '<div id="my-jetpack-container"></div>';
938 + return;
939 + }
940 +
941 + if ( self::should_render_wp_build() ) {
942 + 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.
943 + }
423 944 }
424 945
425 946 /**
426 947 * Register the REST API routes.
@@ -429,12 +950,20 @@
429 950 */
430 951 public static function register_rest_endpoints() {
431 952 new REST_Products();
432 953 new REST_Purchases();
433 - new REST_Zendesk_Chat();
434 - new REST_Product_Data();
435 - new REST_AI();
954 + ( new REST_Jetpack_AI_JWT() )->register_rest_route();
955 + new REST_Recommendations_Evaluation();
436 956
957 + if ( self::is_features_tab_enabled() ) {
958 + ( new REST_Main_Features() )->register_rest_routes();
959 + }
960 +
961 + Products::register_product_endpoints();
962 + Historically_Active_Modules::register_rest_endpoints();
963 + Jetpack_Manage::register_rest_endpoints();
964 + Red_Bubble_Notifications::register_rest_endpoints();
965 +
437 966 register_rest_route(
438 967 'my-jetpack/v1',
439 968 'site',
440 969 array(
@@ -472,12 +1001,8 @@
472 1001 */
473 1002 public static function should_initialize() {
474 1003 $should = true;
475 1004
476 - if ( is_multisite() ) {
477 - $should = false;
478 - }
479 -
480 1005 // All options presented in My Jetpack require a connection to WordPress.com.
481 1006 if ( ( new Status() )->is_offline_mode() ) {
482 1007 $should = false;
483 1008 }
@@ -492,23 +1017,8 @@
492 1017 return apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
493 1018 }
494 1019
495 1020 /**
496 - * Set transient to queue an update to the historically active Jetpack modules on the next wp-admin load
497 - *
498 - * @param string $plugin The plugin that triggered the update. This will be present if the function was queued by a plugin activation.
499 - *
500 - * @return void
501 - */
502 - public static function queue_historically_active_jetpack_modules_update( $plugin = null ) {
503 - $plugin_filenames = Products::get_all_plugin_filenames();
504 -
505 - if ( ! $plugin || in_array( $plugin, $plugin_filenames, true ) ) {
506 - set_transient( self::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY, true );
507 - }
508 - }
509 -
510 - /**
511 1021 * Hook into several connection-based actions to update the historically active Jetpack modules
512 1022 * If the transient that indicates the list needs to be synced, update it and delete the transient
513 1023 *
514 1024 * @return void
@@ -513,11 +1023,13 @@
513 1023 *
514 1024 * @return void
515 1025 */
516 1026 public static function setup_historically_active_jetpack_modules_sync() {
517 - if ( get_transient( self::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY ) && ! wp_doing_ajax() ) {
518 - self::update_historically_active_jetpack_modules();
519 - delete_transient( self::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY );
1027 + // yummmm. ham.
1028 + $ham = new Historically_Active_Modules();
1029 + if ( get_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY ) && ! wp_doing_ajax() ) {
1030 + $ham::update_historically_active_jetpack_modules();
1031 + delete_transient( $ham::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY );
520 1032 }
521 1033
522 1034 $actions = array(
523 1035 'jetpack_site_registered',
@@ -525,54 +1037,16 @@
525 1037 'activated_plugin',
526 1038 );
527 1039
528 1040 foreach ( $actions as $action ) {
529 - add_action( $action, array( __CLASS__, 'queue_historically_active_jetpack_modules_update' ), 5 );
1041 + add_action( $action, array( $ham, 'queue_historically_active_jetpack_modules_update' ), 5 );
530 1042 }
531 1043
532 1044 // Modules are often updated async, so we need to update them right away as there will sometimes be no page reload.
533 - add_action( 'jetpack_activate_module', array( __CLASS__, 'update_historically_active_jetpack_modules' ), 5 );
1045 + add_action( 'jetpack_activate_module', array( $ham, 'update_historically_active_jetpack_modules' ), 5 );
534 1046 }
535 1047
536 1048 /**
537 - * Update historically active Jetpack plugins
538 - * Historically active is defined as the Jetpack plugins that are installed and active with the required connections
539 - * This array will consist of any plugins that were active at one point in time and are still enabled on the site
540 - *
541 - * @return void
542 - */
543 - public static function update_historically_active_jetpack_modules() {
544 - $historically_active_modules = \Jetpack_Options::get_option( 'historically_active_modules', array() );
545 - $products = Products::get_products();
546 -
547 - foreach ( $products as $product ) {
548 - $status = $product['status'];
549 - $product_slug = $product['slug'];
550 - // We want to leave modules in the array if they've been active in the past
551 - // and were not manually disabled by the user.
552 - if ( in_array( $status, Products::$broken_module_statuses, true ) ) {
553 - continue;
554 - }
555 -
556 - // If the module is active and not already in the array, add it
557 - if (
558 - in_array( $status, Products::$active_module_statuses, true ) &&
559 - ! in_array( $product_slug, $historically_active_modules, true )
560 - ) {
561 - $historically_active_modules[] = $product_slug;
562 - }
563 -
564 - // If the module has been disabled due to a manual user action,
565 - // or because of a missing plan error, remove it from the array
566 - if ( in_array( $status, Products::$disabled_module_statuses, true ) ) {
567 - $historically_active_modules = array_values( array_diff( $historically_active_modules, array( $product_slug ) ) );
568 - }
569 - }
570 -
571 - \Jetpack_Options::update_option( 'historically_active_modules', array_unique( $historically_active_modules ) );
572 - }
573 -
574 - /**
575 1049 * Site full-data endpoint.
576 1050 *
577 1051 * @return object Site data.
578 1052 */
@@ -587,9 +1061,9 @@
587 1061 if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
588 1062 return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
589 1063 }
590 1064
591 - return rest_ensure_response( $body, 200 );
1065 + return rest_ensure_response( $body );
592 1066 }
593 1067
594 1068 /**
595 1069 * Populates the self::$site_info var with site data from the /sites/%d endpoint
@@ -621,9 +1095,9 @@
621 1095
622 1096 /**
623 1097 * Returns whether a site has been determined "commercial" or not.
624 1098 *
625 - * @return bool
1099 + * @return bool|null
626 1100 */
627 1101 public static function is_commercial_site() {
628 1102 if ( is_wp_error( self::$site_info ) ) {
629 1103 return null;
@@ -647,13 +1121,13 @@
647 1121 * @return \WP_REST_Response
648 1122 */
649 1123 public static function dismiss_welcome_banner() {
650 1124 \Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
651 - return rest_ensure_response( array( 'success' => true ), 200 );
1125 + return rest_ensure_response( array( 'success' => true ) );
652 1126 }
653 1127
654 1128 /**
655 - * Returns true if the site has file write access to the plugins folder, false otherwise.
1129 + * Returns "yes" if the site has file write access to the plugins folder, "no" otherwise.
656 1130 *
657 1131 * @return string
658 1132 **/
659 1133 public static function has_file_system_write_access() {
@@ -676,9 +1150,9 @@
676 1150 if ( 'direct' === $filesystem_method ) {
677 1151 $write_access = 'yes';
678 1152 }
679 1153
680 - if ( ! $write_access ) {
1154 + if ( 'no' === $write_access ) {
681 1155 ob_start();
682 1156 $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
683 1157 ob_end_clean();
684 1158
@@ -701,149 +1175,162 @@
701 1175 return static::IDC_CONTAINER_ID;
702 1176 }
703 1177
704 1178 /**
705 - * Conditionally append the red bubble notification to the "Jetpack" menu item if there are alerts to show
1179 + * Conditionally append the red bubble notification to the "Jetpack" menu item if there are alerts to show.
706 1180 *
1181 + * On My Jetpack page: Uses blocking behavior to fetch fresh data.
1182 + * On other admin pages: Uses cached data only to avoid blocking, with async JS fetch if cache is empty.
1183 + *
707 1184 * @return void
708 1185 */
709 1186 public static function maybe_show_red_bubble() {
710 - global $menu;
711 - // filters for the items in this file
712 - add_filter( 'my_jetpack_red_bubble_notification_slugs', array( __CLASS__, 'add_red_bubble_alerts' ) );
713 - $red_bubble_alerts = self::get_red_bubble_alerts();
1187 + global $pagenow;
714 1188
715 - // The Jetpack menu item should be on index 3
716 - if (
717 - ! empty( $red_bubble_alerts ) &&
718 - is_countable( $red_bubble_alerts ) &&
719 - isset( $menu[3] ) &&
720 - $menu[3][0] === 'Jetpack'
721 - ) {
722 - // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
723 - $menu[3][0] .= sprintf( ' <span class="awaiting-mod">%d</span>', count( $red_bubble_alerts ) );
1189 + // Don't show red bubble alerts for non-admin users
1190 + // These alerts are generally only actionable for admins
1191 + if ( ! current_user_can( 'manage_options' ) ) {
1192 + return;
724 1193 }
725 - }
726 1194
727 - /**
728 - * Collect all possible alerts that we might use a red bubble notification for
729 - *
730 - * @return array
731 - */
732 - public static function get_red_bubble_alerts() {
733 - static $red_bubble_alerts = array();
1195 + // Don't show any red bubbles when Jetpack is disconnected
1196 + // Users can't act on most alerts without a connection
1197 + $connection = new Connection_Manager();
1198 + if ( ! $connection->is_connected() ) {
1199 + return;
1200 + }
734 1201
735 - // using a static cache since we call this function more than once in the class
736 - if ( ! empty( $red_bubble_alerts ) ) {
737 - return $red_bubble_alerts;
1202 + // Check if we're on the My Jetpack page.
1203 + // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1204 + $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
1205 + $is_my_jetpack_page = $pagenow === 'admin.php' && $page === 'my-jetpack';
1206 +
1207 + if ( $is_my_jetpack_page ) {
1208 + // On My Jetpack page: use blocking behavior for fresh data.
1209 + add_filter( 'my_jetpack_red_bubble_notification_slugs', array( Red_Bubble_Notifications::class, 'add_red_bubble_alerts' ) );
1210 + $red_bubble_alerts = Red_Bubble_Notifications::get_red_bubble_alerts();
1211 + } else {
1212 + // On other pages: use cached data only to avoid blocking.
1213 + $cached_alerts = Red_Bubble_Notifications::get_cached_alerts();
1214 +
1215 + if ( false === $cached_alerts ) {
1216 + // No cache: warm it asynchronously via JS. Register a hidden zero-count
1217 + // placeholder so Menu_Renderer emits a `my-jetpack` badge element the
1218 + // warmer can reveal (see async-notification-bubble.ts) without a reload.
1219 + Menu_Badges::init(); // idempotent; wires the renderer.
1220 + Notification_Counts::register(
1221 + 'my-jetpack',
1222 + array(
1223 + 'menu_slug' => 'my-jetpack',
1224 + 'count' => 0,
1225 + 'type' => 'count',
1226 + )
1227 + );
1228 + add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_red_bubble_script' ) );
1229 + return;
1230 + }
1231 +
1232 + $red_bubble_alerts = $cached_alerts;
738 1233 }
739 - // go find the alerts
740 - $red_bubble_alerts = apply_filters( 'my_jetpack_red_bubble_notification_slugs', $red_bubble_alerts );
741 1234
742 - return $red_bubble_alerts;
743 - }
1235 + // Filter out silent alerts.
1236 + $red_bubble_alerts = array_filter(
1237 + $red_bubble_alerts,
1238 + function ( $alert ) {
1239 + return empty( $alert['is_silent'] );
1240 + }
1241 + );
744 1242
745 - /**
746 - * Check for features broken by a disconnected user or site
747 - *
748 - * @return array
749 - */
750 - public static function check_for_broken_modules() {
751 - $connection = new Connection_Manager();
752 - $is_user_connected = $connection->is_user_connected() || $connection->has_connected_owner();
753 - $is_site_connected = $connection->is_connected();
754 - $broken_modules = array(
755 - 'needs_site_connection' => array(),
756 - 'needs_user_connection' => array(),
757 - );
1243 + // Report each non-silent alert to the central menu-badges registry as an
1244 + // attention entry (count 1). The registry + renderer own the badge.
1245 + Menu_Badges::init(); // idempotent; wires the renderer.
758 1246
759 - if ( $is_user_connected && $is_site_connected ) {
760 - return $broken_modules;
1247 + // Connection errors are owned by the Error Handler (the single source of truth):
1248 + // surface any it reports for this viewer as their own attention entry. Read live
1249 + // rather than from the red-bubble transient, since that cache is not viewer-keyed.
1250 + $has_connection_error = self::has_connection_error();
1251 + if ( $has_connection_error ) {
1252 + Notification_Counts::register(
1253 + 'my-jetpack-connection-error',
1254 + array(
1255 + 'menu_slug' => 'my-jetpack',
1256 + 'type' => 'attention',
1257 + )
1258 + );
761 1259 }
762 1260
763 - $products = Products::get_products_classes();
764 - $historically_active_modules = \Jetpack_Options::get_option( 'historically_active_modules', array() );
765 -
766 - foreach ( $products as $product ) {
767 - if ( ! in_array( $product::$slug, $historically_active_modules, true ) ) {
1261 + foreach ( array_keys( $red_bubble_alerts ) as $slug ) {
1262 + // Protect reports its own count directly to the registry, but only when its
1263 + // standalone plugin is active (see class-jetpack-protect.php::admin_page_init()).
1264 + // If the standalone plugin isn't active, nobody else registers this count, so we
1265 + // must not skip it here or the alert silently disappears from the menu total.
1266 + if ( 'protect_has_threats' === $slug && Products\Protect::is_standalone_plugin_active() ) {
768 1267 continue;
769 1268 }
770 -
771 - if ( $product::$requires_user_connection && ! $is_user_connected ) {
772 - if ( ! in_array( $product::$slug, $broken_modules['needs_user_connection'], true ) ) {
773 - $broken_modules['needs_user_connection'][] = $product::$slug;
774 - }
775 - } elseif ( ! $is_site_connected ) {
776 - if ( ! in_array( $product::$slug, $broken_modules['needs_site_connection'], true ) ) {
777 - $broken_modules['needs_site_connection'][] = $product::$slug;
778 - }
1269 + // The missing-connection slug and a connection error describe the same broken
1270 + // connection; count it once (the error, above, is the more specific signal).
1271 + if ( $has_connection_error && 'missing-connection' === $slug ) {
1272 + continue;
779 1273 }
1274 + Notification_Counts::register(
1275 + 'my-jetpack-' . $slug,
1276 + array(
1277 + 'menu_slug' => 'my-jetpack',
1278 + 'type' => 'attention',
1279 + )
1280 + );
780 1281 }
781 -
782 - return $broken_modules;
783 1282 }
784 1283
785 1284 /**
786 - * Add relevant red bubble notifications
1285 + * Whether the Connection Error Handler reports a displayable connection error
1286 + * for the current viewer.
787 1287 *
788 - * @param array $red_bubble_slugs - slugs that describe the reasons the red bubble is showing.
789 - * @return array
1288 + * Read live (not via the red-bubble transient): get_displayable_errors() is a
1289 + * cached option read that the Error Handler already scopes and caches per viewer.
1290 + * Guarded for the mid-plugin-update window, where a stale connection package
1291 + * predating the method can be loaded.
1292 + *
1293 + * @return bool
790 1294 */
791 - public static function add_red_bubble_alerts( array $red_bubble_slugs ) {
792 - if ( wp_doing_ajax() ) {
793 - return array();
1295 + private static function has_connection_error() {
1296 + if ( ! class_exists( Connection_Error_Handler::class ) || ! method_exists( Connection_Error_Handler::class, 'get_displayable_errors' ) ) {
1297 + return false;
794 1298 }
1299 + return ! empty( Connection_Error_Handler::get_instance()->get_displayable_errors() );
1300 + }
795 1301
796 - $welcome_banner_dismissed = \Jetpack_Options::get_option( 'dismissed_welcome_banner', false );
797 - if ( self::is_jetpack_user_new() && ! $welcome_banner_dismissed ) {
798 - $red_bubble_slugs['welcome-banner-active'] = null;
799 - return $red_bubble_slugs;
800 - } else {
801 - return self::alert_if_missing_connection( $red_bubble_slugs );
802 - }
1302 + /**
1303 + * Enqueue the notification bubble script.
1304 + * Fetches fresh alert data via REST API without blocking page load.
1305 + *
1306 + * @return void
1307 + */
1308 + public static function enqueue_red_bubble_script() {
1309 + Assets::register_script(
1310 + 'my-jetpack-notification-bubble',
1311 + '../build/async-notification-bubble.js',
1312 + __FILE__,
1313 + array(
1314 + 'enqueue' => true,
1315 + 'in_footer' => true,
1316 + )
1317 + );
803 1318 }
804 1319
805 1320 /**
806 - * Add an alert slug if the site is missing a site connection
1321 + * Get list of module names sorted by their recommendation score
807 1322 *
808 - * @param array $red_bubble_slugs - slugs that describe the reasons the red bubble is showing.
809 - * @return array
1323 + * @return array|null
810 1324 */
811 - public static function alert_if_missing_connection( array $red_bubble_slugs ) {
812 - $broken_modules = self::check_for_broken_modules();
813 - $connection = new Connection_Manager();
1325 + public static function get_recommended_modules() {
1326 + $recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );
814 1327
815 - if ( ! empty( $broken_modules['needs_user_connection'] ) ) {
816 - $red_bubble_slugs[ self::MISSING_CONNECTION_NOTIFICATION_KEY ] = array(
817 - 'type' => 'user',
818 - 'is_error' => true,
819 - );
820 - return $red_bubble_slugs;
1328 + if ( empty( $recommendations_evaluation ) || ! is_array( $recommendations_evaluation ) ) {
1329 + return null;
821 1330 }
822 1331
823 - if ( ! empty( $broken_modules['needs_site_connection'] ) ) {
824 - $red_bubble_slugs[ self::MISSING_CONNECTION_NOTIFICATION_KEY ] = array(
825 - 'type' => 'site',
826 - 'is_error' => true,
827 - );
828 - return $red_bubble_slugs;
829 - }
1332 + arsort( $recommendations_evaluation ); // Sort by scores in descending order
830 1333
831 - if ( ! $connection->is_user_connected() && ! $connection->has_connected_owner() ) {
832 - $red_bubble_slugs[ self::MISSING_CONNECTION_NOTIFICATION_KEY ] = array(
833 - 'type' => 'user',
834 - 'is_error' => false,
835 - );
836 - return $red_bubble_slugs;
837 - }
838 -
839 - if ( ! $connection->is_connected() ) {
840 - $red_bubble_slugs[ self::MISSING_CONNECTION_NOTIFICATION_KEY ] = array(
841 - 'type' => 'site',
842 - 'is_error' => false,
843 - );
844 - return $red_bubble_slugs;
845 - }
846 -
847 - return $red_bubble_slugs;
1334 + return array_keys( $recommendations_evaluation ); // Get only module names
848 1335 }
849 1336 }