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 +716 -91 12.3.2 → 16.3-beta 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,35 +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 - 99
103 - );
104 - 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.
105 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 +
106 211 // Init Jetpack packages.
107 212 add_action(
108 213 'plugins_loaded',
109 214 function () {
110 - $config = new Automattic\Jetpack\Config();
215 + $config = new Config();
111 216 // Connection package.
112 217 $config->ensure(
113 218 'connection',
114 219 array(
@@ -128,15 +233,40 @@
128 233
129 234 add_action( 'plugins_loaded', array( __CLASS__, 'maybe_upgrade_db' ), 20 );
130 235
131 236 add_filter( 'jetpack_connection_user_has_license', array( __CLASS__, 'jetpack_check_user_licenses' ), 10, 3 );
237 + }
132 238
133 - /**
134 - * Runs right after the Jetpack Backup package is initialized.
135 - *
136 - * @since 1.3.0
137 - */
138 - 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 + }
139 269 }
140 270
141 271 /**
142 272 * Initialize the admin resources.
@@ -142,8 +272,19 @@
142 272 * Initialize the admin resources.
143 273 */
144 274 public static function admin_init() {
145 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 + }
146 287 }
147 288
148 289 /**
149 290 * Checks current version against version in code and run upgrades if we are running a new version
@@ -171,8 +312,30 @@
171 312 /**
172 313 * Enqueue plugin admin scripts and styles.
173 314 */
174 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 +
175 338 Assets::register_script(
176 339 'jetpack-backup',
177 340 '../build/index.js',
178 341 __FILE__,
@@ -183,9 +346,9 @@
183 346 );
184 347 Assets::enqueue_script( 'jetpack-backup' );
185 348 // Initial JS state including JP Connection data.
186 349 wp_add_inline_script( 'jetpack-backup', self::get_initial_state(), 'before' );
187 - wp_add_inline_script( 'jetpack-backup', Connection_Initial_State::render(), 'before' );
350 + Connection_Initial_State::render_script( 'jetpack-backup' );
188 351
189 352 // Load script for analytics.
190 353 if ( self::can_use_analytics() ) {
191 354 Tracking::register_tracks_functions_scripts( true );
@@ -242,9 +405,9 @@
242 405 'jetpack/v4',
243 406 '/has-backup-plan',
244 407 array(
245 408 'methods' => WP_REST_Server::READABLE,
246 - 'callback' => __CLASS__ . '::has_backup_plan',
409 + 'callback' => __CLASS__ . '::get_backup_plan_state',
247 410 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
248 411 )
249 412 );
250 413
@@ -287,9 +450,9 @@
287 450 register_rest_route(
288 451 'jetpack/v4',
289 452 '/site/dismissed-review-request',
290 453 array(
291 - 'methods' => \WP_REST_Server::EDITABLE,
454 + 'methods' => WP_REST_Server::EDITABLE,
292 455 'callback' => __CLASS__ . '::manage_dismissed_backup_review_request',
293 456 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
294 457 'args' => array(
295 458 'option_name' => array(
@@ -294,8 +457,15 @@
294 457 'args' => array(
295 458 'option_name' => array(
296 459 'required' => true,
297 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' ),
298 468 ),
299 469 'should_dismiss' => array(
300 470 'required' => true,
301 471 'type' => 'boolean',
@@ -314,8 +484,19 @@
314 484 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
315 485 )
316 486 );
317 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 +
318 499 // Get site policies
319 500 register_rest_route(
320 501 'jetpack/v4',
321 502 '/site/backup/policies',
@@ -345,8 +526,19 @@
345 526 ),
346 527 ),
347 528 )
348 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 + );
349 541 }
350 542
351 543 /**
352 544 * The backup calls should only occur from a signed in admin user
@@ -360,19 +552,46 @@
360 552 return current_user_can( 'manage_options' );
361 553 }
362 554
363 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 + /**
364 583 * Get information about recent backups
365 584 *
366 585 * @access public
367 586 * @static
368 587 *
369 - * @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.
370 589 */
371 590 public static function get_recent_backups() {
372 - $blog_id = \Jetpack_Options::get_option( 'id' );
591 + $blog_id = Jetpack_Options::get_option( 'id' );
373 592
374 - $response = Automattic\Jetpack\Connection\Client::wpcom_json_api_request_as_blog(
593 + $response = Client::wpcom_json_api_request_as_blog(
375 594 '/sites/' . $blog_id . '/rewind/backups',
376 595 'v2',
377 596 array(),
378 597 null,
@@ -378,10 +597,12 @@
378 597 null,
379 598 'wpcom'
380 599 );
381 600
382 - if ( 200 !== $response['response']['code'] ) {
383 - 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 );
384 605 }
385 606
386 607 return rest_ensure_response(
387 608 json_decode( $response['body'], true )
@@ -390,55 +611,91 @@
390 611
391 612 /**
392 613 * Hits the wpcom api to check rewind status.
393 614 *
394 - * @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.
395 619 */
396 620 private static function get_rewind_state_from_wpcom() {
397 - static $status = null;
398 -
399 - if ( $status !== null ) {
400 - return $status;
621 + if ( self::$rewind_state !== null ) {
622 + return self::$rewind_state;
401 623 }
402 624
403 625 $site_id = Jetpack_Options::get_option( 'id' );
404 626
405 - $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' );
406 628
407 - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
408 - 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 );
409 636 }
410 637
411 - $body = wp_remote_retrieve_body( $response );
412 - $status = json_decode( $body );
413 - 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;
414 653 }
415 654
416 655 /**
417 - * 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.
418 657 *
419 - * @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.
420 661 */
421 - public static function has_backup_plan() {
662 + public static function get_backup_plan_state() {
422 663 $rewind_data = static::get_rewind_state_from_wpcom();
664 +
423 665 if ( is_wp_error( $rewind_data ) ) {
424 - return false;
666 + return $rewind_data;
425 667 }
426 - return is_object( $rewind_data ) && isset( $rewind_data->state ) && 'unavailable' !== $rewind_data->state;
668 +
669 + return 'unavailable' !== $rewind_data->state;
427 670 }
428 671
429 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 + /**
430 687 * Get an array of backup/scan/anti-spam site capabilities
431 688 *
432 689 * @access public
433 690 * @static
434 691 *
435 - * @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.
436 693 */
437 694 public static function get_backup_capabilities() {
438 - $blog_id = \Jetpack_Options::get_option( 'id' );
695 + $blog_id = Jetpack_Options::get_option( 'id' );
439 696
440 - $response = Automattic\Jetpack\Connection\Client::wpcom_json_api_request_as_user(
697 + $response = Client::wpcom_json_api_request_as_user(
441 698 '/sites/' . $blog_id . '/rewind/capabilities',
442 699 'v2',
443 700 array(),
444 701 null,
@@ -444,14 +701,12 @@
444 701 null,
445 702 'wpcom'
446 703 );
447 704
448 - if ( is_wp_error( $response ) ) {
449 - return null;
450 - }
705 + $response_code = (int) wp_remote_retrieve_response_code( $response );
451 706
452 - if ( 200 !== $response['response']['code'] ) {
453 - return null;
707 + if ( 200 !== $response_code ) {
708 + return self::get_failed_fetch_error( $response_code );
454 709 }
455 710
456 711 return rest_ensure_response(
457 712 json_decode( $response['body'], true )
@@ -463,13 +718,13 @@
463 718 *
464 719 * @access public
465 720 * @static
466 721 *
467 - * @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.
468 723 */
469 724 public static function get_recent_restores() {
470 - $blog_id = \Jetpack_Options::get_option( 'id' );
471 - $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(
472 727 '/sites/' . $blog_id . '/rewind/restores',
473 728 'v2',
474 729 array(),
475 730 null,
@@ -475,9 +730,82 @@
475 730 null,
476 731 'wpcom'
477 732 );
478 733
479 - 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 ) ) {
480 808 return null;
481 809 }
482 810
483 811 return rest_ensure_response(
@@ -487,28 +815,64 @@
487 815
488 816 /**
489 817 * Gets information about the currently promoted backup product.
490 818 *
491 - * @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.
492 822 */
493 823 public static function get_backup_promoted_product_info() {
494 - $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';
495 833 $wpcom_request = wp_remote_get( esc_url_raw( $request_url ) );
496 - $response_code = wp_remote_retrieve_response_code( $wpcom_request );
497 - if ( 200 === $response_code ) {
498 - $products = json_decode( wp_remote_retrieve_body( $wpcom_request ) );
499 - return $products->{self::JETPACK_BACKUP_PROMOTED_PRODUCT};
500 - } else {
501 - // 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 ) {
502 839 return new WP_Error(
503 840 'failed_to_fetch_data',
504 841 esc_html__( 'Unable to fetch the requested data.', 'jetpack-backup-pkg' ),
505 842 array(
506 - '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,
507 846 'request' => $wpcom_request,
508 847 )
509 848 );
510 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;
511 875 }
512 876
513 877 /**
514 878 * Check for user licenses.
@@ -537,16 +901,16 @@
537 901 return $license_found && ! static::has_backup_plan();
538 902 }
539 903
540 904 /**
541 - * Returns the result of `/sites/%d/purchases` endpoint call.
905 + * Returns the result of `/upgrades` endpoint call.
542 906 *
543 - * @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.
544 908 */
545 909 public static function get_site_current_purchases() {
546 910
547 - $request = sprintf( '/sites/%d/purchases', \Jetpack_Options::get_option( 'id' ) );
548 - $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' );
549 913
550 914 // Bail if there was an error or malformed response.
551 915 if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
552 916 return self::get_failed_fetch_error();
@@ -551,10 +915,12 @@
551 915 if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
552 916 return self::get_failed_fetch_error();
553 917 }
554 918
555 - if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
556 - 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 );
557 923 }
558 924
559 925 return rest_ensure_response(
560 926 json_decode( $response['body'], true )
@@ -574,24 +940,24 @@
574 940
575 941 if ( ! $request['should_dismiss'] ) {
576 942
577 943 return rest_ensure_response(
578 - \Jetpack_Options::get_option( 'dismissed_backup_review_' . $request['option_name'] )
944 + Jetpack_Options::get_option( 'dismissed_backup_review_' . $request['option_name'] )
579 945 );
580 946 }
581 947
582 - 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 );
583 949 }
584 950
585 951 /**
586 952 * Get site storage size
587 953 *
588 - * @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.
589 955 */
590 956 public static function get_site_backup_size() {
591 - $blog_id = \Jetpack_Options::get_option( 'id' );
957 + $blog_id = Jetpack_Options::get_option( 'id' );
592 958
593 - $response = Automattic\Jetpack\Connection\Client::wpcom_json_api_request_as_user(
959 + $response = Client::wpcom_json_api_request_as_user(
594 960 '/sites/' . $blog_id . '/rewind/size?force=wpcom',
595 961 'v2',
596 962 array(),
597 963 null,
@@ -597,10 +963,12 @@
597 963 null,
598 964 'wpcom'
599 965 );
600 966
601 - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
602 - 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 );
603 971 }
604 972
605 973 return rest_ensure_response(
606 974 json_decode( $response['body'], true )
@@ -609,15 +977,14 @@
609 977
610 978 /**
611 979 * Get site policies from WPCOM. It includes the storage limit and activity log limit, if apply.
612 980 *
613 - * @return string|WP_Error A JSON object with the site storage policies if the request was successful,
614 - * 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.
615 982 */
616 983 public static function get_site_backup_policies() {
617 - $blog_id = \Jetpack_Options::get_option( 'id' );
984 + $blog_id = Jetpack_Options::get_option( 'id' );
618 985
619 - $response = Automattic\Jetpack\Connection\Client::wpcom_json_api_request_as_user(
986 + $response = Client::wpcom_json_api_request_as_user(
620 987 '/sites/' . $blog_id . '/rewind/policies?force=wpcom',
621 988 'v2',
622 989 array(),
623 990 null,
@@ -623,10 +990,12 @@
623 990 null,
624 991 'wpcom'
625 992 );
626 993
627 - if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
628 - 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 );
629 998 }
630 999
631 1000 return rest_ensure_response(
632 1001 json_decode( $response['body'], true )
@@ -662,8 +1031,9 @@
662 1031 if ( $additional_bytes_needed > $bytes_1tb ) {
663 1032 return $upsell_products[ $bytes_1tb ];
664 1033 }
665 1034
1035 + $matched_bytes = $bytes_10gb;
666 1036 foreach ( $upsell_products as $bytes => $product ) {
667 1037 if ( $bytes > $additional_bytes_needed ) {
668 1038 $matched_bytes = $bytes;
669 1039 break;
@@ -669,12 +1039,8 @@
669 1039 break;
670 1040 }
671 1041 }
672 1042
673 - if ( ! $matched_bytes ) {
674 - $matched_bytes = $bytes_10gb;
675 - }
676 -
677 1043 return $upsell_products[ $matched_bytes ];
678 1044 }
679 1045
680 1046 // For 1 TB we are going to offer 1 TB by default
@@ -688,9 +1054,10 @@
688 1054
689 1055 /**
690 1056 * Get the best addon offer for this site, including pricing details
691 1057 *
692 - * @param WP_Request $request Object including storage usage.
1058 + * @param \WP_REST_Request $request Object including storage usage.
1059 + *
693 1060 * @return string|WP_Error A JSON object with the suggested storage addon details if the request was successful,
694 1061 * or a WP_Error otherwise.
695 1062 */
696 1063 public static function get_site_backup_addon_offer( $request ) {
@@ -718,8 +1085,65 @@
718 1085 return rest_ensure_response( $response );
719 1086 }
720 1087
721 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 + /**
722 1146 * Removes plugin from the connection manager
723 1147 * If it's the last plugin using the connection, the site will be disconnected.
724 1148 *
725 1149 * @access public
@@ -729,5 +1153,206 @@
729 1153 $manager = new Connection_Manager( 'jetpack-backup' );
730 1154 $manager->remove_connection();
731 1155 }
732 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
1357 + }
733 1358 }