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