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