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-backup/src/class-jetpack-backup.php +642 -82 13.6.2 → 16.3-beta View file →
@@ -8,22 +8,24 @@
8 8 // After changing this file, consider increasing the version number ("VXXX") in all the files using this namespace, in
9 9 // order to ensure that the specific version of this file always get loaded. Otherwise, Jetpack autoloader might decide
10 10 // to load an older/newer version of the class (if, for example, both the standalone and bundled versions of the plugin
11 11 // are installed, or in some other cases).
12 -namespace Automattic\Jetpack\Backup\V0004;
12 +namespace Automattic\Jetpack\Backup\V0005;
13 13
14 14 if ( ! defined( 'ABSPATH' ) ) {
15 - exit;
15 + exit( 0 );
16 16 }
17 17
18 18 use Automattic\Jetpack\Admin_UI\Admin_Menu;
19 19 use Automattic\Jetpack\Assets;
20 -use Automattic\Jetpack\Backup\V0004\Initial_State as Backup_Initial_State;
20 +use Automattic\Jetpack\Backup\V0005\Initial_State as Backup_Initial_State;
21 21 use Automattic\Jetpack\Config;
22 22 use Automattic\Jetpack\Connection\Client;
23 23 use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
24 24 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
25 25 use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
26 +use Automattic\Jetpack\Constants;
27 +use Automattic\Jetpack\JITMS\JITM;
26 28 use Automattic\Jetpack\My_Jetpack\Wpcom_Products;
27 29 use Automattic\Jetpack\Status;
28 30 use Automattic\Jetpack\Terms_Of_Service;
29 31 use Automattic\Jetpack\Tracking;
@@ -29,12 +31,8 @@
29 31 use Automattic\Jetpack\Tracking;
30 32 use Jetpack_Options;
31 33 use WP_Error;
32 34 use WP_REST_Server;
33 -// phpcs:ignore WordPress.Utils.I18nTextDomainFixer.MissingArgs
34 -use function __;
35 -// phpcs:ignore WordPress.Utils.I18nTextDomainFixer.MissingArgs
36 -use function _x;
37 35 use function add_action;
38 36 use function add_filter;
39 37 use function did_action;
40 38 use function do_action;
@@ -81,8 +79,28 @@
81 79 */
82 80 const JETPACK_BACKUP_PROMOTED_PRODUCT = 'jetpack_backup_t1_yearly';
83 81
84 82 /**
83 + * Transient key prefix for the cached promoted product.
84 + *
85 + * Suffixed with the locale: it is a query arg on the catalogue request, so
86 + * one shared key would serve one reader's language to another.
87 + *
88 + * @var string
89 + */
90 + const PROMOTED_PRODUCT_TRANSIENT_PREFIX = 'jetpack_backup_promoted_product_';
91 +
92 + /**
93 + * How long a fetched promoted product stays cached.
94 + *
95 + * The catalogue turns over on a marketing schedule rather than a
96 + * session's, so half a day bounds how stale a price can get.
97 + *
98 + * @var int
99 + */
100 + const PROMOTED_PRODUCT_CACHE_TTL = 12 * HOUR_IN_SECONDS;
101 +
102 + /**
85 103 * Licenses product ID.
86 104 *
87 105 * @var string
88 106 */
@@ -106,29 +124,91 @@
106 124 */
107 125 const JETPACK_BACKUP_DB_VERSION = '2';
108 126
109 127 /**
128 + * Filter name that gates the wp-build–based dashboard.
129 + *
130 + * When this filter returns true, "Jetpack > Backup" renders the new
131 + * wp-build dashboard instead of the legacy React app.
132 + */
133 + const MODERNIZATION_FILTER = 'rsm_jetpack_ui_modernization_backup';
134 +
135 + /**
136 + * Blog sticker that takes a site out of the internal preview.
137 + *
138 + * Atomic sees it only if it is on WordPress.com's `atomic_site_stickers()` allowlist.
139 + */
140 + const LEGACY_DASHBOARD_STICKER = 'use-backup-legacy-dashboard';
141 +
142 + /**
143 + * Rewind state read from WordPress.com, memoized for the request.
144 + *
145 + * A class property and not a function static so tests can clear it.
146 + *
147 + * @var object|null
148 + */
149 + private static $rewind_state = null;
150 +
151 + /**
152 + * The screen ID alias_screen_id_for_wp_build() replaced, until it is restored.
153 + *
154 + * @var string|null
155 + */
156 + private static $wp_build_original_screen_id = null;
157 +
158 + /**
159 + * Initialization options.
160 + *
161 + * @var array
162 + */
163 + const DEFAULT_INIT_OPTIONS = array(
164 + // A host that already ensured a connection under its own slug must not have it
165 + // re-ensured here as `jetpack-backup`, which would rename the site's connection.
166 + 'manage_connection' => true,
167 + );
168 +
169 + /**
110 170 * Constructor.
171 + *
172 + * @param array $options Overrides for self::DEFAULT_INIT_OPTIONS.
111 173 */
112 - public static function initialize() {
174 + public static function initialize( array $options = array() ) {
113 175 if ( did_action( 'jetpack_backup_initialized' ) ) {
114 176 return;
115 177 }
116 178
117 - // Set up the REST authentication hooks.
118 - Connection_Rest_Authentication::init();
179 + $options = array_merge( self::DEFAULT_INIT_OPTIONS, $options );
119 180
120 181 add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
182 + add_action( 'rest_api_init', array( \Automattic\Jetpack\Backup\V0005\REST\Rest_Controller::class, 'register_routes' ) );
121 183
122 - $page_suffix = Admin_Menu::add_menu(
123 - __( 'Jetpack VaultPress Backup', 'jetpack-backup-pkg' ),
124 - _x( 'VaultPress Backup', 'The Jetpack VaultPress Backup product name, without the Jetpack prefix', 'jetpack-backup-pkg' ),
125 - 'manage_options',
126 - 'jetpack-backup',
127 - array( __CLASS__, 'plugin_settings_page' )
128 - );
129 - add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
184 + add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
185 + add_action( 'admin_menu', array( __CLASS__, 'add_wp_admin_submenu' ), 1 ); // Akismet uses 4, so we need to use 1 to ensure both menus are added when only they exist.
130 186
187 + if ( $options['manage_connection'] ) {
188 + self::init_standalone_connection();
189 + }
190 +
191 + // Jetpack Backup abilities are registered from `actions.php` at package
192 + // autoload time so the surface is available in every consumer that
193 + // loads this package (both the standalone Backup plugin and the
194 + // Jetpack plugin), not only when `Jetpack_Backup::initialize()` runs.
195 +
196 + /**
197 + * Runs right after the Jetpack Backup package is initialized.
198 + *
199 + * @since 1.3.0
200 + */
201 + do_action( 'jetpack_backup_initialized' );
202 + }
203 +
204 + /**
205 + * Set up the connection, sync and identity-crisis packages under the standalone plugin's slug.
206 + */
207 + private static function init_standalone_connection() {
208 + // Set up the REST authentication hooks.
209 + Connection_Rest_Authentication::init();
210 +
131 211 // Init Jetpack packages.
132 212 add_action(
133 213 'plugins_loaded',
134 214 function () {
@@ -153,15 +233,40 @@
153 233
154 234 add_action( 'plugins_loaded', array( __CLASS__, 'maybe_upgrade_db' ), 20 );
155 235
156 236 add_filter( 'jetpack_connection_user_has_license', array( __CLASS__, 'jetpack_check_user_licenses' ), 10, 3 );
237 + }
157 238
158 - /**
159 - * Runs right after the Jetpack Backup package is initialized.
160 - *
161 - * @since 1.3.0
162 - */
163 - do_action( 'jetpack_backup_initialized' );
239 + /**
240 + * The page to be added to submenu
241 + */
242 + public static function add_wp_admin_submenu() {
243 + $wp_build_active = self::is_wp_build_dashboard_active();
244 + $callback = $wp_build_active
245 + ? 'jetpack_backup_jetpack_backup_dashboard_wp_admin_render_page'
246 + : array( __CLASS__, 'plugin_settings_page' );
247 +
248 + // The page title's relabel rides the modernized dashboard rather than the filter alone,
249 + // so a fallback to the legacy page also falls back to the legacy title.
250 + $page_title = $wp_build_active ? 'Jetpack VaultPress Backup' : 'Jetpack Backup';
251 + $menu_title = 'Backup'; // Product name, do not translate.
252 +
253 + $page_suffix = Admin_Menu::add_menu(
254 + $page_title,
255 + $menu_title,
256 + 'manage_options',
257 + self::JETPACK_BACKUP_SLUG,
258 + $callback,
259 + null,
260 + array(
261 + 'product' => 'backup',
262 + 'key' => 'jetpack-backup',
263 + )
264 + );
265 +
266 + if ( $page_suffix ) {
267 + add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
268 + }
164 269 }
165 270
166 271 /**
167 272 * Initialize the admin resources.
@@ -167,8 +272,19 @@
167 272 * Initialize the admin resources.
168 273 */
169 274 public static function admin_init() {
170 275 add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_admin_scripts' ) );
276 +
277 + if ( self::is_wp_build_dashboard_active() ) {
278 + // Notices reflow the dual-pane layout, so clear them but keep our own.
279 + // An older jetpack-jitm may predate the helper; the fallback costs the JITM.
280 + if ( method_exists( JITM::class, 'suppress_foreign_admin_notices' ) ) {
281 + JITM::suppress_foreign_admin_notices();
282 + } else {
283 + remove_all_actions( 'admin_notices' );
284 + remove_all_actions( 'all_admin_notices' );
285 + }
286 + }
171 287 }
172 288
173 289 /**
174 290 * Checks current version against version in code and run upgrades if we are running a new version
@@ -196,8 +312,30 @@
196 312 /**
197 313 * Enqueue plugin admin scripts and styles.
198 314 */
199 315 public static function enqueue_admin_scripts() {
316 + // This callback is registered via `load-{$page_suffix}` in `add_wp_admin_submenu()`,
317 + // so it only fires on the Backup admin page — no need to re-check the page here.
318 + if ( self::is_wp_build_dashboard_active() ) {
319 + // The i18n loader is registered on every admin page by jetpack-assets but
320 + // only enqueued when depended on; the esbuild bundles don't pull it in.
321 + // Enqueue it here, before the early return, so the wp-build dashboard's
322 + // init module can download its JS translation catalogs.
323 + if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
324 + wp_enqueue_script( 'wp-jp-i18n-loader' );
325 + }
326 +
327 + // The esbuild bundles don't declare the Tracks client as a dependency
328 + // either, so it never reaches the page on its own.
329 + if ( self::can_use_analytics() ) {
330 + Tracking::register_tracks_functions_scripts( true );
331 + }
332 +
333 + // wp-build manages its own enqueue pipeline. The legacy script and
334 + // its initial state are skipped for the wp-build dashboard.
335 + return;
336 + }
337 +
200 338 Assets::register_script(
201 339 'jetpack-backup',
202 340 '../build/index.js',
203 341 __FILE__,
@@ -267,9 +405,9 @@
267 405 'jetpack/v4',
268 406 '/has-backup-plan',
269 407 array(
270 408 'methods' => WP_REST_Server::READABLE,
271 - 'callback' => __CLASS__ . '::has_backup_plan',
409 + 'callback' => __CLASS__ . '::get_backup_plan_state',
272 410 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
273 411 )
274 412 );
275 413
@@ -319,8 +457,15 @@
319 457 'args' => array(
320 458 'option_name' => array(
321 459 'required' => true,
322 460 'type' => 'string',
461 + // The two names `Jetpack_Options` recognises. Anything else
462 + // falls through its allowlist to a `trigger_error()` and is
463 + // stored nowhere, so an unlisted reason would dismiss
464 + // nothing while answering as though it had — and on a site
465 + // with `display_errors` on, the warning is printed ahead of
466 + // the JSON and the response no longer parses.
467 + 'enum' => array( 'restore', 'backups' ),
323 468 ),
324 469 'should_dismiss' => array(
325 470 'required' => true,
326 471 'type' => 'boolean',
@@ -339,8 +484,19 @@
339 484 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
340 485 )
341 486 );
342 487
488 + // Get backup schedule time
489 + register_rest_route(
490 + 'jetpack/v4',
491 + '/site/backup/schedule',
492 + array(
493 + 'methods' => WP_REST_Server::READABLE,
494 + 'callback' => __CLASS__ . '::get_site_backup_schedule_time',
495 + 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
496 + )
497 + );
498 +
343 499 // Get site policies
344 500 register_rest_route(
345 501 'jetpack/v4',
346 502 '/site/backup/policies',
@@ -396,14 +552,41 @@
396 552 return current_user_can( 'manage_options' );
397 553 }
398 554
399 555 /**
556 + * The error a route answers with when its WordPress.com request did not come
557 + * back with a 200.
558 + *
559 + * Returning `null` instead — which these routes used to do — is served as an
560 + * HTTP 200 carrying a `null` body, so `apiFetch` resolves and nothing throws.
561 + * A WordPress.com blip then reaches the dashboard as an empty success, which
562 + * is how a paying customer ends up looking at the first-run screen. A
563 + * WP_Error makes the REST layer answer with a status, so every caller's
564 + * existing failure path runs.
565 + *
566 + * @param int $status The upstream response code, already cast to an int, or 0
567 + * when the request never reached WordPress.com.
568 + * @return WP_Error
569 + */
570 + private static function get_failed_fetch_error( $status = 0 ) {
571 + return new WP_Error(
572 + 'failed_to_fetch_data',
573 + esc_html__( 'Unable to fetch the requested data.', 'jetpack-backup-pkg' ),
574 + array(
575 + // A transport failure has no status at all, and `status_header( 0 )`
576 + // emits an invalid status line — so anything falsy becomes a 500.
577 + 'status' => $status ? $status : 500,
578 + )
579 + );
580 + }
581 +
582 + /**
400 583 * Get information about recent backups
401 584 *
402 585 * @access public
403 586 * @static
404 587 *
405 - * @return array An array of recent backups
588 + * @return \WP_REST_Response|WP_Error The recent backups, or a WP_Error if WordPress.com could not be reached.
406 589 */
407 590 public static function get_recent_backups() {
408 591 $blog_id = Jetpack_Options::get_option( 'id' );
409 592
@@ -414,10 +597,12 @@
414 597 null,
415 598 'wpcom'
416 599 );
417 600
418 - if ( 200 !== $response['response']['code'] ) {
419 - return null;
601 + $response_code = (int) wp_remote_retrieve_response_code( $response );
602 +
603 + if ( 200 !== $response_code ) {
604 + return self::get_failed_fetch_error( $response_code );
420 605 }
421 606
422 607 return rest_ensure_response(
423 608 json_decode( $response['body'], true )
@@ -426,50 +611,86 @@
426 611
427 612 /**
428 613 * Hits the wpcom api to check rewind status.
429 614 *
430 - * @return Object|WP_Error
615 + * Bounded well clear of a healthy round trip; `Client`'s 10s default is too
616 + * long for the synchronous `authorize_redirect` this sits on.
617 + *
618 + * @return object|WP_Error The decoded rewind state, or a WP_Error if WordPress.com could not be read.
431 619 */
432 620 private static function get_rewind_state_from_wpcom() {
433 - static $status = null;
434 -
435 - if ( $status !== null ) {
436 - return $status;
621 + if ( self::$rewind_state !== null ) {
622 + return self::$rewind_state;
437 623 }
438 624
439 625 $site_id = Jetpack_Options::get_option( 'id' );
440 626
441 - $response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d/rewind', $site_id ) . '?force=wpcom', '2', array( 'timeout' => 2 ), null, 'wpcom' );
627 + $response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d/rewind', $site_id ) . '?force=wpcom', '2', array( 'timeout' => 5 ), null, 'wpcom' );
442 628
443 - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
444 - return new WP_Error( 'rewind_state_fetch_failed' );
629 + // Cast: `wp_remote_retrieve_response_code()` hands back whatever the
630 + // transport put there, and a numeric-string `'200'` fails this strict
631 + // comparison.
632 + $response_code = (int) wp_remote_retrieve_response_code( $response );
633 +
634 + if ( 200 !== $response_code ) {
635 + return self::get_failed_fetch_error( $response_code );
445 636 }
446 637
447 - $body = wp_remote_retrieve_body( $response );
448 - $status = json_decode( $body );
449 - return $status;
638 + $state = json_decode( wp_remote_retrieve_body( $response ) );
639 +
640 + // A 200 with no `state` is a read that failed, not a site without a
641 + // plan. Caching it would hold that answer for the rest of the request;
642 + // refusing lets a later caller ask again and get a real one.
643 + if ( ! is_object( $state ) || ! isset( $state->state ) ) {
644 + return new WP_Error(
645 + 'rewind_state_unreadable',
646 + esc_html__( 'Unable to read the backup plan details for this site.', 'jetpack-backup-pkg' ),
647 + array( 'status' => 500 )
648 + );
649 + }
650 +
651 + self::$rewind_state = $state;
652 + return self::$rewind_state;
450 653 }
451 654
452 655 /**
453 - * Checks whether the current plan (or purchases) of the site already supports the product
656 + * Checks whether the site supports the product, reporting an unreadable answer as an error.
454 657 *
455 - * @return boolean
658 + * @since 5.0.1
659 + *
660 + * @return bool|WP_Error True when the site has Backup, or a WP_Error if WordPress.com could not be read.
456 661 */
457 - public static function has_backup_plan() {
662 + public static function get_backup_plan_state() {
458 663 $rewind_data = static::get_rewind_state_from_wpcom();
664 +
459 665 if ( is_wp_error( $rewind_data ) ) {
460 - return false;
666 + return $rewind_data;
461 667 }
462 - return is_object( $rewind_data ) && isset( $rewind_data->state ) && 'unavailable' !== $rewind_data->state;
668 +
669 + return 'unavailable' !== $rewind_data->state;
463 670 }
464 671
465 672 /**
673 + * Checks whether the current plan (or purchases) of the site already supports the product
674 + *
675 + * Answers a plan it could not read as absent, which is the one place that
676 + * decision is made for every `bool` caller.
677 + *
678 + * @return bool
679 + */
680 + public static function has_backup_plan() {
681 + $state = static::get_backup_plan_state();
682 +
683 + return ! is_wp_error( $state ) && $state;
684 + }
685 +
686 + /**
466 687 * Get an array of backup/scan/anti-spam site capabilities
467 688 *
468 689 * @access public
469 690 * @static
470 691 *
471 - * @return array An array of capabilities
692 + * @return \WP_REST_Response|WP_Error The site capabilities, or a WP_Error if WordPress.com could not be reached.
472 693 */
473 694 public static function get_backup_capabilities() {
474 695 $blog_id = Jetpack_Options::get_option( 'id' );
475 696
@@ -480,14 +701,12 @@
480 701 null,
481 702 'wpcom'
482 703 );
483 704
484 - if ( is_wp_error( $response ) ) {
485 - return null;
486 - }
705 + $response_code = (int) wp_remote_retrieve_response_code( $response );
487 706
488 - if ( 200 !== $response['response']['code'] ) {
489 - return null;
707 + if ( 200 !== $response_code ) {
708 + return self::get_failed_fetch_error( $response_code );
490 709 }
491 710
492 711 return rest_ensure_response(
493 712 json_decode( $response['body'], true )
@@ -499,9 +718,9 @@
499 718 *
500 719 * @access public
501 720 * @static
502 721 *
503 - * @return array An array of recent restores
722 + * @return \WP_REST_Response|WP_Error The recent restores, or a WP_Error if WordPress.com could not be reached.
504 723 */
505 724 public static function get_recent_restores() {
506 725 $blog_id = Jetpack_Options::get_option( 'id' );
507 726 $response = Client::wpcom_json_api_request_as_blog(
@@ -511,9 +730,82 @@
511 730 null,
512 731 'wpcom'
513 732 );
514 733
515 - if ( 200 !== $response['response']['code'] ) {
734 + $response_code = (int) wp_remote_retrieve_response_code( $response );
735 +
736 + if ( 200 !== $response_code ) {
737 + return self::get_failed_fetch_error( $response_code );
738 + }
739 +
740 + return rest_ensure_response(
741 + json_decode( $response['body'], true )
742 + );
743 + }
744 +
745 + /**
746 + * Query backup-completion events from the wpcom activity-log via the
747 + * general `/sites/<id>/activity` endpoint with the action filter pinned
748 + * to backup-completion event names. This endpoint paginates real-ly
749 + * (Elasticsearch `from` offset under the hood) — the `/activity/rewindable`
750 + * sibling looks like a more natural fit but hardcodes `page: 1,
751 + * totalPages: 1` and ignores the `page` parameter.
752 + *
753 + * Auth: signs as user. The endpoint gates on the requesting WP user
754 + * being an administrator of the blog (see
755 + * sites-activity.php::readable_permission_check); blog-level tokens
756 + * return 401.
757 + *
758 + * Returned shape (success): a W3C ActivityStreams envelope:
759 + * {
760 + * "@context": ..., "type": "OrderedCollection", "totalItems": int,
761 + * "page": int, "totalPages": int, "itemsPerPage": int,
762 + * "orderedItems": [ <event>, ... ]
763 + * }
764 + * Each event has at least `published`, `rewind_id`, `is_rewindable`,
765 + * `name`, `status`, `summary`.
766 + *
767 + * @param array $args Query args passed through to wpcom. Supported keys:
768 + * `after` (ISO 8601), `before` (ISO 8601), `on` (ISO 8601),
769 + * `date_range`, `number` (max 1000), `page` (1-based),
770 + * `sort_order` ('asc'|'desc'). Any `action` key is
771 + * overridden with the curated backup-completion list.
772 + * @return array|\WP_REST_Response|null
773 + */
774 + public static function list_backup_events( array $args = array() ) {
775 + $blog_id = Jetpack_Options::get_option( 'id' );
776 +
777 + // Curated set of activity actions that represent "a backup completed".
778 + // Mirrors `WPCOM_REST_API_V2_Endpoint_Site_Activity::$backup_action_names`.
779 + // Pinned here (and overriding any caller-supplied `action`) so the
780 + // helper is always scoped to backups regardless of what the caller passes.
781 + $args['action'] = array(
782 + 'backup_complete_full',
783 + 'backup_complete_initial',
784 + 'backup_only_complete_full',
785 + 'backup_only_complete_initial',
786 + 'rewind__backup_complete_full',
787 + 'rewind__backup_complete_initial',
788 + 'rewind__backup_only_complete_full',
789 + 'rewind__backup_only_complete_initial',
790 + );
791 +
792 + $path = '/sites/' . (int) $blog_id . '/activity?' . http_build_query( $args );
793 +
794 + $response = Client::wpcom_json_api_request_as_user(
795 + $path,
796 + 'v2',
797 + array(),
798 + null,
799 + 'wpcom'
800 + );
801 +
802 + // Cast, as everywhere else this package reads a status. Uncast, a
803 + // numeric-string `'200'` discards a good activity page and the
804 + // `jetpack-backup/list-backup-events` ability reports that the site
805 + // has completed no backups — `unwrap_response()` flattens this
806 + // `null` into an empty list, which is a claim rather than an error.
807 + if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
516 808 return null;
517 809 }
518 810
519 811 return rest_ensure_response(
@@ -523,28 +815,64 @@
523 815
524 816 /**
525 817 * Gets information about the currently promoted backup product.
526 818 *
527 - * @return string|WP_Error A JSON object of the current backup product being promoted if the request was successful, or a WP_Error otherwise.
819 + * Answers from a per-locale transient when one is warm; failures are not cached.
820 + *
821 + * @return object|WP_Error The promoted product, or a WP_Error if it could not be read.
528 822 */
529 823 public static function get_backup_promoted_product_info() {
530 - $request_url = 'https://public-api.wordpress.com/rest/v1.1/products?locale=' . get_user_locale() . '&type=jetpack';
824 + $locale = get_user_locale();
825 + $transient_key = self::PROMOTED_PRODUCT_TRANSIENT_PREFIX . sanitize_key( $locale );
826 + $cached = get_transient( $transient_key );
827 +
828 + if ( false !== $cached ) {
829 + return $cached;
830 + }
831 +
832 + $request_url = 'https://public-api.wordpress.com/rest/v1.1/products?locale=' . $locale . '&type=jetpack';
531 833 $wpcom_request = wp_remote_get( esc_url_raw( $request_url ) );
532 - $response_code = wp_remote_retrieve_response_code( $wpcom_request );
533 - if ( 200 === $response_code ) {
534 - $products = json_decode( wp_remote_retrieve_body( $wpcom_request ) );
535 - return $products->{self::JETPACK_BACKUP_PROMOTED_PRODUCT};
536 - } else {
537 - // Something went wrong so we'll just return the response without caching.
834 + // Cast: the transport may report the status as a numeric string, which
835 + // a strict comparison against 200 sends down the failure path.
836 + $response_code = (int) wp_remote_retrieve_response_code( $wpcom_request );
837 +
838 + if ( 200 !== $response_code ) {
538 839 return new WP_Error(
539 840 'failed_to_fetch_data',
540 841 esc_html__( 'Unable to fetch the requested data.', 'jetpack-backup-pkg' ),
541 842 array(
542 - 'status' => $response_code,
843 + // A transport failure has no status at all; reporting 0 would
844 + // leave the REST layer with nothing to serve.
845 + 'status' => $response_code ? $response_code : 500,
543 846 'request' => $wpcom_request,
544 847 )
545 848 );
546 849 }
850 +
851 + $products = json_decode( wp_remote_retrieve_body( $wpcom_request ) );
852 +
853 + // A 200 is not a promise that the promoted product is in the body. A
854 + // truncated response decodes to null, and the slug is a constant here
855 + // but a catalogue entry upstream — retiring it there leaves this a 200
856 + // with the key absent. Reading through either emits a PHP warning and
857 + // yields null, which the route then serves as a 200 carrying `null`:
858 + // indistinguishable, to a caller, from a priced answer it failed to
859 + // read. Refusing says which of the two happened.
860 + if ( ! is_object( $products ) || ! isset( $products->{ self::JETPACK_BACKUP_PROMOTED_PRODUCT } ) ) {
861 + return new WP_Error(
862 + 'promoted_product_unreadable',
863 + esc_html__( 'Unable to read the promoted product information.', 'jetpack-backup-pkg' ),
864 + array( 'status' => 500 )
865 + );
866 + }
867 +
868 + $product = $products->{ self::JETPACK_BACKUP_PROMOTED_PRODUCT };
869 +
870 + // Must stay below both guards: a cached failure would leave the no-plan
871 + // screen without a price for the whole TTL after WordPress.com recovered.
872 + set_transient( $transient_key, $product, self::PROMOTED_PRODUCT_CACHE_TTL );
873 +
874 + return $product;
547 875 }
548 876
549 877 /**
550 878 * Check for user licenses.
@@ -573,16 +901,16 @@
573 901 return $license_found && ! static::has_backup_plan();
574 902 }
575 903
576 904 /**
577 - * Returns the result of `/sites/%d/purchases` endpoint call.
905 + * Returns the result of `/upgrades` endpoint call.
578 906 *
579 - * @return array of site purchases.
907 + * @return \WP_REST_Response|WP_Error The site purchases, or a WP_Error if WordPress.com could not be reached.
580 908 */
581 909 public static function get_site_current_purchases() {
582 910
583 - $request = sprintf( '/sites/%d/purchases', Jetpack_Options::get_option( 'id' ) );
584 - $response = Client::wpcom_json_api_request_as_blog( $request, '1.1' );
911 + $request = sprintf( '/upgrades?site=%d', Jetpack_Options::get_option( 'id' ) );
912 + $response = Client::wpcom_json_api_request_as_blog( $request, '1.2' );
585 913
586 914 // Bail if there was an error or malformed response.
587 915 if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
588 916 return self::get_failed_fetch_error();
@@ -587,10 +915,12 @@
587 915 if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
588 916 return self::get_failed_fetch_error();
589 917 }
590 918
591 - if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
592 - return self::get_failed_fetch_error();
919 + $response_code = (int) wp_remote_retrieve_response_code( $response );
920 +
921 + if ( 200 !== $response_code ) {
922 + return self::get_failed_fetch_error( $response_code );
593 923 }
594 924
595 925 return rest_ensure_response(
596 926 json_decode( $response['body'], true )
@@ -620,9 +950,9 @@
620 950
621 951 /**
622 952 * Get site storage size
623 953 *
624 - * @return string|WP_Error A JSON object with the site storage size if the request was successful, or a WP_Error otherwise.
954 + * @return \WP_REST_Response|WP_Error The site storage size, or a WP_Error if WordPress.com could not be reached.
625 955 */
626 956 public static function get_site_backup_size() {
627 957 $blog_id = Jetpack_Options::get_option( 'id' );
628 958
@@ -633,10 +963,12 @@
633 963 null,
634 964 'wpcom'
635 965 );
636 966
637 - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
638 - return null;
967 + $response_code = (int) wp_remote_retrieve_response_code( $response );
968 +
969 + if ( 200 !== $response_code ) {
970 + return self::get_failed_fetch_error( $response_code );
639 971 }
640 972
641 973 return rest_ensure_response(
642 974 json_decode( $response['body'], true )
@@ -645,10 +977,9 @@
645 977
646 978 /**
647 979 * Get site policies from WPCOM. It includes the storage limit and activity log limit, if apply.
648 980 *
649 - * @return string|WP_Error A JSON object with the site storage policies if the request was successful,
650 - * or a WP_Error otherwise.
981 + * @return \WP_REST_Response|WP_Error The site storage policies, or a WP_Error if WordPress.com could not be reached.
651 982 */
652 983 public static function get_site_backup_policies() {
653 984 $blog_id = Jetpack_Options::get_option( 'id' );
654 985
@@ -659,10 +990,12 @@
659 990 null,
660 991 'wpcom'
661 992 );
662 993
663 - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
664 - return null;
994 + $response_code = (int) wp_remote_retrieve_response_code( $response );
995 +
996 + if ( 200 !== $response_code ) {
997 + return self::get_failed_fetch_error( $response_code );
665 998 }
666 999
667 1000 return rest_ensure_response(
668 1001 json_decode( $response['body'], true )
@@ -698,8 +1031,9 @@
698 1031 if ( $additional_bytes_needed > $bytes_1tb ) {
699 1032 return $upsell_products[ $bytes_1tb ];
700 1033 }
701 1034
1035 + $matched_bytes = $bytes_10gb;
702 1036 foreach ( $upsell_products as $bytes => $product ) {
703 1037 if ( $bytes > $additional_bytes_needed ) {
704 1038 $matched_bytes = $bytes;
705 1039 break;
@@ -705,12 +1039,8 @@
705 1039 break;
706 1040 }
707 1041 }
708 1042
709 - if ( ! $matched_bytes ) {
710 - $matched_bytes = $bytes_10gb;
711 - }
712 -
713 1043 return $upsell_products[ $matched_bytes ];
714 1044 }
715 1045
716 1046 // For 1 TB we are going to offer 1 TB by default
@@ -757,10 +1087,9 @@
757 1087
758 1088 /**
759 1089 * Enqueue a new backup on demand
760 1090 *
761 - * @return string|WP_Error A JSON object with `success` if the request was successful,
762 - * or a WP_Error otherwise.
1091 + * @return \WP_REST_Response|WP_Error The enqueue result, or a WP_Error if WordPress.com could not be reached.
763 1092 */
764 1093 public static function enqueue_backup() {
765 1094 $blog_id = Jetpack_Options::get_option( 'id' );
766 1095 $endpoint = sprintf( '/sites/%d/rewind/backups/enqueue', $blog_id );
@@ -774,10 +1103,12 @@
774 1103 null,
775 1104 'wpcom'
776 1105 );
777 1106
778 - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
779 - return null;
1107 + $response_code = (int) wp_remote_retrieve_response_code( $response );
1108 +
1109 + if ( 200 !== $response_code ) {
1110 + return self::get_failed_fetch_error( $response_code );
780 1111 }
781 1112
782 1113 return rest_ensure_response(
783 1114 json_decode( $response['body'], true )
@@ -784,8 +1115,35 @@
784 1115 );
785 1116 }
786 1117
787 1118 /**
1119 + * Get site backup schedule time
1120 + *
1121 + * @return \WP_REST_Response|WP_Error The backup schedule time, or a WP_Error if WordPress.com could not be reached.
1122 + */
1123 + public static function get_site_backup_schedule_time() {
1124 + $blog_id = Jetpack_Options::get_option( 'id' );
1125 +
1126 + $response = Client::wpcom_json_api_request_as_user(
1127 + '/sites/' . $blog_id . '/rewind/scheduled',
1128 + 'v2',
1129 + array(),
1130 + null,
1131 + 'wpcom'
1132 + );
1133 +
1134 + $response_code = (int) wp_remote_retrieve_response_code( $response );
1135 +
1136 + if ( 200 !== $response_code ) {
1137 + return self::get_failed_fetch_error( $response_code );
1138 + }
1139 +
1140 + return rest_ensure_response(
1141 + json_decode( $response['body'], true )
1142 + );
1143 + }
1144 +
1145 + /**
788 1146 * Removes plugin from the connection manager
789 1147 * If it's the last plugin using the connection, the site will be disconnected.
790 1148 *
791 1149 * @access public
@@ -793,6 +1151,208 @@
793 1151 */
794 1152 public static function plugin_deactivation() {
795 1153 $manager = new Connection_Manager( 'jetpack-backup' );
796 1154 $manager->remove_connection();
1155 + }
1156 +
1157 + /**
1158 + * Load wp-build when modernization is enabled on the Backup admin page.
1159 + *
1160 + * @return void
1161 + */
1162 + public static function maybe_load_wp_build() {
1163 + if ( ! self::is_modernized() || ! self::is_backup_admin_request() ) {
1164 + return;
1165 + }
1166 +
1167 + self::load_wp_build_with_screen_alias();
1168 +
1169 + // wp-build registers standalone modules (e.g. the init module) on
1170 + // wp_default_scripts, which has already fired by admin_menu. Register them
1171 + // directly so the init module makes it into the import map.
1172 + if ( function_exists( 'jetpack_backup_register_script_modules' ) ) {
1173 + jetpack_backup_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
1174 + }
1175 +
1176 + add_action( 'admin_print_scripts', array( __CLASS__, 'render_connection_initial_state' ), 1 );
1177 + }
1178 +
1179 + /**
1180 + * Emit `window.JP_CONNECTION_INITIAL_STATE` inline on the modernized
1181 + * Backup admin page.
1182 + *
1183 + * The modernized enqueue path short-circuits before the legacy
1184 + * `Connection_Initial_State::render_script()` call, so without this
1185 + * the React `<Gates>` component never sees the connection state and
1186 + * sits on its loading skeleton forever. We emit the same JS payload
1187 + * the legacy path emits, just outside of a registered script handle
1188 + * (wp-build's handles aren't reliable here, and the global is
1189 + * page-scoped — any tag setting it works).
1190 + *
1191 + * @return void
1192 + */
1193 + public static function render_connection_initial_state() {
1194 + echo '<script id="jetpack-backup-connection-initial-state">'
1195 + . Connection_Initial_State::render() // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render() returns pre-escaped JSON.
1196 + . '</script>';
1197 + }
1198 +
1199 + /**
1200 + * Load the wp-build entry file and register its polyfills.
1201 + *
1202 + * Only called on `?page=jetpack-backup` admin requests when `is_modernized()`
1203 + * is true. Keeps wp-build off every other request.
1204 + *
1205 + * @return void
1206 + */
1207 + private static function load_wp_build() {
1208 + $build_index = dirname( __DIR__ ) . '/build/build.php';
1209 +
1210 + if ( ! file_exists( $build_index ) ) {
1211 + return;
1212 + }
1213 +
1214 + require_once $build_index;
1215 +
1216 + \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::register(
1217 + 'jetpack-backup',
1218 + array_merge(
1219 + \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::SCRIPT_HANDLES,
1220 + \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::MODULE_IDS
1221 + )
1222 + );
1223 + }
1224 +
1225 + /**
1226 + * Load wp-build with the screen ID aliased across its generated enqueue check.
1227 + *
1228 + * @see WP_Build_Screen_Id::load_with_alias()
1229 + * @return void
1230 + */
1231 + private static function load_wp_build_with_screen_alias() {
1232 + // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
1233 + if ( method_exists( \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
1234 + \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id::load_with_alias(
1235 + array( __CLASS__, 'alias_screen_id_for_wp_build' ),
1236 + array( __CLASS__, 'restore_screen_id_after_wp_build' ),
1237 + function () {
1238 + self::load_wp_build();
1239 + }
1240 + );
1241 + return;
1242 + }
1243 +
1244 + add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
1245 + self::load_wp_build();
1246 + add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
1247 + }
1248 +
1249 + /**
1250 + * Alias the current screen ID to satisfy wp-build's auto-generated enqueue check.
1251 + *
1252 + * Wp-build's `<page>-wp-admin` enqueue callback enqueues only when the screen ID
1253 + * matches the wp-build page slug (`jetpack-backup-dashboard`). Our WP-admin
1254 + * menu slug stays `jetpack-backup`, so we mutate the screen object in place
1255 + * to make the check pass without changing the user-facing URL.
1256 + *
1257 + * Hooked only when modernization is on AND we're on the Backup admin page,
1258 + * so this never affects any other request.
1259 + *
1260 + * @since 5.0.4 Takes no argument; hooked on `admin_enqueue_scripts`.
1261 + *
1262 + * @return void
1263 + */
1264 + public static function alias_screen_id_for_wp_build() {
1265 + $screen = get_current_screen();
1266 + if ( ! $screen ) {
1267 + return;
1268 + }
1269 +
1270 + self::$wp_build_original_screen_id = $screen->id;
1271 + $screen->id = 'jetpack-backup-dashboard';
1272 + }
1273 +
1274 + /**
1275 + * Undo alias_screen_id_for_wp_build(), so code after the generated check sees the real screen ID.
1276 + *
1277 + * @since 5.0.4
1278 + *
1279 + * @return void
1280 + */
1281 + public static function restore_screen_id_after_wp_build() {
1282 + $screen = get_current_screen();
1283 + if ( ! $screen || null === self::$wp_build_original_screen_id ) {
1284 + return;
1285 + }
1286 +
1287 + $screen->id = self::$wp_build_original_screen_id;
1288 + self::$wp_build_original_screen_id = null;
1289 + }
1290 +
1291 + /**
1292 + * Returns the modernization filter's value, which defaults to the internal preview.
1293 + *
1294 + * @since 4.3.14 Changed from private to public; the REST bridges gate their route registration on it.
1295 + *
1296 + * @return bool
1297 + */
1298 + public static function is_modernized() {
1299 + return (bool) apply_filters( self::MODERNIZATION_FILTER, self::is_internal_preview() );
1300 + }
1301 +
1302 + /**
1303 + * Whether an internal user on the A8C proxy previews the dashboard. Not an authorization check.
1304 + *
1305 + * The proxy is checked first, so other requests never make the connected-user lookup.
1306 + *
1307 + * @return bool
1308 + */
1309 + private static function is_internal_preview() {
1310 + if ( ! Constants::is_true( 'AT_PROXIED_REQUEST' ) ) {
1311 + return false;
1312 + }
1313 +
1314 + if ( function_exists( 'wpcomsh_is_site_sticker_active' ) && wpcomsh_is_site_sticker_active( self::LEGACY_DASHBOARD_STICKER ) ) {
1315 + return false;
1316 + }
1317 +
1318 + $user_data = ( new Connection_Manager() )->get_connected_user_data();
1319 + $email = is_array( $user_data ) && ! empty( $user_data['email'] ) ? strtolower( (string) $user_data['email'] ) : '';
1320 +
1321 + return str_ends_with( $email, '@automattic.com' ) || str_ends_with( $email, '@a8c.com' );
1322 + }
1323 +
1324 + /**
1325 + * Returns true when `is_modernized()` is true AND the wp-build dashboard loaded.
1326 + *
1327 + * `build/` is gitignored, so the render function is absent in any unbuilt checkout
1328 + * and in any release whose wp-build step failed. Every consumer of the modernized
1329 + * surface has to agree on this, or the menu falls back to the legacy page while the
1330 + * enqueue path skips the legacy script — an empty div with no JS.
1331 + *
1332 + * Only meaningful once `maybe_load_wp_build()` has run. It is hooked on `admin_menu`
1333 + * at the same priority as `add_wp_admin_submenu()`, so registration order — not
1334 + * priority — is what keeps it first. Do not reorder those two `add_action()` calls.
1335 + *
1336 + * @return bool
1337 + */
1338 + private static function is_wp_build_dashboard_active() {
1339 + return self::is_modernized() && function_exists( 'jetpack_backup_jetpack_backup_dashboard_wp_admin_render_page' );
1340 + }
1341 +
1342 + /**
1343 + * Returns true when the current request targets the Backup admin page.
1344 + *
1345 + * Used to scope wp-build loading to the one page that needs it. The
1346 + * `$_GET['page']` value is populated by wp-admin/admin.php before any of
1347 + * our hooks fire, so this check is reliable from `initialize()` onwards.
1348 + *
1349 + * @return bool
1350 + */
1351 + private static function is_backup_admin_request() {
1352 + if ( ! is_admin() || ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1353 + return false;
1354 + }
1355 +
1356 + return sanitize_text_field( wp_unslash( $_GET['page'] ) ) === self::JETPACK_BACKUP_SLUG; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
797 1357 }
798 1358 }