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
jetpack / jetpack_vendor / automattic / jetpack-my-jetpack / src / class-initializer.php

class-initializer.php in Jetpack – WP Security, Backup, Speed, & Growth 16.3-beta, at jetpack_vendor/automattic/jetpack-my-jetpack/src/class-initializer.php

1,337 lines 42.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WP Admin page with information and configuration shared among all Jetpack stand-alone plugins
4 *
5 * @package automattic/my-jetpack
6 */
7
8 namespace Automattic\Jetpack\My_Jetpack;
9
10 use Automattic\Jetpack\Admin_UI\Admin_Menu;
11 use Automattic\Jetpack\Assets;
12 use Automattic\Jetpack\Boost_Speed_Score\Speed_Score;
13 use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_History;
14 use Automattic\Jetpack\Connection\Client;
15 use Automattic\Jetpack\Connection\Error_Handler as Connection_Error_Handler;
16 use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
17 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
18 use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
19 use Automattic\Jetpack\Connection\REST_Jetpack_AI_JWT;
20 use Automattic\Jetpack\Constants as Jetpack_Constants;
21 use Automattic\Jetpack\ExPlat;
22 use Automattic\Jetpack\Feature_Flags\Feature_Flags;
23 use Automattic\Jetpack\JITMS\JITM;
24 use Automattic\Jetpack\Licensing;
25 use Automattic\Jetpack\Menu_Badges\Menu_Badges;
26 use Automattic\Jetpack\Menu_Badges\Notification_Counts;
27 use Automattic\Jetpack\Modules;
28 use Automattic\Jetpack\Partner_Coupon;
29 use Automattic\Jetpack\Plugins_Installer;
30 use Automattic\Jetpack\Status;
31 use Automattic\Jetpack\Status\Host as Status_Host;
32 use Automattic\Jetpack\Sync\Functions as Sync_Functions;
33 use Automattic\Jetpack\Terms_Of_Service;
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;
37 use Jetpack;
38 use WP_Error;
39
40 /**
41 * The main Initializer class that registers the admin menu and eneuque the assets.
42 */
43 class Initializer {
44
45 /**
46 * My Jetpack package version
47 *
48 * @var string
49 */
50 const PACKAGE_VERSION = '6.8.0';
51
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 /**
75 * HTML container ID for the IDC screen on My Jetpack page.
76 */
77 private const IDC_CONTAINER_ID = 'my-jetpack-identity-crisis-container';
78
79 public const JETPACK_PLUGIN_SLUGS = array(
80 'jetpack-backup',
81 'jetpack-boost',
82 'zerobscrm',
83 'jetpack',
84 'jetpack-protect',
85 'jetpack-social',
86 'jetpack-videopress',
87 'jetpack-search',
88 'jetpack-stats',
89 );
90
91 private const MY_JETPACK_SITE_INFO_TRANSIENT_KEY = 'my-jetpack-site-info';
92
93 /**
94 * Holds info/data about the site (from the /sites/%d endpoint)
95 *
96 * @var object
97 */
98 public static $site_info;
99
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 /**
108 * Initialize My Jetpack
109 *
110 * @return void
111 */
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
120 if ( ! self::should_initialize() || did_action( 'my_jetpack_init' ) ) {
121 return;
122 }
123
124 // Answer "is this product on?" for admin menu registration.
125 Menu_Visibility::init();
126
127 // Extend jetpack plugins action links.
128 Products::extend_plugins_action_links();
129
130 // Set up the REST authentication hooks.
131 Connection_Rest_Authentication::init();
132
133 if ( self::is_licensing_ui_enabled() ) {
134 Licensing::instance()->initialize();
135 }
136
137 // Initialize Boost Speed Score
138 new Speed_Score( array(), 'jetpack-my-jetpack' );
139
140 // Add custom WP REST API endoints.
141 add_action( 'rest_api_init', array( __CLASS__, 'register_rest_endpoints' ) );
142
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 );
147
148 add_action( 'admin_menu', array( __CLASS__, 'add_my_jetpack_menu_item' ) );
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
158 // Sets up JITMS.
159 JITM::configure();
160
161 // Add "Jetpack Manage" menu item.
162 Jetpack_Manage::init();
163
164 /**
165 * Fires after the My Jetpack package is initialized
166 *
167 * @since 0.1.0
168 */
169 do_action( 'my_jetpack_init' );
170 }
171
172 /**
173 * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
174 *
175 * @since 1.2.0
176 *
177 * @return boolean
178 */
179 public static function is_licensing_ui_enabled() {
180 // Default changed to true in 1.5.0.
181 $is_enabled = true;
182
183 /*
184 * Bail if My Jetpack is not enabled,
185 * and thus the licensing UI shouldn't be enabled either.
186 */
187 if ( ! self::should_initialize() ) {
188 $is_enabled = false;
189 }
190
191 /**
192 * Acts as a feature flag, returning a boolean for whether we should show the licensing UI.
193 *
194 * @param bool $is_enabled Defaults to true.
195 *
196 * @since 1.2.0
197 * @since 1.5.0 Update default value to true.
198 */
199 return apply_filters(
200 'jetpack_my_jetpack_should_enable_add_license_screen',
201 $is_enabled
202 );
203 }
204
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 /**
227 * Callback for the load my jetpack page hook.
228 *
229 * @return void
230 */
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
261 self::$site_info = self::get_site_info();
262 add_filter( 'identity_crisis_container_id', array( static::class, 'get_idc_container_id' ) );
263 add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
264 }
265
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 /**
355 * Returns whether we are in condition to track to use
356 * Analytics functionality like Tracks, MC, or GA.
357 */
358 public static function can_use_analytics() {
359 $status = new Status();
360 $connection = new Connection_Manager();
361 $tracking = new Tracking( 'jetpack', $connection );
362
363 return $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
364 }
365
366 /**
367 * Register the package's feature flags.
368 *
369 * @since 6.3.0
370 *
371 * @return void
372 */
373 public static function register_feature_flags() {
374 Feature_Flags::register(
375 self::FEATURES_TAB_FEATURE_FLAG,
376 array(
377 'default' => true,
378 'description' => 'Replace the My Jetpack Products tab with a Features tab.',
379 'owner' => 'my-jetpack',
380 )
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
629 $modules = new Modules();
630 $connection = new Connection_Manager();
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
648 wp_localize_script(
649 $data_handle,
650 'myJetpackInitialState',
651 array(
652 'products' => array(
653 'items' => Products::get_products(),
654 ),
655 'mainFeatures' => $features_tab_enabled ? Main_Features::get_state() : null,
656 'featuresBanner' => $features_tab_enabled ? array( 'isDismissed' => REST_Main_Features::is_banner_dismissed() ) : null,
657 'plugins' => Plugins_Installer::get_plugins(),
658 'themes' => Sync_Functions::get_themes(),
659 'myJetpackUrl' => admin_url( 'admin.php?page=my-jetpack' ),
660 'myJetpackCheckoutUri' => admin_url( 'admin.php?page=my-jetpack' ),
661 'topJetpackMenuItemUrl' => Admin_Menu::get_top_level_menu_item_url(),
662 'siteSuffix' => ( new Status() )->get_site_suffix(),
663 'siteUrl' => esc_url( get_site_url() ),
664 'blogID' => Connection_Manager::get_site_id( true ),
665 'myJetpackVersion' => self::PACKAGE_VERSION,
666 'myJetpackFlags' => self::get_my_jetpack_flags(),
667 'fileSystemWriteAccess' => self::has_file_system_write_access(),
668 'loadAddLicenseScreen' => self::is_licensing_ui_enabled(),
669 'adminUrl' => esc_url( admin_url() ),
670 'assetsUrl' => self::get_assets_url(),
671 'IDCContainerID' => static::get_idc_container_id(),
672 'userIsAdmin' => current_user_can( 'manage_options' ),
673 'lifecycleStats' => array(
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(),
680 ),
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 ),
686 'isStatsModuleActive' => $modules->is_active( 'stats' ),
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,
691 'isAtomic' => ( new Status_Host() )->is_woa_site(),
692 'isJetpackPluginActive' => class_exists( 'Jetpack' ),
693 'latestBoostSpeedScores' => $latest_score,
694 'seoOptIn' => self::get_seo_opt_in_state(),
695 'partnerCoupon' => self::get_partner_coupon_screen(),
696 )
697 );
698
699 wp_localize_script(
700 $data_handle,
701 'myJetpackRest',
702 array(
703 'apiRoot' => esc_url_raw( rest_url() ),
704 'apiNonce' => wp_create_nonce( 'wp_rest' ),
705 )
706 );
707
708 // Connection Initial State.
709 Connection_Initial_State::render_script( $data_handle );
710
711 // Required for Analytics.
712 if ( self::can_use_analytics() ) {
713 Tracking::register_tracks_functions_scripts( true );
714 }
715 }
716
717 /**
718 * Add My Jetpack data to the unified script data object.
719 *
720 * @param array $data The script data.
721 * @return array
722 */
723 public static function add_script_data( $data ) {
724 $block_availability = class_exists( '\Jetpack_Gutenberg' )
725 ? \Jetpack_Gutenberg::get_cached_availability()
726 : array();
727
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(),
735 );
736
737 return $data;
738 }
739
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 /**
788 * Get installed Jetpack plugins
789 *
790 * @return array
791 */
792 public static function get_installed_jetpack_plugins() {
793 $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
794 $plugin_slugs = array_map(
795 static function ( $slug ) {
796 $parts = explode( '/', $slug );
797 // Return the last segment of the filepath without the PHP extension
798 return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
799 },
800 $plugin_slugs
801 );
802
803 return array_values( array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs ) );
804 }
805
806 /**
807 * Get active modules (except ones enabled by default)
808 *
809 * @return array
810 */
811 public static function get_active_modules() {
812 $modules = new Modules();
813 $active_modules = $modules->get_active();
814
815 // if the Jetpack plugin is active, filter out the modules that are active by default
816 if ( class_exists( 'Jetpack' ) && ! empty( $active_modules ) ) {
817 $active_modules = array_diff( $active_modules, Jetpack::get_default_modules() );
818 }
819 return array_values( $active_modules );
820 }
821
822 /**
823 * Determine if the current user is "new" to Jetpack
824 * This is used to vary some messaging in My Jetpack
825 *
826 * On the front-end, purchases are also taken into account
827 *
828 * @return bool
829 */
830 public static function is_jetpack_user_new() {
831 // is the user connected?
832 $connection = new Connection_Manager();
833 if ( $connection->is_user_connected() ) {
834 return false;
835 }
836
837 // TODO: add a data point for the last known connection/ disconnection time
838
839 // are any modules active?
840 $active_modules = self::get_active_modules();
841 if ( ! empty( $active_modules ) ) {
842 return false;
843 }
844
845 // check for other Jetpack plugins that are installed on the site (active or not)
846 // If there's more than one Jetpack plugin active, this user is not "new"
847 $plugin_slugs = array_keys( Plugins_Installer::get_plugins() );
848 $plugin_slugs = array_map(
849 static function ( $slug ) {
850 $parts = explode( '/', $slug );
851 // Return the last segment of the filepath without the PHP extension
852 return str_replace( '.php', '', $parts[ count( $parts ) - 1 ] );
853 },
854 $plugin_slugs
855 );
856 $installed_jetpack_plugins = array_intersect( self::JETPACK_PLUGIN_SLUGS, $plugin_slugs );
857 if ( is_countable( $installed_jetpack_plugins ) && count( $installed_jetpack_plugins ) >= 2 ) {
858 return false;
859 }
860
861 // Does the site have any purchases?
862 $purchases = Wpcom_Products::get_site_current_purchases();
863 if ( ! empty( $purchases ) && ! is_wp_error( $purchases ) ) {
864 return false;
865 }
866
867 return true;
868 }
869
870 /**
871 * Build flags for My Jetpack UI
872 *
873 * @return array
874 */
875 public static function get_my_jetpack_flags() {
876 $flags = array(
877 'videoPressStats' => Jetpack_Constants::is_true( 'JETPACK_MY_JETPACK_VIDEOPRESS_STATS_ENABLED' ),
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(),
883 );
884
885 return $flags;
886 }
887
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 /**
928 * Echoes the admin page content.
929 *
930 * @return void
931 */
932 public static function admin_page() {
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 }
944 }
945
946 /**
947 * Register the REST API routes.
948 *
949 * @return void
950 */
951 public static function register_rest_endpoints() {
952 new REST_Products();
953 new REST_Purchases();
954 ( new REST_Jetpack_AI_JWT() )->register_rest_route();
955 new REST_Recommendations_Evaluation();
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
966 register_rest_route(
967 'my-jetpack/v1',
968 'site',
969 array(
970 'methods' => \WP_REST_Server::READABLE,
971 'callback' => __CLASS__ . '::get_site',
972 'permission_callback' => __CLASS__ . '::permissions_callback',
973 )
974 );
975
976 register_rest_route(
977 'my-jetpack/v1',
978 'site/dismiss-welcome-banner',
979 array(
980 'methods' => \WP_REST_Server::EDITABLE,
981 'callback' => __CLASS__ . '::dismiss_welcome_banner',
982 'permission_callback' => __CLASS__ . '::permissions_callback',
983 )
984 );
985 }
986
987 /**
988 * Check user capability to access the endpoint.
989 *
990 * @access public
991 * @static
992 *
993 * @return true|WP_Error
994 */
995 public static function permissions_callback() {
996 return current_user_can( 'manage_options' );
997 }
998
999 /**
1000 * Return true if we should initialize the My Jetpack admin page.
1001 */
1002 public static function should_initialize() {
1003 $should = true;
1004
1005 // All options presented in My Jetpack require a connection to WordPress.com.
1006 if ( ( new Status() )->is_offline_mode() ) {
1007 $should = false;
1008 }
1009
1010 /**
1011 * Allows filtering whether My Jetpack should be initialized.
1012 *
1013 * @since 0.5.0-alpha
1014 *
1015 * @param bool $shoud_initialize Should we initialize My Jetpack?
1016 */
1017 return apply_filters( 'jetpack_my_jetpack_should_initialize', $should );
1018 }
1019
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 /**
1049 * Site full-data endpoint.
1050 *
1051 * @return object Site data.
1052 */
1053 public static function get_site() {
1054 $site_id = \Jetpack_Options::get_option( 'id' );
1055 $wpcom_endpoint = sprintf( '/sites/%d?force=wpcom', $site_id );
1056 $wpcom_api_version = '1.1';
1057 $response = Client::wpcom_json_api_request_as_blog( $wpcom_endpoint, $wpcom_api_version );
1058 $response_code = wp_remote_retrieve_response_code( $response );
1059 $body = json_decode( wp_remote_retrieve_body( $response ) );
1060
1061 if ( is_wp_error( $response ) || empty( $response['body'] ) ) {
1062 return new WP_Error( 'site_data_fetch_failed', 'Site data fetch failed', array( 'status' => $response_code ) );
1063 }
1064
1065 return rest_ensure_response( $body );
1066 }
1067
1068 /**
1069 * Populates the self::$site_info var with site data from the /sites/%d endpoint
1070 *
1071 * @return object|WP_Error
1072 */
1073 public static function get_site_info() {
1074 static $site_info = null;
1075
1076 if ( $site_info !== null ) {
1077 return $site_info;
1078 }
1079
1080 // Check for a cached value before doing lookup
1081 $stored_site_info = get_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY );
1082 if ( $stored_site_info !== false ) {
1083 return $stored_site_info;
1084 }
1085
1086 $response = self::get_site();
1087 if ( is_wp_error( $response ) ) {
1088 return $response;
1089 }
1090 $site_info = $response->data;
1091 set_transient( self::MY_JETPACK_SITE_INFO_TRANSIENT_KEY, $site_info, DAY_IN_SECONDS );
1092
1093 return $site_info;
1094 }
1095
1096 /**
1097 * Returns whether a site has been determined "commercial" or not.
1098 *
1099 * @return bool|null
1100 */
1101 public static function is_commercial_site() {
1102 if ( is_wp_error( self::$site_info ) ) {
1103 return null;
1104 }
1105
1106 return empty( self::$site_info->options->is_commercial ) ? false : self::$site_info->options->is_commercial;
1107 }
1108
1109 /**
1110 * Check if site is registered (has been connected before).
1111 *
1112 * @return bool
1113 */
1114 public static function is_registered() {
1115 return (bool) \Jetpack_Options::get_option( 'id' );
1116 }
1117
1118 /**
1119 * Dismiss the welcome banner.
1120 *
1121 * @return \WP_REST_Response
1122 */
1123 public static function dismiss_welcome_banner() {
1124 \Jetpack_Options::update_option( 'dismissed_welcome_banner', true );
1125 return rest_ensure_response( array( 'success' => true ) );
1126 }
1127
1128 /**
1129 * Returns "yes" if the site has file write access to the plugins folder, "no" otherwise.
1130 *
1131 * @return string
1132 **/
1133 public static function has_file_system_write_access() {
1134
1135 $cache = get_transient( 'my_jetpack_write_access' );
1136
1137 if ( false !== $cache ) {
1138 return $cache;
1139 }
1140
1141 if ( ! function_exists( 'get_filesystem_method' ) ) {
1142 require_once ABSPATH . 'wp-admin/includes/file.php';
1143 }
1144
1145 require_once ABSPATH . 'wp-admin/includes/template.php';
1146
1147 $write_access = 'no';
1148
1149 $filesystem_method = get_filesystem_method( array(), WP_PLUGIN_DIR );
1150 if ( 'direct' === $filesystem_method ) {
1151 $write_access = 'yes';
1152 }
1153
1154 if ( 'no' === $write_access ) {
1155 ob_start();
1156 $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1157 ob_end_clean();
1158
1159 if ( $filesystem_credentials_are_stored ) {
1160 $write_access = 'yes';
1161 }
1162 }
1163
1164 set_transient( 'my_jetpack_write_access', $write_access, 30 * MINUTE_IN_SECONDS );
1165
1166 return $write_access;
1167 }
1168
1169 /**
1170 * Get container IDC for the IDC screen.
1171 *
1172 * @return string
1173 */
1174 public static function get_idc_container_id() {
1175 return static::IDC_CONTAINER_ID;
1176 }
1177
1178 /**
1179 * Conditionally append the red bubble notification to the "Jetpack" menu item if there are alerts to show.
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 *
1184 * @return void
1185 */
1186 public static function maybe_show_red_bubble() {
1187 global $pagenow;
1188
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;
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 }
1282 }
1283
1284 /**
1285 * Whether the Connection Error Handler reports a displayable connection error
1286 * for the current viewer.
1287 *
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
1294 */
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;
1298 }
1299 return ! empty( Connection_Error_Handler::get_instance()->get_displayable_errors() );
1300 }
1301
1302 /**
1303 * Enqueue the notification bubble script.
1304 * Fetches fresh alert data via REST API without blocking page load.
1305 *
1306 * @return void
1307 */
1308 public static function enqueue_red_bubble_script() {
1309 Assets::register_script(
1310 'my-jetpack-notification-bubble',
1311 '../build/async-notification-bubble.js',
1312 __FILE__,
1313 array(
1314 'enqueue' => true,
1315 'in_footer' => true,
1316 )
1317 );
1318 }
1319
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 );
1327
1328 if ( empty( $recommendations_evaluation ) || ! is_array( $recommendations_evaluation ) ) {
1329 return null;
1330 }
1331
1332 arsort( $recommendations_evaluation ); // Sort by scores in descending order
1333
1334 return array_keys( $recommendations_evaluation ); // Get only module names
1335 }
1336 }
1337