PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3-a.5
Jetpack – WP Security, Backup, Speed, & Growth v16.3-a.5
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 13.8.3 All 506 releases
jetpack / jetpack_vendor / automattic / jetpack-backup / src / class-jetpack-backup.php

class-jetpack-backup.php in Jetpack – WP Security, Backup, Speed, & Growth 16.3-a.5, at jetpack_vendor/automattic/jetpack-backup/src/class-jetpack-backup.php

1,335 lines 41.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Primary class file for the Jetpack Backup plugin.
4 *
5 * @package automattic/jetpack-backup-plugin
6 */
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
14 if ( ! defined( 'ABSPATH' ) ) {
15 exit( 0 );
16 }
17
18 use Automattic\Jetpack\Admin_UI\Admin_Menu;
19 use Automattic\Jetpack\Assets;
20 use Automattic\Jetpack\Backup\V0005\Initial_State as Backup_Initial_State;
21 use Automattic\Jetpack\Config;
22 use Automattic\Jetpack\Connection\Client;
23 use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
24 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
25 use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
26 use Automattic\Jetpack\Constants;
27 use Automattic\Jetpack\JITMS\JITM;
28 use Automattic\Jetpack\My_Jetpack\Wpcom_Products;
29 use Automattic\Jetpack\Status;
30 use Automattic\Jetpack\Terms_Of_Service;
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;
48
49 /**
50 * Class Jetpack_Backup
51 */
52 class Jetpack_Backup {
53
54 /**
55 * Slug.
56 *
57 * @var string
58 */
59 const JETPACK_BACKUP_SLUG = 'jetpack-backup';
60
61 /**
62 * Backup name.
63 *
64 * @var string
65 */
66 const JETPACK_BACKUP_NAME = 'Jetpack Backup';
67
68 /**
69 * Backup URL.
70 *
71 * @var string
72 */
73 const JETPACK_BACKUP_URI = 'https://jetpack.com/jetpack-backup';
74
75 /**
76 * Promoted product.
77 *
78 * @var string
79 */
80 const JETPACK_BACKUP_PROMOTED_PRODUCT = 'jetpack_backup_t1_yearly';
81
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 /**
103 * Licenses product ID.
104 *
105 * @var string
106 */
107 const JETPACK_BACKUP_PRODUCT_IDS = array(
108 2014, // JETPACK_COMPLETE.
109 2015, // JETPACK_COMPLETE_MONTHLY.
110 2016, // JETPACK_SECURITY_TIER_1_YEARLY.
111 2017, // JETPACK_SECURITY_TIER_1_MONTHLY.
112 2019, // JETPACK_SECURITY_TIER_2_YEARLY.
113 2020, // JETPACK_SECURITY_TIER_2_MONTHLY.
114 2112, // JETPACK_BACKUP_TIER_1_YEARLY.
115 2113, // JETPACK_BACKUP_TIER_1_MONTHLY.
116 2114, // JETPACK_BACKUP_TIER_2_YEARLY.
117 2115, // JETPACK_BACKUP_TIER_2_MONTHLY.
118 );
119
120 /**
121 * Jetpack Backup DB version.
122 *
123 * @var string
124 */
125 const JETPACK_BACKUP_DB_VERSION = '2';
126
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 * Constructor.
160 */
161 public static function initialize() {
162 if ( did_action( 'jetpack_backup_initialized' ) ) {
163 return;
164 }
165
166 // Set up the REST authentication hooks.
167 Connection_Rest_Authentication::init();
168
169 add_action( 'rest_api_init', array( __CLASS__, 'register_rest_routes' ) );
170 add_action( 'rest_api_init', array( \Automattic\Jetpack\Backup\V0005\REST\Rest_Controller::class, 'register_routes' ) );
171
172 add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
173 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.
174
175 // Init Jetpack packages.
176 add_action(
177 'plugins_loaded',
178 function () {
179 $config = new Config();
180 // Connection package.
181 $config->ensure(
182 'connection',
183 array(
184 'slug' => self::JETPACK_BACKUP_SLUG,
185 'name' => self::JETPACK_BACKUP_NAME,
186 'url_info' => self::JETPACK_BACKUP_URI,
187 )
188 );
189 // Sync package.
190 $config->ensure( 'sync' );
191
192 // Identity crisis package.
193 $config->ensure( 'identity_crisis' );
194 },
195 1
196 );
197
198 add_action( 'plugins_loaded', array( __CLASS__, 'maybe_upgrade_db' ), 20 );
199
200 add_filter( 'jetpack_connection_user_has_license', array( __CLASS__, 'jetpack_check_user_licenses' ), 10, 3 );
201
202 // Jetpack Backup abilities are registered from `actions.php` at package
203 // autoload time so the surface is available in every consumer that
204 // loads this package (both the standalone Backup plugin and the
205 // Jetpack plugin), not only when `Jetpack_Backup::initialize()` runs.
206
207 /**
208 * Runs right after the Jetpack Backup package is initialized.
209 *
210 * @since 1.3.0
211 */
212 do_action( 'jetpack_backup_initialized' );
213 }
214
215 /**
216 * The page to be added to submenu
217 */
218 public static function add_wp_admin_submenu() {
219 $wp_build_active = self::is_wp_build_dashboard_active();
220 $callback = $wp_build_active
221 ? 'jetpack_backup_jetpack_backup_dashboard_wp_admin_render_page'
222 : array( __CLASS__, 'plugin_settings_page' );
223
224 // The relabel rides the modernized dashboard rather than the filter alone,
225 // so a fallback to the legacy page also falls back to the legacy title.
226 $page_title = $wp_build_active ? 'Jetpack VaultPress Backup' : 'Jetpack Backup';
227 $menu_title = $wp_build_active ? 'VaultPress Backup' : 'Backup'; // Product name, do not translate.
228
229 $page_suffix = Admin_Menu::add_menu(
230 $page_title,
231 $menu_title,
232 'manage_options',
233 self::JETPACK_BACKUP_SLUG,
234 $callback,
235 null,
236 array(
237 'product' => 'backup',
238 'key' => 'jetpack-backup',
239 )
240 );
241
242 if ( $page_suffix ) {
243 add_action( 'load-' . $page_suffix, array( __CLASS__, 'admin_init' ) );
244 }
245 }
246
247 /**
248 * Initialize the admin resources.
249 */
250 public static function admin_init() {
251 add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_admin_scripts' ) );
252
253 if ( self::is_wp_build_dashboard_active() ) {
254 // Notices reflow the dual-pane layout, so clear them but keep our own.
255 // An older jetpack-jitm may predate the helper; the fallback costs the JITM.
256 if ( method_exists( JITM::class, 'suppress_foreign_admin_notices' ) ) {
257 JITM::suppress_foreign_admin_notices();
258 } else {
259 remove_all_actions( 'admin_notices' );
260 remove_all_actions( 'all_admin_notices' );
261 }
262 }
263 }
264
265 /**
266 * Checks current version against version in code and run upgrades if we are running a new version
267 */
268 public static function maybe_upgrade_db() {
269 $current_db_version = get_option( 'jetpack_backup_db_version' );
270 if ( version_compare( $current_db_version, self::JETPACK_BACKUP_DB_VERSION, '<' ) ) {
271 update_option( 'jetpack_backup_db_version', self::JETPACK_BACKUP_DB_VERSION );
272 Jetpack_Backup_Upgrades::upgrade();
273 }
274 }
275
276 /**
277 * Returns whether we are in condition to track to use
278 * Analytics functionality like Tracks, MC, or GA.
279 */
280 public static function can_use_analytics() {
281 $status = new Status();
282 $connection = new Connection_Manager( 'jetpack-backup' );
283 $tracking = new Tracking( 'jetpack', $connection );
284
285 return $tracking->should_enable_tracking( new Terms_Of_Service(), $status );
286 }
287
288 /**
289 * Enqueue plugin admin scripts and styles.
290 */
291 public static function enqueue_admin_scripts() {
292 // This callback is registered via `load-{$page_suffix}` in `add_wp_admin_submenu()`,
293 // so it only fires on the Backup admin page — no need to re-check the page here.
294 if ( self::is_wp_build_dashboard_active() ) {
295 // The i18n loader is registered on every admin page by jetpack-assets but
296 // only enqueued when depended on; the esbuild bundles don't pull it in.
297 // Enqueue it here, before the early return, so the wp-build dashboard's
298 // init module can download its JS translation catalogs.
299 if ( wp_script_is( 'wp-jp-i18n-loader', 'registered' ) ) {
300 wp_enqueue_script( 'wp-jp-i18n-loader' );
301 }
302
303 // The esbuild bundles don't declare the Tracks client as a dependency
304 // either, so it never reaches the page on its own.
305 if ( self::can_use_analytics() ) {
306 Tracking::register_tracks_functions_scripts( true );
307 }
308
309 // wp-build manages its own enqueue pipeline. The legacy script and
310 // its initial state are skipped for the wp-build dashboard.
311 return;
312 }
313
314 Assets::register_script(
315 'jetpack-backup',
316 '../build/index.js',
317 __FILE__,
318 array(
319 'in_footer' => true,
320 'textdomain' => 'jetpack-backup-pkg',
321 )
322 );
323 Assets::enqueue_script( 'jetpack-backup' );
324 // Initial JS state including JP Connection data.
325 wp_add_inline_script( 'jetpack-backup', self::get_initial_state(), 'before' );
326 Connection_Initial_State::render_script( 'jetpack-backup' );
327
328 // Load script for analytics.
329 if ( self::can_use_analytics() ) {
330 Tracking::register_tracks_functions_scripts( true );
331 }
332 }
333
334 /**
335 * Main plugin settings page.
336 */
337 public static function plugin_settings_page() {
338 ?>
339 <div id="jetpack-backup-root"></div>
340 <?php
341 }
342
343 /**
344 * Return the rendered initial state JavaScript code.
345 *
346 * @return string
347 */
348 private static function get_initial_state() {
349 return ( new Backup_Initial_State() )->render();
350 }
351
352 /**
353 * Register REST API
354 */
355 public static function register_rest_routes() {
356
357 // Get information on most recent 10 backups.
358 register_rest_route(
359 'jetpack/v4',
360 '/backups',
361 array(
362 'methods' => WP_REST_Server::READABLE,
363 'callback' => __CLASS__ . '::get_recent_backups',
364 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
365 )
366 );
367
368 // Get site backup/scan/anti-spam capabilities.
369 register_rest_route(
370 'jetpack/v4',
371 '/backup-capabilities',
372 array(
373 'methods' => WP_REST_Server::READABLE,
374 'callback' => __CLASS__ . '::get_backup_capabilities',
375 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
376 )
377 );
378
379 // Get whether the site has a backup plan
380 register_rest_route(
381 'jetpack/v4',
382 '/has-backup-plan',
383 array(
384 'methods' => WP_REST_Server::READABLE,
385 'callback' => __CLASS__ . '::get_backup_plan_state',
386 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
387 )
388 );
389
390 // Get site rewind data.
391 register_rest_route(
392 'jetpack/v4',
393 '/restores',
394 array(
395 'methods' => WP_REST_Server::READABLE,
396 'callback' => __CLASS__ . '::get_recent_restores',
397 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
398 )
399 );
400
401 // Get information on site products.
402 // Backup plugin version of /site/purchases from JP plugin.
403 // Revert once this route and MyPlan component are extracted to a common package.
404 register_rest_route(
405 'jetpack/v4',
406 '/site/current-purchases',
407 array(
408 'methods' => WP_REST_Server::READABLE,
409 'callback' => __CLASS__ . '::get_site_current_purchases',
410 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
411 )
412 );
413
414 // Get currently promoted product from the product's endpoint.
415 register_rest_route(
416 'jetpack/v4',
417 '/backup-promoted-product-info',
418 array(
419 'methods' => WP_REST_Server::READABLE,
420 'callback' => __CLASS__ . '::get_backup_promoted_product_info',
421 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
422 )
423 );
424
425 // Get and set value of dismissed_backup_review_request option
426 register_rest_route(
427 'jetpack/v4',
428 '/site/dismissed-review-request',
429 array(
430 'methods' => WP_REST_Server::EDITABLE,
431 'callback' => __CLASS__ . '::manage_dismissed_backup_review_request',
432 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
433 'args' => array(
434 'option_name' => array(
435 'required' => true,
436 'type' => 'string',
437 // The two names `Jetpack_Options` recognises. Anything else
438 // falls through its allowlist to a `trigger_error()` and is
439 // stored nowhere, so an unlisted reason would dismiss
440 // nothing while answering as though it had — and on a site
441 // with `display_errors` on, the warning is printed ahead of
442 // the JSON and the response no longer parses.
443 'enum' => array( 'restore', 'backups' ),
444 ),
445 'should_dismiss' => array(
446 'required' => true,
447 'type' => 'boolean',
448 ),
449 ),
450 )
451 );
452
453 // Get site size
454 register_rest_route(
455 'jetpack/v4',
456 '/site/backup/size',
457 array(
458 'methods' => WP_REST_Server::READABLE,
459 'callback' => __CLASS__ . '::get_site_backup_size',
460 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
461 )
462 );
463
464 // Get backup schedule time
465 register_rest_route(
466 'jetpack/v4',
467 '/site/backup/schedule',
468 array(
469 'methods' => WP_REST_Server::READABLE,
470 'callback' => __CLASS__ . '::get_site_backup_schedule_time',
471 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
472 )
473 );
474
475 // Get site policies
476 register_rest_route(
477 'jetpack/v4',
478 '/site/backup/policies',
479 array(
480 'methods' => WP_REST_Server::READABLE,
481 'callback' => __CLASS__ . '::get_site_backup_policies',
482 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
483 )
484 );
485
486 // Get site add-on offer
487 register_rest_route(
488 'jetpack/v4',
489 '/site/backup/addon-offer',
490 array(
491 'methods' => WP_REST_Server::READABLE,
492 'callback' => __CLASS__ . '::get_site_backup_addon_offer',
493 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
494 'args' => array(
495 'storage_size' => array(
496 'required' => true,
497 'type' => 'numeric',
498 ),
499 'storage_limit' => array(
500 'required' => true,
501 'type' => 'numeric',
502 ),
503 ),
504 )
505 );
506
507 // Enqueue a new backup
508 register_rest_route(
509 'jetpack/v4',
510 '/site/backup/enqueue',
511 array(
512 'methods' => WP_REST_Server::CREATABLE,
513 'callback' => __CLASS__ . '::enqueue_backup',
514 'permission_callback' => __CLASS__ . '::backups_permissions_callback',
515 )
516 );
517 }
518
519 /**
520 * The backup calls should only occur from a signed in admin user
521 *
522 * @access public
523 * @static
524 *
525 * @return true|WP_Error
526 */
527 public static function backups_permissions_callback() {
528 return current_user_can( 'manage_options' );
529 }
530
531 /**
532 * The error a route answers with when its WordPress.com request did not come
533 * back with a 200.
534 *
535 * Returning `null` instead — which these routes used to do — is served as an
536 * HTTP 200 carrying a `null` body, so `apiFetch` resolves and nothing throws.
537 * A WordPress.com blip then reaches the dashboard as an empty success, which
538 * is how a paying customer ends up looking at the first-run screen. A
539 * WP_Error makes the REST layer answer with a status, so every caller's
540 * existing failure path runs.
541 *
542 * @param int $status The upstream response code, already cast to an int, or 0
543 * when the request never reached WordPress.com.
544 * @return WP_Error
545 */
546 private static function get_failed_fetch_error( $status = 0 ) {
547 return new WP_Error(
548 'failed_to_fetch_data',
549 esc_html__( 'Unable to fetch the requested data.', 'jetpack-backup-pkg' ),
550 array(
551 // A transport failure has no status at all, and `status_header( 0 )`
552 // emits an invalid status line — so anything falsy becomes a 500.
553 'status' => $status ? $status : 500,
554 )
555 );
556 }
557
558 /**
559 * Get information about recent backups
560 *
561 * @access public
562 * @static
563 *
564 * @return \WP_REST_Response|WP_Error The recent backups, or a WP_Error if WordPress.com could not be reached.
565 */
566 public static function get_recent_backups() {
567 $blog_id = Jetpack_Options::get_option( 'id' );
568
569 $response = Client::wpcom_json_api_request_as_blog(
570 '/sites/' . $blog_id . '/rewind/backups',
571 'v2',
572 array(),
573 null,
574 'wpcom'
575 );
576
577 $response_code = (int) wp_remote_retrieve_response_code( $response );
578
579 if ( 200 !== $response_code ) {
580 return self::get_failed_fetch_error( $response_code );
581 }
582
583 return rest_ensure_response(
584 json_decode( $response['body'], true )
585 );
586 }
587
588 /**
589 * Hits the wpcom api to check rewind status.
590 *
591 * Bounded well clear of a healthy round trip; `Client`'s 10s default is too
592 * long for the synchronous `authorize_redirect` this sits on.
593 *
594 * @return object|WP_Error The decoded rewind state, or a WP_Error if WordPress.com could not be read.
595 */
596 private static function get_rewind_state_from_wpcom() {
597 if ( self::$rewind_state !== null ) {
598 return self::$rewind_state;
599 }
600
601 $site_id = Jetpack_Options::get_option( 'id' );
602
603 $response = Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d/rewind', $site_id ) . '?force=wpcom', '2', array( 'timeout' => 5 ), null, 'wpcom' );
604
605 // Cast: `wp_remote_retrieve_response_code()` hands back whatever the
606 // transport put there, and a numeric-string `'200'` fails this strict
607 // comparison.
608 $response_code = (int) wp_remote_retrieve_response_code( $response );
609
610 if ( 200 !== $response_code ) {
611 return self::get_failed_fetch_error( $response_code );
612 }
613
614 $state = json_decode( wp_remote_retrieve_body( $response ) );
615
616 // A 200 with no `state` is a read that failed, not a site without a
617 // plan. Caching it would hold that answer for the rest of the request;
618 // refusing lets a later caller ask again and get a real one.
619 if ( ! is_object( $state ) || ! isset( $state->state ) ) {
620 return new WP_Error(
621 'rewind_state_unreadable',
622 esc_html__( 'Unable to read the backup plan details for this site.', 'jetpack-backup-pkg' ),
623 array( 'status' => 500 )
624 );
625 }
626
627 self::$rewind_state = $state;
628 return self::$rewind_state;
629 }
630
631 /**
632 * Checks whether the site supports the product, reporting an unreadable answer as an error.
633 *
634 * @since 5.0.1
635 *
636 * @return bool|WP_Error True when the site has Backup, or a WP_Error if WordPress.com could not be read.
637 */
638 public static function get_backup_plan_state() {
639 $rewind_data = static::get_rewind_state_from_wpcom();
640
641 if ( is_wp_error( $rewind_data ) ) {
642 return $rewind_data;
643 }
644
645 return 'unavailable' !== $rewind_data->state;
646 }
647
648 /**
649 * Checks whether the current plan (or purchases) of the site already supports the product
650 *
651 * Answers a plan it could not read as absent, which is the one place that
652 * decision is made for every `bool` caller.
653 *
654 * @return bool
655 */
656 public static function has_backup_plan() {
657 $state = static::get_backup_plan_state();
658
659 return ! is_wp_error( $state ) && $state;
660 }
661
662 /**
663 * Get an array of backup/scan/anti-spam site capabilities
664 *
665 * @access public
666 * @static
667 *
668 * @return \WP_REST_Response|WP_Error The site capabilities, or a WP_Error if WordPress.com could not be reached.
669 */
670 public static function get_backup_capabilities() {
671 $blog_id = Jetpack_Options::get_option( 'id' );
672
673 $response = Client::wpcom_json_api_request_as_user(
674 '/sites/' . $blog_id . '/rewind/capabilities',
675 'v2',
676 array(),
677 null,
678 'wpcom'
679 );
680
681 $response_code = (int) wp_remote_retrieve_response_code( $response );
682
683 if ( 200 !== $response_code ) {
684 return self::get_failed_fetch_error( $response_code );
685 }
686
687 return rest_ensure_response(
688 json_decode( $response['body'], true )
689 );
690 }
691
692 /**
693 * Get information about recent restores
694 *
695 * @access public
696 * @static
697 *
698 * @return \WP_REST_Response|WP_Error The recent restores, or a WP_Error if WordPress.com could not be reached.
699 */
700 public static function get_recent_restores() {
701 $blog_id = Jetpack_Options::get_option( 'id' );
702 $response = Client::wpcom_json_api_request_as_blog(
703 '/sites/' . $blog_id . '/rewind/restores',
704 'v2',
705 array(),
706 null,
707 'wpcom'
708 );
709
710 $response_code = (int) wp_remote_retrieve_response_code( $response );
711
712 if ( 200 !== $response_code ) {
713 return self::get_failed_fetch_error( $response_code );
714 }
715
716 return rest_ensure_response(
717 json_decode( $response['body'], true )
718 );
719 }
720
721 /**
722 * Query backup-completion events from the wpcom activity-log via the
723 * general `/sites/<id>/activity` endpoint with the action filter pinned
724 * to backup-completion event names. This endpoint paginates real-ly
725 * (Elasticsearch `from` offset under the hood) — the `/activity/rewindable`
726 * sibling looks like a more natural fit but hardcodes `page: 1,
727 * totalPages: 1` and ignores the `page` parameter.
728 *
729 * Auth: signs as user. The endpoint gates on the requesting WP user
730 * being an administrator of the blog (see
731 * sites-activity.php::readable_permission_check); blog-level tokens
732 * return 401.
733 *
734 * Returned shape (success): a W3C ActivityStreams envelope:
735 * {
736 * "@context": ..., "type": "OrderedCollection", "totalItems": int,
737 * "page": int, "totalPages": int, "itemsPerPage": int,
738 * "orderedItems": [ <event>, ... ]
739 * }
740 * Each event has at least `published`, `rewind_id`, `is_rewindable`,
741 * `name`, `status`, `summary`.
742 *
743 * @param array $args Query args passed through to wpcom. Supported keys:
744 * `after` (ISO 8601), `before` (ISO 8601), `on` (ISO 8601),
745 * `date_range`, `number` (max 1000), `page` (1-based),
746 * `sort_order` ('asc'|'desc'). Any `action` key is
747 * overridden with the curated backup-completion list.
748 * @return array|\WP_REST_Response|null
749 */
750 public static function list_backup_events( array $args = array() ) {
751 $blog_id = Jetpack_Options::get_option( 'id' );
752
753 // Curated set of activity actions that represent "a backup completed".
754 // Mirrors `WPCOM_REST_API_V2_Endpoint_Site_Activity::$backup_action_names`.
755 // Pinned here (and overriding any caller-supplied `action`) so the
756 // helper is always scoped to backups regardless of what the caller passes.
757 $args['action'] = array(
758 'backup_complete_full',
759 'backup_complete_initial',
760 'backup_only_complete_full',
761 'backup_only_complete_initial',
762 'rewind__backup_complete_full',
763 'rewind__backup_complete_initial',
764 'rewind__backup_only_complete_full',
765 'rewind__backup_only_complete_initial',
766 );
767
768 $path = '/sites/' . (int) $blog_id . '/activity?' . http_build_query( $args );
769
770 $response = Client::wpcom_json_api_request_as_user(
771 $path,
772 'v2',
773 array(),
774 null,
775 'wpcom'
776 );
777
778 // Cast, as everywhere else this package reads a status. Uncast, a
779 // numeric-string `'200'` discards a good activity page and the
780 // `jetpack-backup/list-backup-events` ability reports that the site
781 // has completed no backups — `unwrap_response()` flattens this
782 // `null` into an empty list, which is a claim rather than an error.
783 if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
784 return null;
785 }
786
787 return rest_ensure_response(
788 json_decode( $response['body'], true )
789 );
790 }
791
792 /**
793 * Gets information about the currently promoted backup product.
794 *
795 * Answers from a per-locale transient when one is warm; failures are not cached.
796 *
797 * @return object|WP_Error The promoted product, or a WP_Error if it could not be read.
798 */
799 public static function get_backup_promoted_product_info() {
800 $locale = get_user_locale();
801 $transient_key = self::PROMOTED_PRODUCT_TRANSIENT_PREFIX . sanitize_key( $locale );
802 $cached = get_transient( $transient_key );
803
804 if ( false !== $cached ) {
805 return $cached;
806 }
807
808 $request_url = 'https://public-api.wordpress.com/rest/v1.1/products?locale=' . $locale . '&type=jetpack';
809 $wpcom_request = wp_remote_get( esc_url_raw( $request_url ) );
810 // Cast: the transport may report the status as a numeric string, which
811 // a strict comparison against 200 sends down the failure path.
812 $response_code = (int) wp_remote_retrieve_response_code( $wpcom_request );
813
814 if ( 200 !== $response_code ) {
815 return new WP_Error(
816 'failed_to_fetch_data',
817 esc_html__( 'Unable to fetch the requested data.', 'jetpack-backup-pkg' ),
818 array(
819 // A transport failure has no status at all; reporting 0 would
820 // leave the REST layer with nothing to serve.
821 'status' => $response_code ? $response_code : 500,
822 'request' => $wpcom_request,
823 )
824 );
825 }
826
827 $products = json_decode( wp_remote_retrieve_body( $wpcom_request ) );
828
829 // A 200 is not a promise that the promoted product is in the body. A
830 // truncated response decodes to null, and the slug is a constant here
831 // but a catalogue entry upstream — retiring it there leaves this a 200
832 // with the key absent. Reading through either emits a PHP warning and
833 // yields null, which the route then serves as a 200 carrying `null`:
834 // indistinguishable, to a caller, from a priced answer it failed to
835 // read. Refusing says which of the two happened.
836 if ( ! is_object( $products ) || ! isset( $products->{ self::JETPACK_BACKUP_PROMOTED_PRODUCT } ) ) {
837 return new WP_Error(
838 'promoted_product_unreadable',
839 esc_html__( 'Unable to read the promoted product information.', 'jetpack-backup-pkg' ),
840 array( 'status' => 500 )
841 );
842 }
843
844 $product = $products->{ self::JETPACK_BACKUP_PROMOTED_PRODUCT };
845
846 // Must stay below both guards: a cached failure would leave the no-plan
847 // screen without a price for the whole TTL after WordPress.com recovered.
848 set_transient( $transient_key, $product, self::PROMOTED_PRODUCT_CACHE_TTL );
849
850 return $product;
851 }
852
853 /**
854 * Check for user licenses.
855 *
856 * @param boolean $has_license If the user already has a license found.
857 * @param array $licenses List of unattached licenses belonging to the user.
858 * @param string $plugin_slug The plugin that initiated the flow.
859 *
860 * @return boolean
861 */
862 public static function jetpack_check_user_licenses( $has_license, $licenses, $plugin_slug ) {
863 if ( $plugin_slug !== static::JETPACK_BACKUP_SLUG || $has_license ) {
864 return $has_license;
865 }
866
867 $license_found = false;
868
869 foreach ( $licenses as $license ) {
870 if ( in_array( $license->product_id, static::JETPACK_BACKUP_PRODUCT_IDS, true ) ) {
871 $license_found = true;
872 break;
873 }
874 }
875
876 // Checking for existing backup plan is costly, so only check if there's an appropriate license.
877 return $license_found && ! static::has_backup_plan();
878 }
879
880 /**
881 * Returns the result of `/upgrades` endpoint call.
882 *
883 * @return \WP_REST_Response|WP_Error The site purchases, or a WP_Error if WordPress.com could not be reached.
884 */
885 public static function get_site_current_purchases() {
886
887 $request = sprintf( '/upgrades?site=%d', Jetpack_Options::get_option( 'id' ) );
888 $response = Client::wpcom_json_api_request_as_blog( $request, '1.2' );
889
890 // Bail if there was an error or malformed response.
891 if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
892 return self::get_failed_fetch_error();
893 }
894
895 $response_code = (int) wp_remote_retrieve_response_code( $response );
896
897 if ( 200 !== $response_code ) {
898 return self::get_failed_fetch_error( $response_code );
899 }
900
901 return rest_ensure_response(
902 json_decode( $response['body'], true )
903 );
904 }
905
906 /**
907 * Set value of the dismissed_backup_review_request Jetack option.
908 * Get value if should_dismiss is false
909 *
910 * @access public
911 * @static
912 * @param array $request arguments should_dismiss and option_name.
913 * @return bool value of option if value is requested | updated or not if value is updated.
914 */
915 public static function manage_dismissed_backup_review_request( $request ) {
916
917 if ( ! $request['should_dismiss'] ) {
918
919 return rest_ensure_response(
920 Jetpack_Options::get_option( 'dismissed_backup_review_' . $request['option_name'] )
921 );
922 }
923
924 return Jetpack_Options::update_option( 'dismissed_backup_review_' . $request['option_name'], true );
925 }
926
927 /**
928 * Get site storage size
929 *
930 * @return \WP_REST_Response|WP_Error The site storage size, or a WP_Error if WordPress.com could not be reached.
931 */
932 public static function get_site_backup_size() {
933 $blog_id = Jetpack_Options::get_option( 'id' );
934
935 $response = Client::wpcom_json_api_request_as_user(
936 '/sites/' . $blog_id . '/rewind/size?force=wpcom',
937 'v2',
938 array(),
939 null,
940 'wpcom'
941 );
942
943 $response_code = (int) wp_remote_retrieve_response_code( $response );
944
945 if ( 200 !== $response_code ) {
946 return self::get_failed_fetch_error( $response_code );
947 }
948
949 return rest_ensure_response(
950 json_decode( $response['body'], true )
951 );
952 }
953
954 /**
955 * Get site policies from WPCOM. It includes the storage limit and activity log limit, if apply.
956 *
957 * @return \WP_REST_Response|WP_Error The site storage policies, or a WP_Error if WordPress.com could not be reached.
958 */
959 public static function get_site_backup_policies() {
960 $blog_id = Jetpack_Options::get_option( 'id' );
961
962 $response = Client::wpcom_json_api_request_as_user(
963 '/sites/' . $blog_id . '/rewind/policies?force=wpcom',
964 'v2',
965 array(),
966 null,
967 'wpcom'
968 );
969
970 $response_code = (int) wp_remote_retrieve_response_code( $response );
971
972 if ( 200 !== $response_code ) {
973 return self::get_failed_fetch_error( $response_code );
974 }
975
976 return rest_ensure_response(
977 json_decode( $response['body'], true )
978 );
979 }
980
981 /**
982 * Get suggested storage addon based on storage usage
983 *
984 * @param int $bytes_used Storage used.
985 * @param int $bytes_available Storage limit.
986 * @return string Suggested addon storage slug
987 */
988 public static function get_storage_addon_upsell_slug( $bytes_used, $bytes_available ) {
989 $bytes_10gb = 10 * 1024 * 1024 * 1024; // 10GB in bytes
990 $bytes_100gb = 100 * 1024 * 1024 * 1024; // 100GB in bytes
991 $bytes_1tb = 1024 * 1024 * 1024 * 1024; // 1TB in bytes
992
993 $upsell_products = array(
994 $bytes_10gb => 'jetpack_backup_addon_storage_10gb_monthly',
995 $bytes_100gb => 'jetpack_backup_addon_storage_100gb_monthly',
996 $bytes_1tb => 'jetpack_backup_addon_storage_1tb_monthly',
997 );
998
999 // If usage has crossed over the storage limit, then dynamically calculate the upgrade option
1000 if ( $bytes_used > $bytes_available ) {
1001 $additional_bytes_used = $bytes_used - $bytes_available;
1002
1003 // Add aditional 25% buffer
1004 $additional_bytes_needed = $additional_bytes_used + $additional_bytes_used * 0.25;
1005
1006 // Since 1TB is our max upgrade but the additional storage needed is greater than 1TB, then just return 1TB
1007 if ( $additional_bytes_needed > $bytes_1tb ) {
1008 return $upsell_products[ $bytes_1tb ];
1009 }
1010
1011 $matched_bytes = $bytes_10gb;
1012 foreach ( $upsell_products as $bytes => $product ) {
1013 if ( $bytes > $additional_bytes_needed ) {
1014 $matched_bytes = $bytes;
1015 break;
1016 }
1017 }
1018
1019 return $upsell_products[ $matched_bytes ];
1020 }
1021
1022 // For 1 TB we are going to offer 1 TB by default
1023 if ( $bytes_1tb === $bytes_available ) {
1024 return $upsell_products[ $bytes_1tb ];
1025 }
1026
1027 // Otherwise, we are going to offer 10 GB
1028 return $upsell_products[ $bytes_10gb ];
1029 }
1030
1031 /**
1032 * Get the best addon offer for this site, including pricing details
1033 *
1034 * @param \WP_REST_Request $request Object including storage usage.
1035 *
1036 * @return string|WP_Error A JSON object with the suggested storage addon details if the request was successful,
1037 * or a WP_Error otherwise.
1038 */
1039 public static function get_site_backup_addon_offer( $request ) {
1040 $suggested_addon = self::get_storage_addon_upsell_slug(
1041 $request['storage_size'],
1042 $request['storage_limit']
1043 );
1044
1045 $addons_size_text_map = array(
1046 'jetpack_backup_addon_storage_10gb_monthly' => '10GB',
1047 'jetpack_backup_addon_storage_100gb_monthly' => '100GB',
1048 'jetpack_backup_addon_storage_1tb_monthly' => '1TB',
1049 );
1050
1051 // Fetch addon storage price information
1052 $pricing_info = Wpcom_Products::get_product_pricing( $suggested_addon );
1053
1054 // Response
1055 $response = array(
1056 'slug' => $suggested_addon,
1057 'size_text' => $addons_size_text_map[ $suggested_addon ],
1058 'pricing' => $pricing_info,
1059 );
1060
1061 return rest_ensure_response( $response );
1062 }
1063
1064 /**
1065 * Enqueue a new backup on demand
1066 *
1067 * @return \WP_REST_Response|WP_Error The enqueue result, or a WP_Error if WordPress.com could not be reached.
1068 */
1069 public static function enqueue_backup() {
1070 $blog_id = Jetpack_Options::get_option( 'id' );
1071 $endpoint = sprintf( '/sites/%d/rewind/backups/enqueue', $blog_id );
1072
1073 $response = Client::wpcom_json_api_request_as_user(
1074 $endpoint,
1075 'v2',
1076 array(
1077 'method' => 'POST',
1078 ),
1079 null,
1080 'wpcom'
1081 );
1082
1083 $response_code = (int) wp_remote_retrieve_response_code( $response );
1084
1085 if ( 200 !== $response_code ) {
1086 return self::get_failed_fetch_error( $response_code );
1087 }
1088
1089 return rest_ensure_response(
1090 json_decode( $response['body'], true )
1091 );
1092 }
1093
1094 /**
1095 * Get site backup schedule time
1096 *
1097 * @return \WP_REST_Response|WP_Error The backup schedule time, or a WP_Error if WordPress.com could not be reached.
1098 */
1099 public static function get_site_backup_schedule_time() {
1100 $blog_id = Jetpack_Options::get_option( 'id' );
1101
1102 $response = Client::wpcom_json_api_request_as_user(
1103 '/sites/' . $blog_id . '/rewind/scheduled',
1104 'v2',
1105 array(),
1106 null,
1107 'wpcom'
1108 );
1109
1110 $response_code = (int) wp_remote_retrieve_response_code( $response );
1111
1112 if ( 200 !== $response_code ) {
1113 return self::get_failed_fetch_error( $response_code );
1114 }
1115
1116 return rest_ensure_response(
1117 json_decode( $response['body'], true )
1118 );
1119 }
1120
1121 /**
1122 * Removes plugin from the connection manager
1123 * If it's the last plugin using the connection, the site will be disconnected.
1124 *
1125 * @access public
1126 * @static
1127 */
1128 public static function plugin_deactivation() {
1129 $manager = new Connection_Manager( 'jetpack-backup' );
1130 $manager->remove_connection();
1131 }
1132
1133 /**
1134 * Load wp-build when modernization is enabled on the Backup admin page.
1135 *
1136 * @return void
1137 */
1138 public static function maybe_load_wp_build() {
1139 if ( ! self::is_modernized() || ! self::is_backup_admin_request() ) {
1140 return;
1141 }
1142
1143 self::load_wp_build_with_screen_alias();
1144
1145 // wp-build registers standalone modules (e.g. the init module) on
1146 // wp_default_scripts, which has already fired by admin_menu. Register them
1147 // directly so the init module makes it into the import map.
1148 if ( function_exists( 'jetpack_backup_register_script_modules' ) ) {
1149 jetpack_backup_register_script_modules(); // @phan-suppress-current-line PhanUndeclaredFunction -- Checked with function_exists(); defined in the generated build/modules.php, which Phan excludes.
1150 }
1151
1152 add_action( 'admin_print_scripts', array( __CLASS__, 'render_connection_initial_state' ), 1 );
1153 }
1154
1155 /**
1156 * Emit `window.JP_CONNECTION_INITIAL_STATE` inline on the modernized
1157 * Backup admin page.
1158 *
1159 * The modernized enqueue path short-circuits before the legacy
1160 * `Connection_Initial_State::render_script()` call, so without this
1161 * the React `<Gates>` component never sees the connection state and
1162 * sits on its loading skeleton forever. We emit the same JS payload
1163 * the legacy path emits, just outside of a registered script handle
1164 * (wp-build's handles aren't reliable here, and the global is
1165 * page-scoped — any tag setting it works).
1166 *
1167 * @return void
1168 */
1169 public static function render_connection_initial_state() {
1170 echo '<script id="jetpack-backup-connection-initial-state">'
1171 . Connection_Initial_State::render() // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render() returns pre-escaped JSON.
1172 . '</script>';
1173 }
1174
1175 /**
1176 * Load the wp-build entry file and register its polyfills.
1177 *
1178 * Only called on `?page=jetpack-backup` admin requests when `is_modernized()`
1179 * is true. Keeps wp-build off every other request.
1180 *
1181 * @return void
1182 */
1183 private static function load_wp_build() {
1184 $build_index = dirname( __DIR__ ) . '/build/build.php';
1185
1186 if ( ! file_exists( $build_index ) ) {
1187 return;
1188 }
1189
1190 require_once $build_index;
1191
1192 \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::register(
1193 'jetpack-backup',
1194 array_merge(
1195 \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::SCRIPT_HANDLES,
1196 \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills::MODULE_IDS
1197 )
1198 );
1199 }
1200
1201 /**
1202 * Load wp-build with the screen ID aliased across its generated enqueue check.
1203 *
1204 * @see WP_Build_Screen_Id::load_with_alias()
1205 * @return void
1206 */
1207 private static function load_wp_build_with_screen_alias() {
1208 // Fallback: an older wp-build-polyfills under the jetpack-autoloader may predate load_with_alias().
1209 if ( method_exists( \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id::class, 'load_with_alias' ) ) {
1210 \Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Screen_Id::load_with_alias(
1211 array( __CLASS__, 'alias_screen_id_for_wp_build' ),
1212 array( __CLASS__, 'restore_screen_id_after_wp_build' ),
1213 function () {
1214 self::load_wp_build();
1215 }
1216 );
1217 return;
1218 }
1219
1220 add_action( 'admin_enqueue_scripts', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
1221 self::load_wp_build();
1222 add_action( 'admin_enqueue_scripts', array( __CLASS__, 'restore_screen_id_after_wp_build' ) );
1223 }
1224
1225 /**
1226 * Alias the current screen ID to satisfy wp-build's auto-generated enqueue check.
1227 *
1228 * Wp-build's `<page>-wp-admin` enqueue callback enqueues only when the screen ID
1229 * matches the wp-build page slug (`jetpack-backup-dashboard`). Our WP-admin
1230 * menu slug stays `jetpack-backup`, so we mutate the screen object in place
1231 * to make the check pass without changing the user-facing URL.
1232 *
1233 * Hooked only when modernization is on AND we're on the Backup admin page,
1234 * so this never affects any other request.
1235 *
1236 * @since 5.0.4 Takes no argument; hooked on `admin_enqueue_scripts`.
1237 *
1238 * @return void
1239 */
1240 public static function alias_screen_id_for_wp_build() {
1241 $screen = get_current_screen();
1242 if ( ! $screen ) {
1243 return;
1244 }
1245
1246 self::$wp_build_original_screen_id = $screen->id;
1247 $screen->id = 'jetpack-backup-dashboard';
1248 }
1249
1250 /**
1251 * Undo alias_screen_id_for_wp_build(), so code after the generated check sees the real screen ID.
1252 *
1253 * @since 5.0.4
1254 *
1255 * @return void
1256 */
1257 public static function restore_screen_id_after_wp_build() {
1258 $screen = get_current_screen();
1259 if ( ! $screen || null === self::$wp_build_original_screen_id ) {
1260 return;
1261 }
1262
1263 $screen->id = self::$wp_build_original_screen_id;
1264 self::$wp_build_original_screen_id = null;
1265 }
1266
1267 /**
1268 * Returns the modernization filter's value, which defaults to the internal preview.
1269 *
1270 * @since 4.3.14 Changed from private to public; the REST bridges gate their route registration on it.
1271 *
1272 * @return bool
1273 */
1274 public static function is_modernized() {
1275 return (bool) apply_filters( self::MODERNIZATION_FILTER, self::is_internal_preview() );
1276 }
1277
1278 /**
1279 * Whether an internal user on the A8C proxy previews the dashboard. Not an authorization check.
1280 *
1281 * The proxy is checked first, so other requests never make the connected-user lookup.
1282 *
1283 * @return bool
1284 */
1285 private static function is_internal_preview() {
1286 if ( ! Constants::is_true( 'AT_PROXIED_REQUEST' ) ) {
1287 return false;
1288 }
1289
1290 if ( function_exists( 'wpcomsh_is_site_sticker_active' ) && wpcomsh_is_site_sticker_active( self::LEGACY_DASHBOARD_STICKER ) ) {
1291 return false;
1292 }
1293
1294 $user_data = ( new Connection_Manager() )->get_connected_user_data();
1295 $email = is_array( $user_data ) && ! empty( $user_data['email'] ) ? strtolower( (string) $user_data['email'] ) : '';
1296
1297 return str_ends_with( $email, '@automattic.com' ) || str_ends_with( $email, '@a8c.com' );
1298 }
1299
1300 /**
1301 * Returns true when `is_modernized()` is true AND the wp-build dashboard loaded.
1302 *
1303 * `build/` is gitignored, so the render function is absent in any unbuilt checkout
1304 * and in any release whose wp-build step failed. Every consumer of the modernized
1305 * surface has to agree on this, or the menu falls back to the legacy page while the
1306 * enqueue path skips the legacy script — an empty div with no JS.
1307 *
1308 * Only meaningful once `maybe_load_wp_build()` has run. It is hooked on `admin_menu`
1309 * at the same priority as `add_wp_admin_submenu()`, so registration order — not
1310 * priority — is what keeps it first. Do not reorder those two `add_action()` calls.
1311 *
1312 * @return bool
1313 */
1314 private static function is_wp_build_dashboard_active() {
1315 return self::is_modernized() && function_exists( 'jetpack_backup_jetpack_backup_dashboard_wp_admin_render_page' );
1316 }
1317
1318 /**
1319 * Returns true when the current request targets the Backup admin page.
1320 *
1321 * Used to scope wp-build loading to the one page that needs it. The
1322 * `$_GET['page']` value is populated by wp-admin/admin.php before any of
1323 * our hooks fire, so this check is reliable from `initialize()` onwards.
1324 *
1325 * @return bool
1326 */
1327 private static function is_backup_admin_request() {
1328 if ( ! is_admin() || ! isset( $_GET['page'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1329 return false;
1330 }
1331
1332 return sanitize_text_field( wp_unslash( $_GET['page'] ) ) === self::JETPACK_BACKUP_SLUG; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1333 }
1334 }
1335