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