PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3
Jetpack – WP Security, Backup, Speed, & Growth v16.3
16.3 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 All 508 releases
← All changes | jetpack_vendor/automattic/jetpack-backup/src/class-jetpack-backup.php +716 -89 12.9.5 → 16.3 View file →
@@ -4,24 +4,48 @@
4 4 *
5 5 * @package automattic/jetpack-backup-plugin
6 6 */
7 7
8 +// After changing this file, consider increasing the version number ("VXXX") in all the files using this namespace, in
9 +// order to ensure that the specific version of this file always get loaded. Otherwise, Jetpack autoloader might decide
10 +// to load an older/newer version of the class (if, for example, both the standalone and bundled versions of the plugin
11 +// are installed, or in some other cases).
12 +namespace Automattic\Jetpack\Backup\V0005;
13 +
8 14 if ( ! defined( 'ABSPATH' ) ) {
9 - exit;
15 + exit( 0 );
10 16 }
11 17
12 18 use Automattic\Jetpack\Admin_UI\Admin_Menu;
13 19 use Automattic\Jetpack\Assets;
14 -use Automattic\Jetpack\Backup\Initial_State as Backup_Initial_State;
15 -use Automattic\Jetpack\Backup\Jetpack_Backup_Upgrades;
20 +use Automattic\Jetpack\Backup\V0005\Initial_State as Backup_Initial_State;
21 +use Automattic\Jetpack\Config;
16 22 use Automattic\Jetpack\Connection\Client;
17 23 use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
18 24 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
19 25 use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
26 +use Automattic\Jetpack\Constants;
27 +use Automattic\Jetpack\JITMS\JITM;
20 28 use Automattic\Jetpack\My_Jetpack\Wpcom_Products;
21 29 use Automattic\Jetpack\Status;
22 30 use Automattic\Jetpack\Terms_Of_Service;
23 31 use Automattic\Jetpack\Tracking;
32 +use Jetpack_Options;
33 +use WP_Error;
34 +use WP_REST_Server;
35 +use function add_action;
36 +use function add_filter;
37 +use function did_action;
38 +use function do_action;
39 +use function esc_url_raw;
40 +use function get_option;
41 +use function is_wp_error;
42 +use function rest_ensure_response;
43 +use function update_option;
44 +use function wp_add_inline_script;
45 +use function wp_remote_get;
46 +use function wp_remote_retrieve_body;
47 +use function wp_remote_retrieve_response_code;
24 48
25 49 /**
26 50 * Class Jetpack_Backup
27 51 */
@@ -55,8 +79,28 @@
55 79 */
56 80 const JETPACK_BACKUP_PROMOTED_PRODUCT = 'jetpack_backup_t1_yearly';
57 81
58 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 + /**
59 103 * Licenses product ID.
60 104 *
61 105 * @var string
62 106 */
@@ -80,34 +124,96 @@
80 124 */
81 125 const JETPACK_BACKUP_DB_VERSION = '2';
82 126
83 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 + /**
84 170 * Constructor.
171 + *
172 + * @param array $options Overrides for self::DEFAULT_INIT_OPTIONS.
85 173 */
86 - public static function initialize() {
174 + public static function initialize( array $options = array() ) {
87 175 if ( did_action( 'jetpack_backup_initialized' ) ) {
88 176 return;
89 177 }
90 178
91 - // Set up the REST authentication hooks.
92 - Connection_Rest_Authentication::init();
179 + $options = array_merge( self::DEFAULT_INIT_OPTIONS, $options );
93 180
94 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' ) );
95 183
96 - $page_suffix = Admin_Menu::add_menu(
97 - __( 'Jetpack VaultPress Backup', 'jetpack-backup-pkg' ),
98 - _x( 'VaultPress Backup', 'The Jetpack VaultPress Backup product name, without the Jetpack prefix', 'jetpack-backup-pkg' ),
99 - 'manage_options',
100 - 'jetpack-backup',
101 - array( __CLASS__, 'plugin_settings_page' )
102 - );
103 - 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.
104 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 +
105 211 // Init Jetpack packages.
106 212 add_action(
107 213 'plugins_loaded',
108 214 function () {
109 - $config = new Automattic\Jetpack\Config();
215 + $config = new Config();
110 216 // Connection package.
111 217 $config->ensure(
112 218 'connection',
113 219 array(
@@ -127,15 +233,40 @@
127 233
128 234 add_action( 'plugins_loaded', array( __CLASS__, 'maybe_upgrade_db' ), 20 );
129 235
130 236 add_filter( 'jetpack_connection_user_has_license', array( __CLASS__, 'jetpack_check_user_licenses' ), 10, 3 );
237 + }
131 238
132 - /**
133 - * Runs right after the Jetpack Backup package is initialized.
134 - *
135 - * @since 1.3.0
136 - */
137 - 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 + }
138 269 }
139 270
140 271 /**
141 272 * Initialize the admin resources.
@@ -141,8 +272,19 @@
141 272 * Initialize the admin resources.
142 273 */
143 274 public static function admin_init() {
144 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 + }
145 287 }
146 288
147 289 /**
148 290 * Checks current version against version in code and run upgrades if we are running a new version
@@ -170,8 +312,30 @@
170 312 /**
171 313 * Enqueue plugin admin scripts and styles.
172 314 */
173 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 +
174 338 Assets::register_script(
175 339 'jetpack-backup',
176 340 '../build/index.js',
177 341 __FILE__,
@@ -241,9 +405,9 @@
241 405 'jetpack/v4',
242 406 '/has-backup-plan',
243 407 array(
244 408 'methods' => WP_REST_Server::READABLE,
245 - 'callback' => __CLASS__ . '::has_backup_plan',
409 + 'callback' => __CLASS__ . '::get_backup_plan_state',
246 410 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
247 411 )
248 412 );
249 413
@@ -286,9 +450,9 @@
286 450 register_rest_route(
287 451 'jetpack/v4',
288 452 '/site/dismissed-review-request',
289 453 array(
290 - 'methods' => \WP_REST_Server::EDITABLE,
454 + 'methods' => WP_REST_Server::EDITABLE,
291 455 'callback' => __CLASS__ . '::manage_dismissed_backup_review_request',
292 456 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
293 457 'args' => array(
294 458 'option_name' => array(
@@ -293,8 +457,15 @@
293 457 'args' => array(
294 458 'option_name' => array(
295 459 'required' => true,
296 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' ),
297 468 ),
298 469 'should_dismiss' => array(
299 470 'required' => true,
300 471 'type' => 'boolean',
@@ -313,8 +484,19 @@
313 484 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
314 485 )
315 486 );
316 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 +
317 499 // Get site policies
318 500 register_rest_route(
319 501 'jetpack/v4',
320 502 '/site/backup/policies',
@@ -344,8 +526,19 @@
344 526 ),
345 527 ),
346 528 )
347 529 );
530 +
531 + // Enqueue a new backup
532 + register_rest_route(
533 + 'jetpack/v4',
534 + '/site/backup/enqueue',
535 + array(
536 + 'methods' => WP_REST_Server::CREATABLE,
537 + 'callback' => __CLASS__ . '::enqueue_backup',
538 + 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
539 + )
540 + );
348 541 }
349 542
350 543 /**
351 544 * The backup calls should only occur from a signed in admin user
@@ -359,19 +552,46 @@
359 552 return current_user_can( 'manage_options' );
360 553 }
361 554
362 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 + /**
363 583 * Get information about recent backups
364 584 *
365 585 * @access public
366 586 * @static
367 587 *
368 - * @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.
369 589 */
370 590 public static function get_recent_backups() {
371 - $blog_id = \Jetpack_Options::get_option( 'id' );
591 + $blog_id = Jetpack_Options::get_option( 'id' );
372 592
373 - $response = Automattic\Jetpack\Connection\Client::wpcom_json_api_request_as_blog(
593 + $response = Client::wpcom_json_api_request_as_blog(
374 594 '/sites/' . $blog_id . '/rewind/backups',
375 595 'v2',
376 596 array(),
377 597 null,
@@ -377,10 +597,12 @@
377 597 null,
378 598 'wpcom'
379 599 );
380 600
381 - if ( 200 !== $response['response']['code'] ) {
382 - 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 );
383 605 }
384 606
385 607 return rest_ensure_response(
386 608 json_decode( $response['body'], true )
@@ -389,55 +611,91 @@
389 611
390 612 /**
391 613 * Hits the wpcom api to check rewind status.
392 614 *
393 - * @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.
394 619 */
395 620 private static function get_rewind_state_from_wpcom() {
396 - static $status = null;
397 -
398 - if ( $status !== null ) {
399 - return $status;
621 + if ( self::$rewind_state !== null ) {
622 + return self::$rewind_state;
400 623 }
401 624
402 625 $site_id = Jetpack_Options::get_option( 'id' );
403 626
404 - $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' );
405 628
406 - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
407 - 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 );
408 636 }
409 637
410 - $body = wp_remote_retrieve_body( $response );
411 - $status = json_decode( $body );
412 - 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;
413 653 }
414 654
415 655 /**
416 - * 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.
417 657 *
418 - * @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.
419 661 */
420 - public static function has_backup_plan() {
662 + public static function get_backup_plan_state() {
421 663 $rewind_data = static::get_rewind_state_from_wpcom();
664 +
422 665 if ( is_wp_error( $rewind_data ) ) {
423 - return false;
666 + return $rewind_data;
424 667 }
425 - return is_object( $rewind_data ) && isset( $rewind_data->state ) && 'unavailable' !== $rewind_data->state;
668 +
669 + return 'unavailable' !== $rewind_data->state;
426 670 }
427 671
428 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 + /**
429 687 * Get an array of backup/scan/anti-spam site capabilities
430 688 *
431 689 * @access public
432 690 * @static
433 691 *
434 - * @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.
435 693 */
436 694 public static function get_backup_capabilities() {
437 - $blog_id = \Jetpack_Options::get_option( 'id' );
695 + $blog_id = Jetpack_Options::get_option( 'id' );
438 696
439 - $response = Automattic\Jetpack\Connection\Client::wpcom_json_api_request_as_user(
697 + $response = Client::wpcom_json_api_request_as_user(
440 698 '/sites/' . $blog_id . '/rewind/capabilities',
441 699 'v2',
442 700 array(),
443 701 null,
@@ -443,14 +701,12 @@
443 701 null,
444 702 'wpcom'
445 703 );
446 704
447 - if ( is_wp_error( $response ) ) {
448 - return null;
449 - }
705 + $response_code = (int) wp_remote_retrieve_response_code( $response );
450 706
451 - if ( 200 !== $response['response']['code'] ) {
452 - return null;
707 + if ( 200 !== $response_code ) {
708 + return self::get_failed_fetch_error( $response_code );
453 709 }
454 710
455 711 return rest_ensure_response(
456 712 json_decode( $response['body'], true )
@@ -462,13 +718,13 @@
462 718 *
463 719 * @access public
464 720 * @static
465 721 *
466 - * @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.
467 723 */
468 724 public static function get_recent_restores() {
469 - $blog_id = \Jetpack_Options::get_option( 'id' );
470 - $response = Automattic\Jetpack\Connection\Client::wpcom_json_api_request_as_blog(
725 + $blog_id = Jetpack_Options::get_option( 'id' );
726 + $response = Client::wpcom_json_api_request_as_blog(
471 727 '/sites/' . $blog_id . '/rewind/restores',
472 728 'v2',
473 729 array(),
474 730 null,
@@ -474,9 +730,82 @@
474 730 null,
475 731 'wpcom'
476 732 );
477 733
478 - 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 ) ) {
479 808 return null;
480 809 }
481 810
482 811 return rest_ensure_response(
@@ -486,28 +815,64 @@
486 815
487 816 /**
488 817 * Gets information about the currently promoted backup product.
489 818 *
490 - * @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.
491 822 */
492 823 public static function get_backup_promoted_product_info() {
493 - $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';
494 833 $wpcom_request = wp_remote_get( esc_url_raw( $request_url ) );
495 - $response_code = wp_remote_retrieve_response_code( $wpcom_request );
496 - if ( 200 === $response_code ) {
497 - $products = json_decode( wp_remote_retrieve_body( $wpcom_request ) );
498 - return $products->{self::JETPACK_BACKUP_PROMOTED_PRODUCT};
499 - } else {
500 - // 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 ) {
501 839 return new WP_Error(
502 840 'failed_to_fetch_data',
503 841 esc_html__( 'Unable to fetch the requested data.', 'jetpack-backup-pkg' ),
504 842 array(
505 - '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,
506 846 'request' => $wpcom_request,
507 847 )
508 848 );
509 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;
510 875 }
511 876
512 877 /**
513 878 * Check for user licenses.
@@ -536,16 +901,16 @@
536 901 return $license_found && ! static::has_backup_plan();
537 902 }
538 903
539 904 /**
540 - * Returns the result of `/sites/%d/purchases` endpoint call.
905 + * Returns the result of `/upgrades` endpoint call.
541 906 *
542 - * @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.
543 908 */
544 909 public static function get_site_current_purchases() {
545 910
546 - $request = sprintf( '/sites/%d/purchases', \Jetpack_Options::get_option( 'id' ) );
547 - $response = Automattic\Jetpack\Connection\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' );
548 913
549 914 // Bail if there was an error or malformed response.
550 915 if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
551 916 return self::get_failed_fetch_error();
@@ -550,10 +915,12 @@
550 915 if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
551 916 return self::get_failed_fetch_error();
552 917 }
553 918
554 - if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
555 - 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 );
556 923 }
557 924
558 925 return rest_ensure_response(
559 926 json_decode( $response['body'], true )
@@ -573,24 +940,24 @@
573 940
574 941 if ( ! $request['should_dismiss'] ) {
575 942
576 943 return rest_ensure_response(
577 - \Jetpack_Options::get_option( 'dismissed_backup_review_' . $request['option_name'] )
944 + Jetpack_Options::get_option( 'dismissed_backup_review_' . $request['option_name'] )
578 945 );
579 946 }
580 947
581 - return \Jetpack_Options::update_option( 'dismissed_backup_review_' . $request['option_name'], true );
948 + return Jetpack_Options::update_option( 'dismissed_backup_review_' . $request['option_name'], true );
582 949 }
583 950
584 951 /**
585 952 * Get site storage size
586 953 *
587 - * @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.
588 955 */
589 956 public static function get_site_backup_size() {
590 - $blog_id = \Jetpack_Options::get_option( 'id' );
957 + $blog_id = Jetpack_Options::get_option( 'id' );
591 958
592 - $response = Automattic\Jetpack\Connection\Client::wpcom_json_api_request_as_user(
959 + $response = Client::wpcom_json_api_request_as_user(
593 960 '/sites/' . $blog_id . '/rewind/size?force=wpcom',
594 961 'v2',
595 962 array(),
596 963 null,
@@ -596,10 +963,12 @@
596 963 null,
597 964 'wpcom'
598 965 );
599 966
600 - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
601 - 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 );
602 971 }
603 972
604 973 return rest_ensure_response(
605 974 json_decode( $response['body'], true )
@@ -608,15 +977,14 @@
608 977
609 978 /**
610 979 * Get site policies from WPCOM. It includes the storage limit and activity log limit, if apply.
611 980 *
612 - * @return string|WP_Error A JSON object with the site storage policies if the request was successful,
613 - * 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.
614 982 */
615 983 public static function get_site_backup_policies() {
616 - $blog_id = \Jetpack_Options::get_option( 'id' );
984 + $blog_id = Jetpack_Options::get_option( 'id' );
617 985
618 - $response = Automattic\Jetpack\Connection\Client::wpcom_json_api_request_as_user(
986 + $response = Client::wpcom_json_api_request_as_user(
619 987 '/sites/' . $blog_id . '/rewind/policies?force=wpcom',
620 988 'v2',
621 989 array(),
622 990 null,
@@ -622,10 +990,12 @@
622 990 null,
623 991 'wpcom'
624 992 );
625 993
626 - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
627 - 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 );
628 998 }
629 999
630 1000 return rest_ensure_response(
631 1001 json_decode( $response['body'], true )
@@ -661,8 +1031,9 @@
661 1031 if ( $additional_bytes_needed > $bytes_1tb ) {
662 1032 return $upsell_products[ $bytes_1tb ];
663 1033 }
664 1034
1035 + $matched_bytes = $bytes_10gb;
665 1036 foreach ( $upsell_products as $bytes => $product ) {
666 1037 if ( $bytes > $additional_bytes_needed ) {
667 1038 $matched_bytes = $bytes;
668 1039 break;
@@ -668,12 +1039,8 @@
668 1039 break;
669 1040 }
670 1041 }
671 1042
672 - if ( ! $matched_bytes ) {
673 - $matched_bytes = $bytes_10gb;
674 - }
675 -
676 1043 return $upsell_products[ $matched_bytes ];
677 1044 }
678 1045
679 1046 // For 1 TB we are going to offer 1 TB by default
@@ -687,9 +1054,10 @@
687 1054
688 1055 /**
689 1056 * Get the best addon offer for this site, including pricing details
690 1057 *
691 - * @param WP_Request $request Object including storage usage.
1058 + * @param \WP_REST_Request $request Object including storage usage.
1059 + *
692 1060 * @return string|WP_Error A JSON object with the suggested storage addon details if the request was successful,
693 1061 * or a WP_Error otherwise.
694 1062 */
695 1063 public static function get_site_backup_addon_offer( $request ) {
@@ -717,8 +1085,65 @@
717 1085 return rest_ensure_response( $response );
718 1086 }
719 1087
720 1088 /**
1089 + * Enqueue a new backup on demand
1090 + *
1091 + * @return \WP_REST_Response|WP_Error The enqueue result, or a WP_Error if WordPress.com could not be reached.
1092 + */
1093 + public static function enqueue_backup() {
1094 + $blog_id = Jetpack_Options::get_option( 'id' );
1095 + $endpoint = sprintf( '/sites/%d/rewind/backups/enqueue', $blog_id );
1096 +
1097 + $response = Client::wpcom_json_api_request_as_user(
1098 + $endpoint,
1099 + 'v2',
1100 + array(
1101 + 'method' => 'POST',
1102 + ),
1103 + null,
1104 + 'wpcom'
1105 + );
1106 +
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 );
1111 + }
1112 +
1113 + return rest_ensure_response(
1114 + json_decode( $response['body'], true )
1115 + );
1116 + }
1117 +
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 + /**
721 1146 * Removes plugin from the connection manager
722 1147 * If it's the last plugin using the connection, the site will be disconnected.
723 1148 *
724 1149 * @access public
@@ -726,6 +1151,208 @@
726 1151 */
727 1152 public static function plugin_deactivation() {
728 1153 $manager = new Connection_Manager( 'jetpack-backup' );
729 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
730 1357 }
731 1358 }