Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
74.29% covered (warning)
74.29%
78 / 105
60.00% covered (warning)
60.00%
9 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_Backup
75.73% covered (warning)
75.73%
78 / 103
60.00% covered (warning)
60.00%
9 / 15
88.19
0.00% covered (danger)
0.00%
0 / 1
 is_atomic
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 should_register
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 filter_jetpack_backup_dashboard
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_page_title
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_menu_title
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_initial_state
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
3.00
 has_backup_feature
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 is_transfer_in_progress
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
42
 get_eligibility
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 get_state
50.00% covered (danger)
50.00%
3 / 6
0.00% covered (danger)
0.00%
0 / 1
6.00
 get_transfer_errors
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
6
 get_transfer_warnings
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
11.02
 get_upgrade_url
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 get_post_transfer_page_url
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 get_activate_url
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- Feature entry file, named after the feature, also holds the WPCOM_Backup bootstrap class.
2/**
3 * An in-wp-admin Backup page for WordPress.com Simple and WoA sites.
4 * Prompts for a plan upgrade or activation of backups.
5 *
6 * @package automattic/jetpack-mu-wpcom
7 */
8
9namespace Automattic\Jetpack\Jetpack_Mu_Wpcom;
10
11use Automattic\Jetpack\Constants;
12
13require_once __DIR__ . '/../../common/class-wpcom-wp-build-page.php';
14
15/**
16 * Registers the Backup admin page and its wp-build assets.
17 */
18class WPCOM_Backup extends WPCOM_WP_Build_Page {
19
20    /**
21     * Admin page slug. Matches Jetpack_Backup::JETPACK_BACKUP_SLUG so the URL survives a
22     * transfer to WoA, where the Jetpack plugin takes the slug over once backups are live.
23     */
24    const MENU_SLUG = 'jetpack-backup';
25
26    /**
27     * Page name for wp-build, as declared in routes/wpcom-backup/package.json.
28     */
29    const WP_BUILD_PAGE = 'wpcom-backup';
30
31    /**
32     * Global the page's boot script reads its initial state from.
33     */
34    const INITIAL_STATE_VAR = 'wpcomBackupInitialState';
35
36    /**
37     * The page records its prompts in Tracks.
38     */
39    const ENQUEUE_TRACKS = true;
40
41    /**
42     * Calypso flow that initiates the transfer, reports progress and returns here.
43     */
44    const TRANSFER_FLOW_URL = 'https://wordpress.com/setup/transferring-hosted-site';
45
46    /**
47     * Tracks context recorded for the WoA transfer.
48     */
49    const TRANSFER_CONTEXT = 'jetpack_product_activation';
50
51    /**
52     * Site has no backup-capable plan. Offer an upgrade.
53     */
54    const STATE_UPGRADE = 'upgrade';
55
56    /**
57     * A transfer to WoA is already running or queued. Offer nothing; report status.
58     */
59    const STATE_IN_PROGRESS = 'in_progress';
60
61    /**
62     * Site has the plan and can transfer. Offer activation.
63     */
64    const STATE_ACTIVATE = 'activate';
65
66    /**
67     * Whether the site runs on WordPress.com's Atomic infrastructure.
68     *
69     * Read through Constants rather than `defined()` so tests can exercise both
70     * platforms in one process.
71     *
72     * @return bool
73     */
74    public static function is_atomic() {
75        return Constants::is_true( 'IS_ATOMIC' );
76    }
77
78    /**
79     * Whether this page should claim the Backup slug at all.
80     *
81     * A plan that includes backups only makes them live on Atomic infrastructure, so on
82     * WoA an entitled site already has working backups and this page steps aside. A Simple
83     * site is never Atomic, so the page always applies there.
84     *
85     * @return bool
86     */
87    public static function should_register() {
88        if ( ! self::is_atomic() ) {
89            return true;
90        }
91
92        return ! self::has_backup_feature();
93    }
94
95    /**
96     * Keep the Jetpack plugin's Backup dashboard off a WoA site whose plan lacks backups.
97     *
98     * Otherwise it claims the slug first and this page's upgrade prompt steps aside.
99     *
100     * @param bool $enabled Whether the Jetpack plugin offers its Backup dashboard.
101     * @return bool
102     */
103    public static function filter_jetpack_backup_dashboard( $enabled ) {
104        return $enabled && self::has_backup_feature();
105    }
106
107    /**
108     * The page title.
109     *
110     * @return string
111     */
112    public static function get_page_title() {
113        // Product name, do not translate.
114        return 'Jetpack VaultPress Backup';
115    }
116
117    /**
118     * The menu entry's label.
119     *
120     * @return string
121     */
122    public static function get_menu_title() {
123        // Product name, do not translate.
124        return 'Backup';
125    }
126
127    /**
128     * The resolved prompt and everything it links to.
129     *
130     * @return array
131     */
132    public static function get_initial_state() {
133        $blog_id = get_current_blog_id();
134        $domain  = wp_parse_url( home_url(), PHP_URL_HOST );
135        $state   = self::get_state( $blog_id );
136
137        // Only the activation prompt reads eligibility, and both lists come from the
138        // same result, so resolve it once and only for that state.
139        $eligibility = self::STATE_ACTIVATE === $state
140            ? self::get_eligibility( $blog_id, get_current_user_id() )
141            : null;
142        $warnings    = self::get_transfer_warnings( $eligibility );
143
144        return array(
145            'state'       => $state,
146            'domain'      => $domain,
147            // A null result means the library was unavailable, not that the site
148            // failed a check; let the transfer flow reject it instead.
149            'isEligible'  => null === $eligibility || ! empty( $eligibility['is_eligible'] ),
150            'errors'      => self::get_transfer_errors( $eligibility ),
151            'warnings'    => $warnings,
152            'upgradeUrl'  => self::get_upgrade_url( $domain ),
153            'activateUrl' => self::get_activate_url( $warnings ),
154        );
155    }
156
157    /**
158     * Whether the site's plan includes self-serve backups.
159     *
160     * @return bool
161     */
162    public static function has_backup_feature() {
163        if ( ! function_exists( 'wpcom_site_has_feature' ) || ! defined( '\WPCOM_Features::BACKUPS_SELF_SERVE' ) ) {
164            return false;
165        }
166
167        // Called without a blog ID.
168        // WoA sites would pass the local blog ID, which is not the WordPress.com blog ID.
169        // wpcom resolves the current site.
170        return (bool) wpcom_site_has_feature( \WPCOM_Features::BACKUPS_SELF_SERVE );
171    }
172
173    /**
174     * Whether a transfer to WoA is already underway.
175     *
176     * @param int $blog_id Blog ID.
177     * @return bool
178     */
179    public static function is_transfer_in_progress( $blog_id ) {
180        if ( ! function_exists( 'require_lib' ) ) {
181            return false;
182        }
183
184        // These checks are only relevant for simple sites.
185        if ( self::is_atomic() ) {
186            return false;
187        }
188
189        require_lib( 'atomic' );
190
191        if ( function_exists( '\A8C\Atomic\has_site_pending_automated_transfer' ) ) {
192            // @phan-suppress-next-line PhanUndeclaredFunction -- wpcom-only; pending addition to stub-defs.php.
193            if ( \A8C\Atomic\has_site_pending_automated_transfer( $blog_id ) ) {
194                return true;
195            }
196        }
197
198        if ( function_exists( '\A8C\Atomic\is_wpcom_atomic' ) ) {
199            // Second argument includes pending/active/provisioned transfers.
200            // @phan-suppress-next-line PhanUndeclaredFunction -- wpcom-only; pending addition to stub-defs.php.
201            return (bool) \A8C\Atomic\is_wpcom_atomic( $blog_id, true );
202        }
203
204        return false;
205    }
206
207    /**
208     * Transfer eligibility for the site, or null when it cannot be determined.
209     *
210     * An in-progress transfer is reported as a `transfer_already_exists` error, so
211     * that state is checked first and never reaches here as a blocker.
212     *
213     * @param int $blog_id Blog ID.
214     * @param int $user_id User ID.
215     * @return array|null { is_eligible: bool, errors: array, warnings: array }
216     */
217    public static function get_eligibility( $blog_id, $user_id ) {
218        if ( ! function_exists( 'require_lib' ) ) {
219            return null;
220        }
221
222        // These checks are only relevant for simple sites.
223        if ( self::is_atomic() ) {
224            return null;
225        }
226
227        require_lib( 'atomic' );
228
229        if ( ! function_exists( '\A8C\Atomic\Eligibility\get_status_for_site' ) ) {
230            return null;
231        }
232
233        // @phan-suppress-next-line PhanUndeclaredFunction -- wpcom-only; pending addition to stub-defs.php.
234        return \A8C\Atomic\Eligibility\get_status_for_site( $blog_id, $user_id );
235    }
236
237    /**
238     * Resolve which prompt the page should show.
239     *
240     * @param int $blog_id Blog ID.
241     * @return string One of the STATE_* constants.
242     */
243    public static function get_state( $blog_id ) {
244        // On WoA the plan is the only question: the site is already on the
245        // infrastructure that runs backups, so there is nothing to transfer, and
246        // should_register() has already stepped the page aside if it has the plan.
247        if ( ! self::has_backup_feature() || self::is_atomic() ) {
248            $state = self::STATE_UPGRADE;
249        } elseif ( self::is_transfer_in_progress( $blog_id ) ) {
250            $state = self::STATE_IN_PROGRESS;
251        } else {
252            // Eligibility failures are explained by the activation prompt's own
253            // confirmation step, so they do not get a state of their own.
254            $state = self::STATE_ACTIVATE;
255        }
256
257        return $state;
258    }
259
260    /**
261     * Reasons a site cannot be transferred, in the shape the API returns them.
262     *
263     * The code is kept because the page maps it to its own copy; the API's message comes
264     * along as the fallback the page renders for codes it does not recognize.
265     *
266     * @param array|null $eligibility Result of get_eligibility().
267     * @return array[] Errors as { code, message }.
268     */
269    public static function get_transfer_errors( $eligibility ) {
270        $errors = array();
271
272        if ( ! empty( $eligibility['errors'] ) && is_array( $eligibility['errors'] ) ) {
273            foreach ( $eligibility['errors'] as $error ) {
274                if ( empty( $error['code'] ) ) {
275                    continue;
276                }
277
278                $errors[] = array(
279                    'code'    => (string) $error['code'],
280                    'message' => isset( $error['message'] ) ? (string) $error['message'] : '',
281                );
282            }
283        }
284
285        return $errors;
286    }
287
288    /**
289     * Non-blocking warnings to confirm before a transfer starts.
290     *
291     * The API groups warnings by type; they are flattened here because the page
292     * renders one list and a PHP map would localize as a JSON array once empty.
293     *
294     * @param array|null $eligibility Result of get_eligibility().
295     * @return array[] Warnings in the API's own shape, minus the grouping.
296     */
297    public static function get_transfer_warnings( $eligibility ) {
298        $warnings = array();
299
300        if ( ! empty( $eligibility['warnings'] ) && is_array( $eligibility['warnings'] ) ) {
301            foreach ( $eligibility['warnings'] as $group ) {
302                if ( ! is_array( $group ) ) {
303                    continue;
304                }
305
306                foreach ( $group as $warning ) {
307                    if ( empty( $warning['id'] ) ) {
308                        continue;
309                    }
310
311                    $warnings[] = array(
312                        'id'           => (string) $warning['id'],
313                        'description'  => isset( $warning['description'] ) ? (string) $warning['description'] : '',
314                        'domain_names' => ( ! empty( $warning['domain_names']['current'] ) && ! empty( $warning['domain_names']['new'] ) )
315                            ? array(
316                                'current' => (string) $warning['domain_names']['current'],
317                                'new'     => (string) $warning['domain_names']['new'],
318                            )
319                            : null,
320                        // Rendered as a link, so only a web URL gets through.
321                        'support_url'  => isset( $warning['support_url'] ) ? esc_url_raw( (string) $warning['support_url'], array( 'http', 'https' ) ) : '',
322                    );
323                }
324            }
325        }
326
327        return $warnings;
328    }
329
330    /**
331     * Checkout, with the plan that includes backups already in the cart.
332     *
333     * `redirect_to` returns a buyer here to activate what they just bought, and
334     * `checkoutBackUrl` returns someone who backs out; without it checkout falls back to /plans.
335     *
336     * @param string $domain Site domain.
337     * @return string
338     */
339    public static function get_upgrade_url( $domain ) {
340        $page_url = rawurlencode( self::get_page_url() );
341
342        return add_query_arg(
343            array(
344                'redirect_to'     => $page_url,
345                'checkoutBackUrl' => $page_url,
346            ),
347            'https://wordpress.com/checkout/' . rawurlencode( (string) $domain ) . '/business'
348        );
349    }
350
351    /**
352     * Where this page will live once the transfer lands.
353     *
354     * Uses the new address from the address-change warning rather than trusting the old
355     * one to redirect, which may not have propagated when the flow sends the reader back.
356     *
357     * @param array[] $warnings Result of get_transfer_warnings().
358     * @return string
359     */
360    public static function get_post_transfer_page_url( array $warnings ) {
361        $page_url = self::get_page_url();
362
363        foreach ( $warnings as $warning ) {
364            $new_host = $warning['domain_names']['new'] ?? '';
365
366            // A bare hostname only, so nothing in the payload can steer the scheme or path.
367            if ( is_string( $new_host ) && filter_var( $new_host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME ) ) {
368                $parts = wp_parse_url( $page_url );
369
370                return 'https://' . strtolower( $new_host ) . ( $parts['path'] ?? '' ) . ( isset( $parts['query'] ) ? '?' . $parts['query'] : '' );
371            }
372        }
373
374        return $page_url;
375    }
376
377    /**
378     * URL of the Calypso flow that transfers the site and switches backups on.
379     *
380     * The flow waits for the transfer to land before following `redirect_to`.
381     *
382     * @param array[] $warnings Result of get_transfer_warnings(), for the post-transfer address.
383     * @return string
384     */
385    public static function get_activate_url( array $warnings = array() ) {
386        return add_query_arg(
387            array(
388                'siteId'                    => get_current_blog_id(),
389                'initiate_transfer_context' => self::TRANSFER_CONTEXT,
390                'redirect_to'               => rawurlencode( self::get_post_transfer_page_url( $warnings ) ),
391            ),
392            self::TRANSFER_FLOW_URL
393        );
394    }
395}
396
397add_action( 'init', array( WPCOM_Backup::class, 'init' ) );