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