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