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 +741 -297 13.7.2 → 16.3-beta View file →
@@ -11,24 +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;
19 21 use Automattic\Jetpack\ExPlat;
22 +use Automattic\Jetpack\Feature_Flags\Feature_Flags;
20 23 use Automattic\Jetpack\JITMS\JITM;
21 24 use Automattic\Jetpack\Licensing;
25 +use Automattic\Jetpack\Menu_Badges\Menu_Badges;
26 +use Automattic\Jetpack\Menu_Badges\Notification_Counts;
22 27 use Automattic\Jetpack\Modules;
28 +use Automattic\Jetpack\Partner_Coupon;
23 29 use Automattic\Jetpack\Plugins_Installer;
24 -use Automattic\Jetpack\Protect_Status\Status as Protect_Status;
25 30 use Automattic\Jetpack\Status;
26 31 use Automattic\Jetpack\Status\Host as Status_Host;
27 32 use Automattic\Jetpack\Sync\Functions as Sync_Functions;
28 33 use Automattic\Jetpack\Terms_Of_Service;
29 34 use Automattic\Jetpack\Tracking;
30 -use Automattic\Jetpack\Waf\Waf_Runner;
35 +use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
36 +use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id;
31 37 use Jetpack;
32 38 use WP_Error;
33 39
34 40 /**
@@ -40,16 +46,38 @@
40 46 * My Jetpack package version
41 47 *
42 48 * @var string
43 49 */
44 - const PACKAGE_VERSION = '4.32.0';
50 + const PACKAGE_VERSION = '6.8.0';
45 51
46 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 + /**
47 75 * HTML container ID for the IDC screen on My Jetpack page.
48 76 */
49 - const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
77 + private const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
50 78
51 - const JETPACK_PLUGIN_SLUGS = array(
79 + public const JETPACK_PLUGIN_SLUGS = array(
52 80 'jetpack-backup',
53 81 'jetpack-boost',
54 82 'zerobscrm',
55 83 'jetpack',
@@ -56,16 +84,13 @@
56 84 'jetpack-protect',
57 85 'jetpack-social',
58 86 'jetpack-videopress',
59 87 'jetpack-search',
88 + 'jetpack-stats',
60 89 );
61 90
62 - const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
91 + private const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
63 92
64 - const UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY = 'update-historically-active-jetpack-modules';
65 -
66 - const MISSING_CONNECTION_NOTIFICATION_KEY = 'missing-connection';
67 -
68 93 /**
69 94 * Holds info/data about the site (from the /sites/%d endpoint)
70 95 *
71 96 * @var object
@@ -72,17 +97,34 @@
72 97 */
73 98 public static $site_info;
74 99
75 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 + /**
76 108 * Initialize My Jetpack
77 109 *
78 110 * @return void
79 111 */
80 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 +
81 120 if ( ! self::should_initialize() || did_action( 'my_jetpack_init' ) ) {
82 121 return;
83 122 }
84 123
124 + // Answer "is this product on?" for admin menu registration.
125 + Menu_Visibility::init();
126 +
85 127 // Extend jetpack plugins action links.
86 128 Products::extend_plugins_action_links();
87 129
88 130 // Set up the REST authentication hooks.
@@ -97,31 +139,26 @@
97 139
98 140 // Add custom WP REST API endoints.
99 141 add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );
100 142
101 - $page_suffix = Admin_Menu::add_menu(
102 - __( 'My Jetpack', 'jetpack-my-jetpack' ),
103 - __( 'My Jetpack', 'jetpack-my-jetpack' ),
104 - 'edit_posts',
105 - 'my-jetpack',
106 - array( __CLASS__, 'admin_page' ),
107 - -1
108 - );
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 );
109 147
110 - add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
148 + add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );
149 +
111 150 add_action( 'admin_init', array( __CLASS__, 'setup_historically_active_jetpack_modules_sync' ) );
112 - // This is later than the admin-ui package, which runs on 1000
113 - 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 );
114 154
115 - //  Set up the ExPlat package endpoints
155 + // Set up the ExPlat package endpoints
116 156 ExPlat::init();
117 157
118 158 // Sets up JITMS.
119 159 JITM::configure();
120 160
121 - // Add "Activity Log" menu item.
122 - Activitylog::init();
123 -
124 161 // Add "Jetpack Manage" menu item.
125 162 Jetpack_Manage::init();
126 163
127 164 /**
@@ -165,23 +202,157 @@
165 202 );
166 203 }
167 204
168 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 + /**
169 227 * Callback for the load my jetpack page hook.
170 228 *
171 229 * @return void
172 230 */
173 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 +
174 261 self::$site_info = self::get_site_info();
175 262 add_filter( 'identity_crisis_container_id', array( static::class, 'get_idc_container_id' ) );
176 263 add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
177 - // Product statuses are constantly changing, so we never want to cache the page.
178 - header( 'Cache-Control: no-cache, no-store, must-revalidate' );
179 - header( 'Pragma: no-cache' );
180 - header( 'Expires: 0' );
181 264 }
182 265
183 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 + /**
184 355 * Returns whether we are in condition to track to use
185 356 * Analytics functionality like Tracks, MC, or GA.
186 357 */
187 358 public static function can_use_analytics() {
@@ -190,24 +361,272 @@
190 361 $tracking = new Tracking( 'jetpack', $connection );
191 362
192 363 return $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
193 364 }
365 +
194 366 /**
195 - * Enqueue admin page assets.
367 + * Register the package's feature flags.
196 368 *
369 + * @since 6.3.0
370 + *
197 371 * @return void
198 372 */
199 - public static function enqueue_scripts() {
200 - Assets::register_script(
201 - 'my_jetpack_main_app',
202 - '../build/index.js',
203 - __FILE__,
373 + public static function register_feature_flags() {
374 + Feature_Flags::register(
375 + self::FEATURES_TAB_FEATURE_FLAG,
204 376 array(
205 - 'enqueue' => true,
206 - 'in_footer' => true,
207 - 'textdomain' => 'jetpack-my-jetpack',
377 + 'default' => true,
378 + 'description' => 'Replace the My Jetpack Products tab with a Features tab.',
379 + 'owner' => 'my-jetpack',
208 380 )
209 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 +
210 629 $modules = new Modules();
211 630 $connection = new Connection_Manager();
212 631 $speed_score_history = new Speed_Score_History( get_site_url() );
213 632 $latest_score = $speed_score_history->latest();
@@ -215,21 +634,27 @@
215 634 if ( $speed_score_history->count() > 1 ) {
216 635 $previous_score = $speed_score_history->latest( 1 );
217 636 }
218 637 $latest_score['previousScores'] = $previous_score['scores'] ?? array();
219 - $scan_data = Protect_Status::get_status();
220 - self::update_historically_active_jetpack_modules();
221 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 +
222 648 wp_localize_script(
223 - 'my_jetpack_main_app',
649 + $data_handle,
224 650 'myJetpackInitialState',
225 651 array(
226 652 'products' => array(
227 653 'items' => Products::get_products(),
228 654 ),
229 - 'purchases' => array(
230 - 'items' => array(),
231 - ),
655 + 'mainFeatures' => $features_tab_enabled ? Main_Features::get_state() : null,
656 + 'featuresBanner' => $features_tab_enabled ? array( 'isDismissed' => REST_Main_Features::is_banner_dismissed() ) : null,
232 657 'plugins' => Plugins_Installer::get_plugins(),
233 658 'themes' => Sync_Functions::get_themes(),
234 659 'myJetpackUrl' => admin_url( 'admin.php?page=my-jetpack' ),
235 660 'myJetpackCheckoutUri' => admin_url( 'admin.php?page=my-jetpack' ),
@@ -241,48 +666,39 @@
241 666 'myJetpackFlags' => self::get_my_jetpack_flags(),
242 667 'fileSystemWriteAccess' => self::has_file_system_write_access(),
243 668 'loadAddLicenseScreen' => self::is_licensing_ui_enabled(),
244 669 'adminUrl' => esc_url( admin_url() ),
670 + 'assetsUrl' => self::get_assets_url(),
245 671 'IDCContainerID' => static::get_idc_container_id(),
246 672 'userIsAdmin' => current_user_can( 'manage_options' ),
247 - 'userIsNewToJetpack' => self::is_jetpack_user_new(),
248 673 'lifecycleStats' => array(
249 674 'jetpackPlugins' => self::get_installed_jetpack_plugins(),
250 675 'historicallyActiveModules' => \Jetpack_Options::get_option( 'historically_active_modules', array() ),
251 - 'ownedProducts' => Products::get_products_by_ownership( 'owned' ),
252 - 'unownedProducts' => Products::get_products_by_ownership( 'unowned' ),
253 - 'brokenModules' => self::check_for_broken_modules(),
676 + 'brokenModules' => Red_Bubble_Notifications::check_for_broken_modules(),
254 677 'isSiteConnected' => $connection->is_connected(),
255 678 'isUserConnected' => $connection->is_user_connected(),
256 - 'purchases' => self::get_purchases(),
257 679 'modules' => self::get_active_modules(),
258 680 ),
259 - 'redBubbleAlerts' => self::get_red_bubble_alerts(),
260 681 'recommendedModules' => array(
261 - 'modules' => self::get_recommended_modules(),
262 - 'dismissed' => \Jetpack_Options::get_option( 'dismissed_recommendations', false ),
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 ),
263 685 ),
264 686 'isStatsModuleActive' => $modules->is_active( 'stats' ),
265 - 'isUserFromKnownHost' => self::is_user_from_known_host(),
266 - '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,
267 691 'isAtomic' => ( new Status_Host() )->is_woa_site(),
268 - 'jetpackManage' => array(
269 - 'isEnabled' => Jetpack_Manage::could_use_jp_manage(),
270 - 'isAgencyAccount' => Jetpack_Manage::is_agency_account(),
271 - ),
692 + 'isJetpackPluginActive' => class_exists( 'Jetpack' ),
272 693 'latestBoostSpeedScores' => $latest_score,
273 - 'protect' => array(
274 - 'scanData' => $scan_data,
275 - 'wafConfig' => array_merge(
276 - Waf_Runner::get_config(),
277 - array( 'blocked_logins' => (int) get_site_option( 'jetpack_protect_blocked_attempts', 0 ) )
278 - ),
279 - ),
694 + 'seoOptIn' => self::get_seo_opt_in_state(),
695 + 'partnerCoupon' => self::get_partner_coupon_screen(),
280 696 )
281 697 );
282 698
283 699 wp_localize_script(
284 - 'my_jetpack_main_app',
700 + $data_handle,
285 701 'myJetpackRest',
286 702 array(
287 703 'apiRoot' => esc_url_raw( rest_url() ),
288 704 'apiNonce' => wp_create_nonce( 'wp_rest' ),
@@ -289,9 +705,9 @@
289 705 )
290 706 );
291 707
292 708 // Connection Initial State.
293 - Connection_Initial_State::render_script( 'my_jetpack_main_app' );
709 + Connection_Initial_State::render_script( $data_handle );
294 710
295 711 // Required for Analytics.
296 712 if ( self::can_use_analytics() ) {
297 713 Tracking::register_tracks_functions_scripts( true );
@@ -298,27 +714,78 @@
298 714 }
299 715 }
300 716
301 717 /**
302 - * Get product slugs of the active purchases
718 + * Add My Jetpack data to the unified script data object.
303 719 *
720 + * @param array $data The script data.
304 721 * @return array
305 722 */
306 - public static function get_purchases() {
307 - $purchases = Wpcom_Products::get_site_current_purchases();
308 - if ( is_wp_error( $purchases ) ) {
309 - return array();
310 - }
723 + public static function add_script_data( $data ) {
724 + $block_availability = class_exists( '\Jetpack_Gutenberg' )
725 + ? \Jetpack_Gutenberg::get_cached_availability()
726 + : array();
311 727
312 - return array_map(
313 - function ( $purchase ) {
314 - return $purchase->product_slug;
315 - },
316 - $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(),
317 735 );
736 +
737 + return $data;
318 738 }
319 739
320 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 + /**
321 788 * Get installed Jetpack plugins
322 789 *
323 790 * @return array
324 791 */
@@ -326,11 +793,8 @@
326 793 $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
327 794 $plugin_slugs = array_map(
328 795 static function ( $slug ) {
329 796 $parts = explode( '/', $slug );
330 - if ( empty( $parts ) ) {
331 - return '';
332 - }
333 797 // Return the last segment of the filepath without the PHP extension
334 798 return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
335 799 },
336 800 $plugin_slugs
@@ -383,11 +847,8 @@
383 847 $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
384 848 $plugin_slugs = array_map(
385 849 static function ( $slug ) {
386 850 $parts = explode( '/', $slug );
387 - if ( empty( $parts ) ) {
388 - return '';
389 - }
390 851 // Return the last segment of the filepath without the PHP extension
391 852 return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
392 853 },
393 854 $plugin_slugs
@@ -406,18 +867,8 @@
406 867 return true;
407 868 }
408 869
409 870 /**
410 - * Determines whether the user has come from a host we can recognize.
411 - *
412 - * @return string
413 - */
414 - public static function is_user_from_known_host() {
415 - // Known (external) host is the one that has been determined and is not dotcom.
416 - return ! in_array( ( new Status_Host() )->get_known_host_guess(), array( 'unknown', 'wpcom' ), true );
417 - }
418 -
419 - /**
420 871 * Build flags for My Jetpack UI
421 872 *
422 873 * @return array
423 874 */
@@ -423,9 +874,13 @@
423 874 */
424 875 public static function get_my_jetpack_flags() {
425 876 $flags = array(
426 877 'videoPressStats' => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
427 - '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(),
428 883 );
429 884
430 885 return $flags;
431 886 }
@@ -430,14 +885,63 @@
430 885 return $flags;
431 886 }
432 887
433 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 + /**
434 928 * Echoes the admin page content.
435 929 *
436 930 * @return void
437 931 */
438 932 public static function admin_page() {
439 - 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 + }
440 944 }
441 945
442 946 /**
443 947 * Register the REST API routes.
@@ -446,13 +950,20 @@
446 950 */
447 951 public static function register_rest_endpoints() {
448 952 new REST_Products();
449 953 new REST_Purchases();
450 - new REST_Zendesk_Chat();
451 - new REST_Product_Data();
452 - new REST_AI();
954 + ( new REST_Jetpack_AI_JWT() )->register_rest_route();
453 955 new REST_Recommendations_Evaluation();
454 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 +
455 966 register_rest_route(
456 967 'my-jetpack/v1',
457 968 'site',
458 969 array(
@@ -490,12 +1001,8 @@
490 1001 */
491 1002 public static function should_initialize() {
492 1003 $should = true;
493 1004
494 - if ( is_multisite() ) {
495 - $should = false;
496 - }
497 -
498 1005 // All options presented in My Jetpack require a connection to WordPress.com.
499 1006 if ( ( new Status() )->is_offline_mode() ) {
500 1007 $should = false;
501 1008 }
@@ -510,23 +1017,8 @@
510 1017 return apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
511 1018 }
512 1019
513 1020 /**
514 - * Set transient to queue an update to the historically active Jetpack modules on the next wp-admin load
515 - *
516 - * @param string $plugin The plugin that triggered the update. This will be present if the function was queued by a plugin activation.
517 - *
518 - * @return void
519 - */
520 - public static function queue_historically_active_jetpack_modules_update( $plugin = null ) {
521 - $plugin_filenames = Products::get_all_plugin_filenames();
522 -
523 - if ( ! $plugin || in_array( $plugin, $plugin_filenames, true ) ) {
524 - set_transient( self::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY, true );
525 - }
526 - }
527 -
528 - /**
529 1021 * Hook into several connection-based actions to update the historically active Jetpack modules
530 1022 * If the transient that indicates the list needs to be synced, update it and delete the transient
531 1023 *
532 1024 * @return void
@@ -531,11 +1023,13 @@
531 1023 *
532 1024 * @return void
533 1025 */
534 1026 public static function setup_historically_active_jetpack_modules_sync() {
535 - if ( get_transient( self::UPDATE_HISTORICALLY_ACTIVE_JETPACK_MODULES_KEY ) && ! wp_doing_ajax() ) {
536 - self::update_historically_active_jetpack_modules();
537 - 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 );
538 1032 }
539 1033
540 1034 $actions = array(
541 1035 'jetpack_site_registered',
@@ -543,54 +1037,16 @@
543 1037 'activated_plugin',
544 1038 );
545 1039
546 1040 foreach ( $actions as $action ) {
547 - 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 );
548 1042 }
549 1043
550 1044 // Modules are often updated async, so we need to update them right away as there will sometimes be no page reload.
551 - 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 );
552 1046 }
553 1047
554 1048 /**
555 - * Update historically active Jetpack plugins
556 - * Historically active is defined as the Jetpack plugins that are installed and active with the required connections
557 - * This array will consist of any plugins that were active at one point in time and are still enabled on the site
558 - *
559 - * @return void
560 - */
561 - public static function update_historically_active_jetpack_modules() {
562 - $historically_active_modules = \Jetpack_Options::get_option( 'historically_active_modules', array() );
563 - $products = Products::get_products();
564 -
565 - foreach ( $products as $product ) {
566 - $status = $product['status'];
567 - $product_slug = $product['slug'];
568 - // We want to leave modules in the array if they've been active in the past
569 - // and were not manually disabled by the user.
570 - if ( in_array( $status, Products::$broken_module_statuses, true ) ) {
571 - continue;
572 - }
573 -
574 - // If the module is active and not already in the array, add it
575 - if (
576 - in_array( $status, Products::$active_module_statuses, true ) &&
577 - ! in_array( $product_slug, $historically_active_modules, true )
578 - ) {
579 - $historically_active_modules[] = $product_slug;
580 - }
581 -
582 - // If the module has been disabled due to a manual user action,
583 - // or because of a missing plan error, remove it from the array
584 - if ( in_array( $status, Products::$disabled_module_statuses, true ) ) {
585 - $historically_active_modules = array_values( array_diff( $historically_active_modules, array( $product_slug ) ) );
586 - }
587 - }
588 -
589 - \Jetpack_Options::update_option( 'historically_active_modules', array_unique( $historically_active_modules ) );
590 - }
591 -
592 - /**
593 1049 * Site full-data endpoint.
594 1050 *
595 1051 * @return object Site data.
596 1052 */
@@ -605,9 +1061,9 @@
605 1061 if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
606 1062 return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
607 1063 }
608 1064
609 - return rest_ensure_response( $body, 200 );
1065 + return rest_ensure_response( $body );
610 1066 }
611 1067
612 1068 /**
613 1069 * Populates the self::$site_info var with site data from the /sites/%d endpoint
@@ -639,9 +1095,9 @@
639 1095
640 1096 /**
641 1097 * Returns whether a site has been determined "commercial" or not.
642 1098 *
643 - * @return bool
1099 + * @return bool|null
644 1100 */
645 1101 public static function is_commercial_site() {
646 1102 if ( is_wp_error( self::$site_info ) ) {
647 1103 return null;
@@ -665,13 +1121,13 @@
665 1121 * @return \WP_REST_Response
666 1122 */
667 1123 public static function dismiss_welcome_banner() {
668 1124 \Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
669 - return rest_ensure_response( array( 'success' => true ), 200 );
1125 + return rest_ensure_response( array( 'success' => true ) );
670 1126 }
671 1127
672 1128 /**
673 - * 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.
674 1130 *
675 1131 * @return string
676 1132 **/
677 1133 public static function has_file_system_write_access() {
@@ -694,9 +1150,9 @@
694 1150 if ( 'direct' === $filesystem_method ) {
695 1151 $write_access = 'yes';
696 1152 }
697 1153
698 - if ( ! $write_access ) {
1154 + if ( 'no' === $write_access ) {
699 1155 ob_start();
700 1156 $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
701 1157 ob_end_clean();
702 1158
@@ -719,174 +1175,162 @@
719 1175 return static::IDC_CONTAINER_ID;
720 1176 }
721 1177
722 1178 /**
723 - * 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.
724 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 + *
725 1184 * @return void
726 1185 */
727 1186 public static function maybe_show_red_bubble() {
728 - global $menu;
729 - // filters for the items in this file
730 - add_filter( 'my_jetpack_red_bubble_notification_slugs', array( __CLASS__, 'add_red_bubble_alerts' ) );
731 - $red_bubble_alerts = array_filter(
732 - self::get_red_bubble_alerts(),
733 - function ( $alert ) {
734 - // We don't want to show silent alerts
735 - return ! $alert['is_silent'];
736 - }
737 - );
1187 + global $pagenow;
738 1188
739 - // The Jetpack menu item should be on index 3
740 - if (
741 - ! empty( $red_bubble_alerts ) &&
742 - is_countable( $red_bubble_alerts ) &&
743 - isset( $menu[3] ) &&
744 - $menu[3][0] === 'Jetpack'
745 - ) {
746 - // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
747 - $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;
748 1193 }
749 - }
750 1194
751 - /**
752 - * Collect all possible alerts that we might use a red bubble notification for
753 - *
754 - * @return array
755 - */
756 - public static function get_red_bubble_alerts() {
757 - 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 + }
758 1201
759 - // using a static cache since we call this function more than once in the class
760 - if ( ! empty( $red_bubble_alerts ) ) {
761 - return $red_bubble_alerts;
762 - }
763 - // go find the alerts
764 - $red_bubble_alerts = apply_filters( 'my_jetpack_red_bubble_notification_slugs', $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';
765 1206
766 - return $red_bubble_alerts;
767 - }
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();
768 1214
769 - /**
770 - * Get list of module names sorted by their recommendation score
771 - *
772 - * @return array|null
773 - */
774 - public static function get_recommended_modules() {
775 - $recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );
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 + }
776 1231
777 - if ( ! $recommendations_evaluation ) {
778 - return null;
1232 + $red_bubble_alerts = $cached_alerts;
779 1233 }
780 1234
781 - arsort( $recommendations_evaluation ); // Sort by scores in descending order
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 + );
782 1242
783 - return array_keys( $recommendations_evaluation ); // Get only module names
784 - }
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.
785 1246
786 - /**
787 - * Check for features broken by a disconnected user or site
788 - *
789 - * @return array
790 - */
791 - public static function check_for_broken_modules() {
792 - $connection = new Connection_Manager();
793 - $is_user_connected = $connection->is_user_connected() || $connection->has_connected_owner();
794 - $is_site_connected = $connection->is_connected();
795 - $broken_modules = array(
796 - 'needs_site_connection' => array(),
797 - 'needs_user_connection' => array(),
798 - );
799 -
800 - if ( $is_user_connected && $is_site_connected ) {
801 - 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 + );
802 1259 }
803 1260
804 - $products = Products::get_products_classes();
805 - $historically_active_modules = \Jetpack_Options::get_option( 'historically_active_modules', array() );
806 -
807 - foreach ( $products as $product ) {
808 - 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() ) {
809 1267 continue;
810 1268 }
811 -
812 - if ( $product::$requires_user_connection && ! $is_user_connected ) {
813 - if ( ! in_array( $product::$slug, $broken_modules['needs_user_connection'], true ) ) {
814 - $broken_modules['needs_user_connection'][] = $product::$slug;
815 - }
816 - } elseif ( ! $is_site_connected ) {
817 - if ( ! in_array( $product::$slug, $broken_modules['needs_site_connection'], true ) ) {
818 - $broken_modules['needs_site_connection'][] = $product::$slug;
819 - }
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;
820 1273 }
1274 + Notification_Counts::register(
1275 + 'my-jetpack-' . $slug,
1276 + array(
1277 + 'menu_slug' => 'my-jetpack',
1278 + 'type' => 'attention',
1279 + )
1280 + );
821 1281 }
822 -
823 - return $broken_modules;
824 1282 }
825 1283
826 1284 /**
827 - * Add relevant red bubble notifications
1285 + * Whether the Connection Error Handler reports a displayable connection error
1286 + * for the current viewer.
828 1287 *
829 - * @param array $red_bubble_slugs - slugs that describe the reasons the red bubble is showing.
830 - * @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
831 1294 */
832 - public static function add_red_bubble_alerts( array $red_bubble_slugs ) {
833 - if ( wp_doing_ajax() ) {
834 - 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;
835 1298 }
836 - $connection = new Connection_Manager();
837 - $welcome_banner_dismissed = \Jetpack_Options::get_option( 'dismissed_welcome_banner', false );
838 - if ( self::is_jetpack_user_new() && ! $welcome_banner_dismissed ) {
839 - $red_bubble_slugs['welcome-banner-active'] = array(
840 - 'is_silent' => $connection->is_connected(), // we don't display the red bubble if the user is connected
841 - );
842 - return $red_bubble_slugs;
843 - } else {
844 - return self::alert_if_missing_connection( $red_bubble_slugs );
845 - }
1299 + return ! empty( Connection_Error_Handler::get_instance()->get_displayable_errors() );
846 1300 }
847 1301
848 1302 /**
849 - * Add an alert slug if the site is missing a site connection
1303 + * Enqueue the notification bubble script.
1304 + * Fetches fresh alert data via REST API without blocking page load.
850 1305 *
851 - * @param array $red_bubble_slugs - slugs that describe the reasons the red bubble is showing.
852 - * @return array
1306 + * @return void
853 1307 */
854 - public static function alert_if_missing_connection( array $red_bubble_slugs ) {
855 - $broken_modules = self::check_for_broken_modules();
856 - $connection = new Connection_Manager();
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 + );
1318 + }
857 1319
858 - if ( ! empty( $broken_modules['needs_user_connection'] ) ) {
859 - $red_bubble_slugs[ self::MISSING_CONNECTION_NOTIFICATION_KEY ] = array(
860 - 'type' => 'user',
861 - 'is_error' => true,
862 - );
863 - return $red_bubble_slugs;
864 - }
1320 + /**
1321 + * Get list of module names sorted by their recommendation score
1322 + *
1323 + * @return array|null
1324 + */
1325 + public static function get_recommended_modules() {
1326 + $recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );
865 1327
866 - if ( ! empty( $broken_modules['needs_site_connection'] ) ) {
867 - $red_bubble_slugs[ self::MISSING_CONNECTION_NOTIFICATION_KEY ] = array(
868 - 'type' => 'site',
869 - 'is_error' => true,
870 - );
871 - return $red_bubble_slugs;
1328 + if ( empty( $recommendations_evaluation ) || ! is_array( $recommendations_evaluation ) ) {
1329 + return null;
872 1330 }
873 1331
874 - if ( ! $connection->is_user_connected() && ! $connection->has_connected_owner() ) {
875 - $red_bubble_slugs[ self::MISSING_CONNECTION_NOTIFICATION_KEY ] = array(
876 - 'type' => 'user',
877 - 'is_error' => false,
878 - );
879 - return $red_bubble_slugs;
880 - }
1332 + arsort( $recommendations_evaluation ); // Sort by scores in descending order
881 1333
882 - if ( ! $connection->is_connected() ) {
883 - $red_bubble_slugs[ self::MISSING_CONNECTION_NOTIFICATION_KEY ] = array(
884 - 'type' => 'site',
885 - 'is_error' => false,
886 - );
887 - return $red_bubble_slugs;
888 - }
889 -
890 - return $red_bubble_slugs;
1334 + return array_keys( $recommendations_evaluation ); // Get only module names
891 1335 }
892 1336 }