PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.2
Jetpack – WP Security, Backup, Speed, & Growth v16.2
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.2, at jetpack_vendor/automattic/jetpack-backup/src/class-jetpack-backup.php

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