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