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