Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.06% covered (success)
95.06%
154 / 162
81.48% covered (warning)
81.48%
22 / 27
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_Hosting_Feature_Page
95.65% covered (success)
95.65%
154 / 161
81.48% covered (warning)
81.48%
22 / 27
86
0.00% covered (danger)
0.00%
0 / 1
 has_feature
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 has_atomic_feature
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 site_has_feature
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
4.25
 is_atomic
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 init
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_rest_route
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%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 can_read_feature_status
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_feature_status
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 is_checkout_pending
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
4
 should_register
100.00% covered (success)
100.00%
3 / 3
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
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
7
 load_atomic_lib
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 is_transfer_in_progress
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
5.39
 get_latest_transfer_status
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
6
 get_eligibility
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
3.58
 get_state
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 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_support_url
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_upgrade_url
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 get_plan_upgrade_url
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
5
 get_live_feature_url
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 get_post_transfer_host
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 get_activate_url
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Shared base for in-wp-admin pages that prompt WordPress.com Simple and WoA sites
4 * to upgrade, or to transfer to WoA, before a hosting feature can run.
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 a hosting feature's admin page and its wp-build assets.
17 *
18 * Each page subclasses this, overriding the page constants.
19 */
20abstract class WPCOM_Hosting_Feature_Page extends WPCOM_WP_Build_Page {
21
22    /**
23     * Document title of the page. A product name, so not translated.
24     */
25    const PAGE_TITLE = '';
26
27    /**
28     * Menu entry label. A product name, so not translated.
29     */
30    const MENU_TITLE = '';
31
32    /**
33     * Name of the `WPCOM_Features` constant the site's plan must include.
34     */
35    const FEATURE = '';
36
37    /**
38     * Calypso flow that initiates the transfer, reports progress and returns here.
39     */
40    const TRANSFER_FLOW_URL = 'https://wordpress.com/setup/transferring-hosted-site';
41
42    /**
43     * Tracks context recorded for the WoA transfer.
44     */
45    const TRANSFER_CONTEXT = 'jetpack_product_activation';
46
47    /**
48     * The pages record their prompts in Tracks.
49     */
50    const ENQUEUE_TRACKS = true;
51
52    /**
53     * Query arg the plan upgrade flow returns a WoA buyer with, set to CHECKOUT_COMPLETE.
54     */
55    const CHECKOUT_ARG = 'checkout';
56
57    /**
58     * Value of CHECKOUT_ARG once checkout has succeeded.
59     */
60    const CHECKOUT_COMPLETE = 'complete';
61
62    /**
63     * Site has no plan that includes the feature. Offer an upgrade.
64     */
65    const STATE_UPGRADE = 'upgrade';
66
67    /**
68     * A transfer to WoA is already running or queued, or on WoA the dashboard waits for the connection. Offer nothing; report status.
69     */
70    const STATE_IN_PROGRESS = 'in_progress';
71
72    /**
73     * Site has the plan and can transfer. Offer activation.
74     */
75    const STATE_ACTIVATE = 'activate';
76
77    /**
78     * Whether the site's plan includes FEATURE. Without one it offers the upgrade, the one
79     * prompt that is never wrong for a site of unknown plan.
80     *
81     * @return bool
82     */
83    public static function has_feature() {
84        return self::site_has_feature( static::FEATURE );
85    }
86
87    /**
88     * Whether the site's plan includes WordPress.com's Atomic hosting, which these features run on.
89     *
90     * @return bool
91     */
92    public static function has_atomic_feature() {
93        return self::site_has_feature( 'ATOMIC' );
94    }
95
96    /**
97     * Whether the site's plan includes a WordPress.com feature.
98     *
99     * @param string $name Name of a `WPCOM_Features` constant.
100     * @return bool
101     */
102    private static function site_has_feature( $name ) {
103        $constant = '\WPCOM_Features::' . $name;
104
105        if ( '' === $name || ! function_exists( 'wpcom_site_has_feature' ) || ! defined( $constant ) ) {
106            return false;
107        }
108
109        // Called without a blog ID: on WoA the local ID is not the WordPress.com one, so wpcom resolves the current site.
110        return (bool) wpcom_site_has_feature( constant( $constant ) );
111    }
112
113    /**
114     * Whether the site runs on WordPress.com's Atomic infrastructure.
115     *
116     * Read through Constants rather than `defined()` so tests can exercise both
117     * platforms in one process.
118     *
119     * @return bool
120     */
121    public static function is_atomic() {
122        return Constants::is_true( 'IS_ATOMIC' );
123    }
124
125    /**
126     * Boot the page, plus, on WoA, the route its post-checkout screen polls.
127     *
128     * @return void
129     */
130    public static function init() {
131        // Registered even when the page steps aside, so a poll still in flight learns the feature arrived.
132        if ( self::is_atomic() ) {
133            add_action( 'rest_api_init', array( static::class, 'register_rest_routes' ) );
134        }
135
136        parent::init();
137    }
138
139    /**
140     * The route reporting whether the plan includes FEATURE yet, relative to `wpcom/v2`.
141     *
142     * @return string
143     */
144    public static function get_rest_route() {
145        return '/hosting-feature-page/' . static::MENU_SLUG;
146    }
147
148    /**
149     * Register the route that reports whether the plan includes FEATURE yet.
150     *
151     * @return void
152     */
153    public static function register_rest_routes() {
154        register_rest_route(
155            'wpcom/v2',
156            static::get_rest_route(),
157            array(
158                'methods'             => \WP_REST_Server::READABLE,
159                'callback'            => array( static::class, 'get_feature_status' ),
160                'permission_callback' => array( static::class, 'can_read_feature_status' ),
161            )
162        );
163    }
164
165    /**
166     * Whether the current user may poll the feature status, as they may see the page.
167     *
168     * @return bool
169     */
170    public static function can_read_feature_status() {
171        return current_user_can( static::CAPABILITY );
172    }
173
174    /**
175     * Whether the plan includes FEATURE, read from the site's own copy of its purchases, which the page renders from.
176     *
177     * Not WordPress.com's, which knows about a purchase before the copy synced to WoA does.
178     *
179     * @return \WP_REST_Response
180     */
181    public static function get_feature_status() {
182        $has_feature = static::has_feature();
183
184        // The Jetpack dashboard the page reloads into reads Jetpack's stored plan, which can lag that copy.
185        if ( $has_feature && method_exists( '\Automattic\Jetpack\Current_Plan', 'refresh_from_wpcom' ) ) {
186            \Automattic\Jetpack\Current_Plan::refresh_from_wpcom( array( 'timeout' => 5 ) );
187        }
188
189        return rest_ensure_response( array( 'hasFeature' => $has_feature ) );
190    }
191
192    /**
193     * Whether a WoA buyer just returned from checkout to a page that has not seen the purchase yet.
194     *
195     * @param string $state The resolved STATE_* constant.
196     * @return bool
197     */
198    public static function is_checkout_pending( $state ) {
199        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only flag set by the plan upgrade flow's return address.
200        $checkout = isset( $_GET[ self::CHECKOUT_ARG ] ) ? sanitize_key( wp_unslash( $_GET[ self::CHECKOUT_ARG ] ) ) : '';
201
202        return self::STATE_UPGRADE === $state && self::is_atomic() && self::CHECKOUT_COMPLETE === $checkout;
203    }
204
205    /**
206     * Whether this page should claim its slug at all.
207     *
208     * A plan that includes the feature only makes it live on Atomic infrastructure, so on
209     * WoA an entitled site already has it and this page steps aside. A Simple site is never
210     * Atomic, so the page always applies there.
211     *
212     * @return bool
213     */
214    public static function should_register() {
215        if ( ! self::is_atomic() ) {
216            return true;
217        }
218
219        return ! static::has_feature();
220    }
221
222    /**
223     * The page title.
224     *
225     * @return string
226     */
227    public static function get_page_title() {
228        return static::PAGE_TITLE;
229    }
230
231    /**
232     * The menu entry's label.
233     *
234     * @return string
235     */
236    public static function get_menu_title() {
237        return static::MENU_TITLE;
238    }
239
240    /**
241     * The resolved prompt and everything it links to.
242     *
243     * @return array
244     */
245    public static function get_initial_state() {
246        $blog_id = get_current_blog_id();
247        $domain  = wp_parse_url( home_url(), PHP_URL_HOST );
248        $state   = static::get_state( $blog_id );
249
250        // Only the activation prompt reads eligibility, and both lists come from the
251        // same result, so resolve it once and only for that state.
252        $eligibility     = self::STATE_ACTIVATE === $state
253            ? self::get_eligibility( $blog_id, get_current_user_id() )
254            : null;
255        $warnings        = self::get_transfer_warnings( $eligibility );
256        $transfer_status = self::STATE_IN_PROGRESS === $state ? null : self::get_latest_transfer_status( $blog_id );
257
258        $initial_state = array(
259            'state'               => $state,
260            'domain'              => $domain,
261            // A null result means the library was unavailable, not that the site
262            // failed a check; let the transfer flow reject it instead.
263            'isEligible'          => null === $eligibility || ! empty( $eligibility['is_eligible'] ),
264            'errors'              => self::get_transfer_errors( $eligibility ),
265            'warnings'            => $warnings,
266            'upgradeUrl'          => static::get_upgrade_url( $domain ),
267            'activateUrl'         => static::get_activate_url( $warnings ),
268            'supportUrl'          => self::get_support_url(),
269            // Each applies only to the prompt Calypso pairs it with.
270            'hasRevertedTransfer' => self::STATE_UPGRADE === $state && 'reverted' === $transfer_status,
271            'transferFailed'      => self::STATE_ACTIVATE === $state && 'error' === $transfer_status,
272            'checkoutPending'     => static::is_checkout_pending( $state ),
273        );
274
275        if ( $initial_state['checkoutPending'] ) {
276            $initial_state['featureStatusPath'] = '/wpcom/v2' . static::get_rest_route();
277        }
278
279        return $initial_state;
280    }
281
282    /**
283     * Load wpcom's Atomic library for the transfer checks, which callers still guard with function_exists().
284     *
285     * @return bool False on WoA, where there is nothing left to transfer.
286     */
287    private static function load_atomic_lib() {
288        if ( self::is_atomic() ) {
289            return false;
290        }
291
292        if ( function_exists( 'require_lib' ) ) {
293            require_lib( 'atomic' );
294        }
295
296        return true;
297    }
298
299    /**
300     * Whether a transfer to WoA is already underway.
301     *
302     * @param int $blog_id Blog ID.
303     * @return bool
304     */
305    public static function is_transfer_in_progress( $blog_id ) {
306        if ( ! self::load_atomic_lib() ) {
307            return false;
308        }
309
310        if ( function_exists( '\A8C\Atomic\has_site_pending_automated_transfer' ) ) {
311            if ( \A8C\Atomic\has_site_pending_automated_transfer( $blog_id ) ) {
312                return true;
313            }
314        }
315
316        if ( function_exists( '\A8C\Atomic\is_wpcom_atomic' ) ) {
317            // Second argument includes pending/active/provisioned transfers.
318            return (bool) \A8C\Atomic\is_wpcom_atomic( $blog_id, true );
319        }
320
321        return false;
322    }
323
324    /**
325     * Status of the site's latest transfer to WoA, or null when it has none.
326     *
327     * @param int $blog_id Blog ID.
328     * @return string|null A transfer record status, such as `reverted` or `error`.
329     */
330    public static function get_latest_transfer_status( $blog_id ) {
331        if ( ! self::load_atomic_lib() || ! function_exists( 'woa_get_latest_transfer' ) ) {
332            return null;
333        }
334
335        $transfer = woa_get_latest_transfer( $blog_id );
336
337        if ( is_wp_error( $transfer ) || ! is_object( $transfer ) || ! isset( $transfer->status ) ) {
338            return null;
339        }
340
341        return (string) $transfer->status;
342    }
343
344    /**
345     * Transfer eligibility for the site, or null when it cannot be determined.
346     *
347     * An in-progress transfer is reported as a `transfer_already_exists` error, so
348     * that state is checked first and never reaches here as a blocker.
349     *
350     * @param int $blog_id Blog ID.
351     * @param int $user_id User ID.
352     * @return array|null { is_eligible: bool, errors: array, warnings: array }
353     */
354    public static function get_eligibility( $blog_id, $user_id ) {
355        if ( ! self::load_atomic_lib() ) {
356            return null;
357        }
358
359        if ( ! function_exists( '\A8C\Atomic\Eligibility\get_status_for_site' ) ) {
360            return null;
361        }
362
363        return \A8C\Atomic\Eligibility\get_status_for_site( $blog_id, $user_id );
364    }
365
366    /**
367     * Resolve which prompt the page should show.
368     *
369     * @param int $blog_id Blog ID.
370     * @return string One of the STATE_* constants.
371     */
372    public static function get_state( $blog_id ) {
373        // On WoA the plan is the only question: the site is already on the
374        // infrastructure that runs the feature, so there is nothing to transfer, and
375        // should_register() has already stepped the page aside if it has the plan.
376        // On Simple, activation also needs the hosting platform, as Calypso requires.
377        if ( ! static::has_feature() || ! self::has_atomic_feature() || self::is_atomic() ) {
378            $state = self::STATE_UPGRADE;
379        } elseif ( self::is_transfer_in_progress( $blog_id ) ) {
380            $state = self::STATE_IN_PROGRESS;
381        } else {
382            // Eligibility failures are explained by the activation prompt's own
383            // confirmation step, so they do not get a state of their own.
384            $state = self::STATE_ACTIVATE;
385        }
386
387        return $state;
388    }
389
390    /**
391     * Reasons a site cannot be transferred, in the shape the API returns them.
392     *
393     * The code is kept because the page maps it to its own copy; the API's message comes
394     * along as the fallback the page renders for codes it does not recognize.
395     *
396     * @param array|null $eligibility Result of get_eligibility().
397     * @return array[] Errors as { code, message }.
398     */
399    public static function get_transfer_errors( $eligibility ) {
400        $errors = array();
401
402        if ( ! empty( $eligibility['errors'] ) && is_array( $eligibility['errors'] ) ) {
403            foreach ( $eligibility['errors'] as $error ) {
404                if ( empty( $error['code'] ) ) {
405                    continue;
406                }
407
408                $errors[] = array(
409                    'code'    => (string) $error['code'],
410                    'message' => isset( $error['message'] ) ? (string) $error['message'] : '',
411                );
412            }
413        }
414
415        return $errors;
416    }
417
418    /**
419     * Non-blocking warnings to confirm before a transfer starts.
420     *
421     * The API groups warnings by type; they are flattened here because the page
422     * renders one list and a PHP map would localize as a JSON array once empty.
423     *
424     * @param array|null $eligibility Result of get_eligibility().
425     * @return array[] Warnings in the API's own shape, minus the grouping.
426     */
427    public static function get_transfer_warnings( $eligibility ) {
428        $warnings = array();
429
430        if ( ! empty( $eligibility['warnings'] ) && is_array( $eligibility['warnings'] ) ) {
431            foreach ( $eligibility['warnings'] as $group ) {
432                if ( ! is_array( $group ) ) {
433                    continue;
434                }
435
436                foreach ( $group as $warning ) {
437                    if ( empty( $warning['id'] ) ) {
438                        continue;
439                    }
440
441                    $warnings[] = array(
442                        'id'           => (string) $warning['id'],
443                        'description'  => isset( $warning['description'] ) ? (string) $warning['description'] : '',
444                        'domain_names' => ( ! empty( $warning['domain_names']['current'] ) && ! empty( $warning['domain_names']['new'] ) )
445                            ? array(
446                                'current' => (string) $warning['domain_names']['current'],
447                                'new'     => (string) $warning['domain_names']['new'],
448                            )
449                            : null,
450                        // Rendered as a link, so only a web URL gets through.
451                        'support_url'  => isset( $warning['support_url'] ) ? esc_url_raw( (string) $warning['support_url'], array( 'http', 'https' ) ) : '',
452                    );
453                }
454            }
455        }
456
457        return $warnings;
458    }
459
460    /**
461     * Support's contact page, in the reader's language where WordPress.com has one.
462     *
463     * @return string
464     */
465    public static function get_support_url() {
466        $url = 'https://wordpress.com/help/contact';
467
468        return function_exists( 'localized_wpcom_url' ) ? localized_wpcom_url( $url ) : $url;
469    }
470
471    /**
472     * On Simple, checkout with the Business plan already in the cart; on WoA, the plan upgrade flow.
473     *
474     * `redirect_to` returns a buyer to activate what they just bought, and
475     * `checkoutBackUrl` returns someone who backs out; without it checkout falls back to /plans.
476     *
477     * @param string $domain Site domain.
478     * @return string
479     */
480    public static function get_upgrade_url( $domain ) {
481        // On WoA the purchase makes the feature live, so there is nothing to come back here for.
482        if ( self::is_atomic() ) {
483            return static::get_plan_upgrade_url();
484        }
485
486        $page_url = rawurlencode( static::get_page_url() );
487
488        return add_query_arg(
489            array(
490                'redirect_to'     => $page_url,
491                'checkoutBackUrl' => $page_url,
492            ),
493            'https://wordpress.com/checkout/' . rawurlencode( (string) $domain ) . '/business'
494        );
495    }
496
497    /**
498     * WordPress.com's plan upgrade flow, showing only plans with FEATURE, with Back to the page the link was on.
499     *
500     * The flow and checkout accept `back_to` and `redirect_to` only on the site's own host or WordPress.com.
501     *
502     * @param string $back_url The admin page the link is on; this page when empty or off this site.
503     * @return string
504     */
505    public static function get_plan_upgrade_url( $back_url = '' ) {
506        $back     = '' === $back_url ? '' : wp_validate_redirect( $back_url, '' );
507        $constant = '\WPCOM_Features::' . static::FEATURE;
508        $live_url = static::get_live_feature_url();
509
510        // Only this page reads the arg, and only a completed purchase follows `redirect_to`.
511        if ( static::get_page_url() === $live_url ) {
512            $live_url = add_query_arg( self::CHECKOUT_ARG, self::CHECKOUT_COMPLETE, $live_url );
513        }
514
515        return add_query_arg(
516            array_filter(
517                array(
518                    'siteSlug'    => rawurlencode( wpcom_get_site_slug() ),
519                    'feature'     => defined( $constant ) ? constant( $constant ) : '',
520                    'back_to'     => rawurlencode( $back ? $back : static::get_page_url() ),
521                    'redirect_to' => rawurlencode( $live_url ),
522                )
523            ),
524            'https://wordpress.com/setup/plan-upgrade'
525        );
526    }
527
528    /**
529     * Where a site lands once its plan makes the feature live and this page steps aside.
530     *
531     * By default the slug's next owner serves the feature at this page's own address.
532     *
533     * @param string|null $new_host The site's address after a transfer, when it changes.
534     * @return string
535     */
536    public static function get_live_feature_url( $new_host = null ) {
537        $page_url = static::get_page_url();
538
539        if ( null === $new_host ) {
540            return $page_url;
541        }
542
543        $parts = wp_parse_url( $page_url );
544
545        return 'https://' . $new_host . ( $parts['path'] ?? '' ) . ( isset( $parts['query'] ) ? '?' . $parts['query'] : '' );
546    }
547
548    /**
549     * The site's new address from the address-change warning, if the transfer changes it.
550     *
551     * Used rather than trusting the old address to redirect, which may not have propagated
552     * when the flow sends the reader back.
553     *
554     * @param array[] $warnings Result of get_transfer_warnings().
555     * @return string|null
556     */
557    public static function get_post_transfer_host( array $warnings ) {
558        foreach ( $warnings as $warning ) {
559            $new_host = $warning['domain_names']['new'] ?? '';
560
561            // A bare hostname only, so nothing in the payload can steer the scheme or path.
562            if ( is_string( $new_host ) && filter_var( $new_host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME ) ) {
563                return strtolower( $new_host );
564            }
565        }
566
567        return null;
568    }
569
570    /**
571     * URL of the Calypso flow that transfers the site and switches the feature on.
572     *
573     * The flow waits for the transfer to land before following `redirect_to`.
574     *
575     * @param array[] $warnings Result of get_transfer_warnings(), for the post-transfer address.
576     * @return string
577     */
578    public static function get_activate_url( array $warnings = array() ) {
579        return add_query_arg(
580            array(
581                // Only Simple sites reach activation, and their local blog ID is the WordPress.com one; WoA's is not.
582                'siteId'                    => get_current_blog_id(),
583                'initiate_transfer_context' => self::TRANSFER_CONTEXT,
584                'redirect_to'               => rawurlencode( static::get_live_feature_url( self::get_post_transfer_host( $warnings ) ) ),
585            ),
586            self::TRANSFER_FLOW_URL
587        );
588    }
589}