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