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