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 +806 -150 13.3.3 → 16.3-beta View file →
@@ -11,21 +11,32 @@
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;
38 +use WP_Error;
28 39
29 40 /**
30 41 * The main Initializer class that registers the admin menu and eneuque the assets.
31 42 */
@@ -35,16 +46,38 @@
35 46 * My Jetpack package version
36 47 *
37 48 * @var string
38 49 */
39 - const PACKAGE_VERSION = '4.20.1.1';
50 + const PACKAGE_VERSION = '6.8.0';
40 51
41 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 + /**
42 75 * HTML container ID for the IDC screen on My Jetpack page.
43 76 */
44 - const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
77 + private const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
45 78
46 - const JETPACK_PLUGIN_SLUGS = array(
79 + public const JETPACK_PLUGIN_SLUGS = array(
47 80 'jetpack-backup',
48 81 'jetpack-boost',
49 82 'zerobscrm',
50 83 'jetpack',
@@ -51,31 +84,47 @@
51 84 'jetpack-protect',
52 85 'jetpack-social',
53 86 'jetpack-videopress',
54 87 'jetpack-search',
88 + 'jetpack-stats',
55 89 );
56 90
57 - const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
91 + private const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
58 92
59 - const MISSING_SITE_CONNECTION_NOTIFICATION_KEY = 'missing-site-connection';
60 -
61 93 /**
62 94 * Holds info/data about the site (from the /sites/%d endpoint)
63 95 *
64 - * @var stdClass Object
96 + * @var object
65 97 */
66 98 public static $site_info;
67 99
68 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 + /**
69 108 * Initialize My Jetpack
70 109 *
71 110 * @return void
72 111 */
73 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 +
74 120 if ( ! self::should_initialize() || did_action( 'my_jetpack_init' ) ) {
75 121 return;
76 122 }
77 123
124 + // Answer "is this product on?" for admin menu registration.
125 + Menu_Visibility::init();
126 +
78 127 // Extend jetpack plugins action links.
79 128 Products::extend_plugins_action_links();
80 129
81 130 // Set up the REST authentication hooks.
@@ -90,27 +139,26 @@
90 139
91 140 // Add custom WP REST API endoints.
92 141 add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );
93 142
94 - $page_suffix = Admin_Menu::add_menu(
95 - __( 'My Jetpack', 'jetpack-my-jetpack' ),
96 - __( 'My Jetpack', 'jetpack-my-jetpack' ),
97 - 'edit_posts',
98 - 'my-jetpack',
99 - array( __CLASS__, 'admin_page' ),
100 - -1
101 - );
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 );
102 147
103 - add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
104 - // This is later than the admin-ui package, which runs on 1000
105 - add_action( 'admin_init', array( __CLASS__, 'maybe_show_red_bubble' ), 1001 );
148 + add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );
106 149
150 + add_action( 'admin_init', array( __CLASS__, 'setup_historically_active_jetpack_modules_sync' ) );
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 );
154 +
155 + // Set up the ExPlat package endpoints
156 + ExPlat::init();
157 +
107 158 // Sets up JITMS.
108 159 JITM::configure();
109 160
110 - // Add "Activity Log" menu item.
111 - Activitylog::init();
112 -
113 161 // Add "Jetpack Manage" menu item.
114 162 Jetpack_Manage::init();
115 163
116 164 /**
@@ -154,23 +202,157 @@
154 202 );
155 203 }
156 204
157 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 + /**
158 227 * Callback for the load my jetpack page hook.
159 228 *
160 229 * @return void
161 230 */
162 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 +
163 261 self::$site_info = self::get_site_info();
164 262 add_filter( 'identity_crisis_container_id', array( static::class, 'get_idc_container_id' ) );
165 263 add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
166 - // Product statuses are constantly changing, so we never want to cache the page.
167 - header( 'Cache-Control: no-cache, no-store, must-revalidate' );
168 - header( 'Pragma: no-cache' );
169 - header( 'Expires: 0' );
170 264 }
171 265
172 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 + /**
173 355 * Returns whether we are in condition to track to use
174 356 * Analytics functionality like Tracks, MC, or GA.
175 357 */
176 358 public static function can_use_analytics() {
@@ -179,42 +361,307 @@
179 361 $tracking = new Tracking( 'jetpack', $connection );
180 362
181 363 return $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
182 364 }
365 +
183 366 /**
184 - * Enqueue admin page assets.
367 + * Register the package's feature flags.
185 368 *
369 + * @since 6.3.0
370 + *
186 371 * @return void
187 372 */
188 - public static function enqueue_scripts() {
189 - Assets::register_script(
190 - 'my_jetpack_main_app',
191 - '../build/index.js',
192 - __FILE__,
373 + public static function register_feature_flags() {
374 + Feature_Flags::register(
375 + self::FEATURES_TAB_FEATURE_FLAG,
193 376 array(
194 - 'enqueue' => true,
195 - 'in_footer' => true,
196 - 'textdomain' => 'jetpack-my-jetpack',
377 + 'default' => true,
378 + 'description' => 'Replace the My Jetpack Products tab with a Features tab.',
379 + 'owner' => 'my-jetpack',
197 380 )
198 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 +
199 629 $modules = new Modules();
200 630 $connection = new Connection_Manager();
201 - $speed_score_history = new Speed_Score_History( wp_parse_url( get_site_url(), PHP_URL_HOST ) );
631 + $speed_score_history = new Speed_Score_History( get_site_url() );
632 + $latest_score = $speed_score_history->latest();
633 + $previous_score = array();
634 + if ( $speed_score_history->count() > 1 ) {
635 + $previous_score = $speed_score_history->latest( 1 );
636 + }
637 + $latest_score['previousScores'] = $previous_score['scores'] ?? array();
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 +
202 648 wp_localize_script(
203 - 'my_jetpack_main_app',
649 + $data_handle,
204 650 'myJetpackInitialState',
205 651 array(
206 652 'products' => array(
207 653 'items' => Products::get_products(),
208 654 ),
209 - 'purchases' => array(
210 - 'items' => array(),
211 - ),
655 + 'mainFeatures' => $features_tab_enabled ? Main_Features::get_state() : null,
656 + 'featuresBanner' => $features_tab_enabled ? array( 'isDismissed' => REST_Main_Features::is_banner_dismissed() ) : null,
212 657 'plugins' => Plugins_Installer::get_plugins(),
658 + 'themes' => Sync_Functions::get_themes(),
213 659 'myJetpackUrl' => admin_url( 'admin.php?page=my-jetpack' ),
214 660 'myJetpackCheckoutUri' => admin_url( 'admin.php?page=my-jetpack' ),
215 661 'topJetpackMenuItemUrl' => Admin_Menu::get_top_level_menu_item_url(),
216 662 'siteSuffix' => ( new Status() )->get_site_suffix(),
663 + 'siteUrl' => esc_url( get_site_url() ),
217 664 'blogID' => Connection_Manager::get_site_id( true ),
218 665 'myJetpackVersion' => self::PACKAGE_VERSION,
219 666 'myJetpackFlags' => self::get_my_jetpack_flags(),
220 667 'fileSystemWriteAccess' => self::has_file_system_write_access(),
@@ -219,33 +666,39 @@
219 666 'myJetpackFlags' => self::get_my_jetpack_flags(),
220 667 'fileSystemWriteAccess' => self::has_file_system_write_access(),
221 668 'loadAddLicenseScreen' => self::is_licensing_ui_enabled(),
222 669 'adminUrl' => esc_url( admin_url() ),
670 + 'assetsUrl' => self::get_assets_url(),
223 671 'IDCContainerID' => static::get_idc_container_id(),
224 672 'userIsAdmin' => current_user_can( 'manage_options' ),
225 - 'userIsNewToJetpack' => self::is_jetpack_user_new(),
226 673 'lifecycleStats' => array(
227 - 'jetpackPlugins' => self::get_installed_jetpack_plugins(),
228 - 'isSiteConnected' => $connection->is_connected(),
229 - 'isUserConnected' => $connection->is_user_connected(),
230 - 'purchases' => self::get_purchases(),
231 - 'modules' => self::get_active_modules(),
674 + 'jetpackPlugins' => self::get_installed_jetpack_plugins(),
675 + 'historicallyActiveModules' => \Jetpack_Options::get_option( 'historically_active_modules', array() ),
676 + 'brokenModules' => Red_Bubble_Notifications::check_for_broken_modules(),
677 + 'isSiteConnected' => $connection->is_connected(),
678 + 'isUserConnected' => $connection->is_user_connected(),
679 + 'modules' => self::get_active_modules(),
232 680 ),
233 - '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 + ),
234 686 'isStatsModuleActive' => $modules->is_active( 'stats' ),
235 - 'isUserFromKnownHost' => self::is_user_from_known_host(),
236 - '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,
237 691 'isAtomic' => ( new Status_Host() )->is_woa_site(),
238 - 'jetpackManage' => array(
239 - 'isEnabled' => Jetpack_Manage::could_use_jp_manage(),
240 - 'isAgencyAccount' => Jetpack_Manage::is_agency_account(),
241 - ),
242 - 'latestBoostSpeedScores' => $speed_score_history->latest(),
692 + 'isJetpackPluginActive' => class_exists( 'Jetpack' ),
693 + 'latestBoostSpeedScores' => $latest_score,
694 + 'seoOptIn' => self::get_seo_opt_in_state(),
695 + 'partnerCoupon' => self::get_partner_coupon_screen(),
243 696 )
244 697 );
245 698
246 699 wp_localize_script(
247 - 'my_jetpack_main_app',
700 + $data_handle,
248 701 'myJetpackRest',
249 702 array(
250 703 'apiRoot' => esc_url_raw( rest_url() ),
251 704 'apiNonce' => wp_create_nonce( 'wp_rest' ),
@@ -252,9 +705,9 @@
252 705 )
253 706 );
254 707
255 708 // Connection Initial State.
256 - Connection_Initial_State::render_script( 'my_jetpack_main_app' );
709 + Connection_Initial_State::render_script( $data_handle );
257 710
258 711 // Required for Analytics.
259 712 if ( self::can_use_analytics() ) {
260 713 Tracking::register_tracks_functions_scripts( true );
@@ -261,27 +714,78 @@
261 714 }
262 715 }
263 716
264 717 /**
265 - * Get product slugs of the active purchases
718 + * Add My Jetpack data to the unified script data object.
266 719 *
720 + * @param array $data The script data.
267 721 * @return array
268 722 */
269 - public static function get_purchases() {
270 - $purchases = Wpcom_Products::get_site_current_purchases();
271 - if ( is_wp_error( $purchases ) ) {
272 - return array();
273 - }
723 + public static function add_script_data( $data ) {
724 + $block_availability = class_exists( '\Jetpack_Gutenberg' )
725 + ? \Jetpack_Gutenberg::get_cached_availability()
726 + : array();
274 727
275 - return array_map(
276 - function ( $purchase ) {
277 - return $purchase->product_slug;
278 - },
279 - $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(),
280 735 );
736 +
737 + return $data;
281 738 }
282 739
283 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 + /**
284 788 * Get installed Jetpack plugins
285 789 *
286 790 * @return array
287 791 */
@@ -289,11 +793,8 @@
289 793 $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
290 794 $plugin_slugs = array_map(
291 795 static function ( $slug ) {
292 796 $parts = explode( '/', $slug );
293 - if ( empty( $parts ) ) {
294 - return '';
295 - }
296 797 // Return the last segment of the filepath without the PHP extension
297 798 return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
298 799 },
299 800 $plugin_slugs
@@ -314,9 +815,9 @@
314 815 // if the Jetpack plugin is active, filter out the modules that are active by default
315 816 if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
316 817 $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
317 818 }
318 - return $active_modules;
819 + return array_values( $active_modules );
319 820 }
320 821
321 822 /**
322 823 * Determine if the current user is "new" to Jetpack
@@ -335,14 +836,9 @@
335 836
336 837 // TODO: add a data point for the last known connection/ disconnection time
337 838
338 839 // are any modules active?
339 - $modules = new Modules();
340 - $active_modules = $modules->get_active();
341 - // if the Jetpack plugin is active, filter out the modules that are active by default
342 - if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
343 - $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
344 - }
840 + $active_modules = self::get_active_modules();
345 841 if ( ! empty( $active_modules ) ) {
346 842 return false;
347 843 }
348 844
@@ -351,11 +847,8 @@
351 847 $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
352 848 $plugin_slugs = array_map(
353 849 static function ( $slug ) {
354 850 $parts = explode( '/', $slug );
355 - if ( empty( $parts ) ) {
356 - return '';
357 - }
358 851 // Return the last segment of the filepath without the PHP extension
359 852 return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
360 853 },
361 854 $plugin_slugs
@@ -374,18 +867,8 @@
374 867 return true;
375 868 }
376 869
377 870 /**
378 - * Determines whether the user has come from a host we can recognize.
379 - *
380 - * @return string
381 - */
382 - public static function is_user_from_known_host() {
383 - // Known (external) host is the one that has been determined and is not dotcom.
384 - return ! in_array( ( new Status_Host() )->get_known_host_guess(), array( 'unknown', 'wpcom' ), true );
385 - }
386 -
387 - /**
388 871 * Build flags for My Jetpack UI
389 872 *
390 873 * @return array
391 874 */
@@ -391,9 +874,13 @@
391 874 */
392 875 public static function get_my_jetpack_flags() {
393 876 $flags = array(
394 877 'videoPressStats' => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
395 - '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(),
396 883 );
397 884
398 885 return $flags;
399 886 }
@@ -398,14 +885,63 @@
398 885 return $flags;
399 886 }
400 887
401 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 + /**
402 928 * Echoes the admin page content.
403 929 *
404 930 * @return void
405 931 */
406 932 public static function admin_page() {
407 - 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 + }
408 944 }
409 945
410 946 /**
411 947 * Register the REST API routes.
@@ -414,12 +950,20 @@
414 950 */
415 951 public static function register_rest_endpoints() {
416 952 new REST_Products();
417 953 new REST_Purchases();
418 - new REST_Zendesk_Chat();
419 - new REST_Product_Data();
420 - new REST_AI();
954 + ( new REST_Jetpack_AI_JWT() )->register_rest_route();
955 + new REST_Recommendations_Evaluation();
421 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 +
422 966 register_rest_route(
423 967 'my-jetpack/v1',
424 968 'site',
425 969 array(
@@ -457,12 +1001,8 @@
457 1001 */
458 1002 public static function should_initialize() {
459 1003 $should = true;
460 1004
461 - if ( is_multisite() ) {
462 - $should = false;
463 - }
464 -
465 1005 // All options presented in My Jetpack require a connection to WordPress.com.
466 1006 if ( ( new Status() )->is_offline_mode() ) {
467 1007 $should = false;
468 1008 }
@@ -477,8 +1017,36 @@
477 1017 return apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
478 1018 }
479 1019
480 1020 /**
1021 + * Hook into several connection-based actions to update the historically active Jetpack modules
1022 + * If the transient that indicates the list needs to be synced, update it and delete the transient
1023 + *
1024 + * @return void
1025 + */
1026 + public static function setup_historically_active_jetpack_modules_sync() {
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 );
1032 + }
1033 +
1034 + $actions = array(
1035 + 'jetpack_site_registered',
1036 + 'jetpack_user_authorized',
1037 + 'activated_plugin',
1038 + );
1039 +
1040 + foreach ( $actions as $action ) {
1041 + add_action( $action, array( $ham, 'queue_historically_active_jetpack_modules_update' ), 5 );
1042 + }
1043 +
1044 + // Modules are often updated async, so we need to update them right away as there will sometimes be no page reload.
1045 + add_action( 'jetpack_activate_module', array( $ham, 'update_historically_active_jetpack_modules' ), 5 );
1046 + }
1047 +
1048 + /**
481 1049 * Site full-data endpoint.
482 1050 *
483 1051 * @return object Site data.
484 1052 */
@@ -490,18 +1058,18 @@
490 1058 $response_code = wp_remote_retrieve_response_code( $response );
491 1059 $body = json_decode( wp_remote_retrieve_body( $response ) );
492 1060
493 1061 if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
494 - return new \WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
1062 + return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
495 1063 }
496 1064
497 - return rest_ensure_response( $body, 200 );
1065 + return rest_ensure_response( $body );
498 1066 }
499 1067
500 1068 /**
501 1069 * Populates the self::$site_info var with site data from the /sites/%d endpoint
502 1070 *
503 - * @return Object|WP_Error
1071 + * @return object|WP_Error
504 1072 */
505 1073 public static function get_site_info() {
506 1074 static $site_info = null;
507 1075
@@ -527,9 +1095,9 @@
527 1095
528 1096 /**
529 1097 * Returns whether a site has been determined "commercial" or not.
530 1098 *
531 - * @return bool
1099 + * @return bool|null
532 1100 */
533 1101 public static function is_commercial_site() {
534 1102 if ( is_wp_error( self::$site_info ) ) {
535 1103 return null;
@@ -553,15 +1121,15 @@
553 1121 * @return \WP_REST_Response
554 1122 */
555 1123 public static function dismiss_welcome_banner() {
556 1124 \Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
557 - return rest_ensure_response( array( 'success' => true ), 200 );
1125 + return rest_ensure_response( array( 'success' => true ) );
558 1126 }
559 1127
560 1128 /**
561 - * 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.
562 1130 *
563 - * @return bool
1131 + * @return string
564 1132 **/
565 1133 public static function has_file_system_write_access() {
566 1134
567 1135 $cache = get_transient( 'my_jetpack_write_access' );
@@ -582,9 +1150,9 @@
582 1150 if ( 'direct' === $filesystem_method ) {
583 1151 $write_access = 'yes';
584 1152 }
585 1153
586 - if ( ! $write_access ) {
1154 + if ( 'no' === $write_access ) {
587 1155 ob_start();
588 1156 $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
589 1157 ob_end_clean();
590 1158
@@ -607,74 +1175,162 @@
607 1175 return static::IDC_CONTAINER_ID;
608 1176 }
609 1177
610 1178 /**
611 - * 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.
612 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 + *
613 1184 * @return void
614 1185 */
615 1186 public static function maybe_show_red_bubble() {
616 - global $menu;
617 - // filters for the items in this file
618 - add_filter( 'my_jetpack_red_bubble_notification_slugs', array( __CLASS__, 'add_red_bubble_alerts' ) );
619 - $red_bubble_alerts = self::get_red_bubble_alerts();
1187 + global $pagenow;
620 1188
621 - // The Jetpack menu item should be on index 3
622 - if (
623 - ! empty( $red_bubble_alerts ) &&
624 - is_countable( $red_bubble_alerts ) &&
625 - isset( $menu[3] ) &&
626 - $menu[3][0] === 'Jetpack'
627 - ) {
628 - // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
629 - $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;
630 1193 }
1194 +
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 + }
1201 +
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;
1233 + }
1234 +
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 + );
1242 +
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.
1246 +
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 + );
1259 + }
1260 +
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() ) {
1267 + continue;
1268 + }
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;
1273 + }
1274 + Notification_Counts::register(
1275 + 'my-jetpack-' . $slug,
1276 + array(
1277 + 'menu_slug' => 'my-jetpack',
1278 + 'type' => 'attention',
1279 + )
1280 + );
1281 + }
631 1282 }
632 1283
633 1284 /**
634 - * Collect all possible alerts that we might use a red bubble notification for
1285 + * Whether the Connection Error Handler reports a displayable connection error
1286 + * for the current viewer.
635 1287 *
636 - * @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
637 1294 */
638 - public static function get_red_bubble_alerts() {
639 - static $red_bubble_alerts = array();
640 -
641 - // using a static cache since we call this function more than once in the class
642 - if ( ! empty( $red_bubble_alerts ) ) {
643 - return $red_bubble_alerts;
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;
644 1298 }
645 - // go find the alerts
646 - $red_bubble_alerts = apply_filters( 'my_jetpack_red_bubble_notification_slugs', $red_bubble_alerts );
647 -
648 - return $red_bubble_alerts;
1299 + return ! empty( Connection_Error_Handler::get_instance()->get_displayable_errors() );
649 1300 }
650 1301
651 1302 /**
652 - * Add relevant red bubble notifications
1303 + * Enqueue the notification bubble script.
1304 + * Fetches fresh alert data via REST API without blocking page load.
653 1305 *
654 - * @param array $red_bubble_slugs - slugs that describe the reasons the red bubble is showing.
655 - * @return array
1306 + * @return void
656 1307 */
657 - public static function add_red_bubble_alerts( array $red_bubble_slugs ) {
658 - $welcome_banner_dismissed = \Jetpack_Options::get_option( 'dismissed_welcome_banner', false );
659 - if ( self::is_jetpack_user_new() && ! $welcome_banner_dismissed ) {
660 - $red_bubble_slugs['welcome-banner-active'] = null;
661 - return $red_bubble_slugs;
662 - } else {
663 - return self::alert_if_missing_site_connection( $red_bubble_slugs );
664 - }
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 + );
665 1318 }
666 1319
667 1320 /**
668 - * Add an alert slug if the site is missing a site connection
1321 + * Get list of module names sorted by their recommendation score
669 1322 *
670 - * @param array $red_bubble_slugs - slugs that describe the reasons the red bubble is showing.
671 - * @return array
1323 + * @return array|null
672 1324 */
673 - public static function alert_if_missing_site_connection( array $red_bubble_slugs ) {
674 - if ( ! ( new Connection_Manager() )->is_connected() ) {
675 - $red_bubble_slugs[ self::MISSING_SITE_CONNECTION_NOTIFICATION_KEY ] = null;
1325 + public static function get_recommended_modules() {
1326 + $recommendations_evaluation = \Jetpack_Options::get_option( 'recommendations_evaluation', null );
1327 +
1328 + if ( empty( $recommendations_evaluation ) || ! is_array( $recommendations_evaluation ) ) {
1329 + return null;
676 1330 }
677 1331
678 - return $red_bubble_slugs;
1332 + arsort( $recommendations_evaluation ); // Sort by scores in descending order
1333 +
1334 + return array_keys( $recommendations_evaluation ); // Get only module names
679 1335 }
680 1336 }