Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.00% covered (success)
94.00%
47 / 50
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
Capabilities_Bridge
97.92% covered (success)
97.92%
47 / 48
50.00% covered (danger)
50.00%
1 / 2
10
0.00% covered (danger)
0.00%
0 / 1
 register_routes
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 get_capabilities
97.44% covered (success)
97.44%
38 / 39
0.00% covered (danger)
0.00%
0 / 1
9
1<?php
2/**
3 * Capabilities REST bridge — WPCOM's site rewind state.
4 *
5 * @package automattic/jetpack-backup-plugin
6 */
7
8namespace Automattic\Jetpack\Backup\V0005\REST;
9
10use Automattic\Jetpack\Backup\V0005\Jetpack_Backup;
11use Automattic\Jetpack\Connection\Client;
12use WP_Error;
13use WP_REST_Server;
14
15if ( ! defined( 'ABSPATH' ) ) {
16    exit( 0 );
17}
18
19/**
20 * Returns what the modernized dashboard is allowed to show.
21 */
22class Capabilities_Bridge {
23
24    /**
25     * Register the GET /jetpack/v4/site/capabilities route.
26     *
27     * @return void
28     */
29    public static function register_routes() {
30        register_rest_route(
31            'jetpack/v4',
32            '/site/capabilities',
33            array(
34                'methods'             => WP_REST_Server::READABLE,
35                'callback'            => array( __CLASS__, 'get_capabilities' ),
36                'permission_callback' => array( Rest_Controller::class, 'permission_check' ),
37            )
38        );
39    }
40
41    /**
42     * Proxy `/sites/{id}/rewind/capabilities` (v2, as_user) and project
43     * the response into the shape the React layer expects.
44     *
45     * This is the same endpoint the legacy `/jetpack/v4/backup-capabilities`
46     * route hits — it returns a flat `{ capabilities: [...] }` envelope.
47     * The earlier `/rewind?force=wpcom` variant returns site *state*, not
48     * a capabilities list, and on some plan shapes (e.g. Jetpack Complete)
49     * the `capabilities` key is missing entirely, which produced a false
50     * "no plan" gate for plans that do include Backup.
51     *
52     * @return \WP_REST_Response|WP_Error The decoded capabilities, or WP_Error on failure.
53     */
54    public static function get_capabilities() {
55        $blog_id = Rest_Controller::get_blog_id_or_error();
56        if ( is_wp_error( $blog_id ) ) {
57            return $blog_id;
58        }
59
60        $cached = get_transient( Jetpack_Backup::CAPABILITIES_TRANSIENT );
61        if ( is_array( $cached ) ) {
62            return rest_ensure_response( $cached );
63        }
64
65        $response = Client::wpcom_json_api_request_as_user(
66            sprintf( '/sites/%d/rewind/capabilities', $blog_id ),
67            'v2',
68            array(),
69            null,
70            'wpcom'
71        );
72
73        if ( is_wp_error( $response ) ) {
74            return Rest_Controller::transport_error( $response, 'capabilities_fetch_failed' );
75        }
76
77        // Cast: `wp_remote_retrieve_response_code()` returns whatever the
78        // transport put there, and a numeric string fails a strict
79        // comparison against 200 — sending a perfectly good response down
80        // the failure branch, and reporting it as a failure rather than as
81        // the success it was.
82        $status_code = (int) wp_remote_retrieve_response_code( $response );
83        if ( 200 !== $status_code ) {
84            return Rest_Controller::upstream_error(
85                $response,
86                'capabilities_fetch_failed',
87                __( 'Could not fetch site capabilities.', 'jetpack-backup-pkg' )
88            );
89        }
90
91        $body = json_decode( wp_remote_retrieve_body( $response ), true );
92
93        // A 200 we cannot read is refused rather than projected.
94        //
95        // Coercing it to an empty list is the same as answering "this site
96        // has no Backup plan", and that answer is acted on: `<Gates>`
97        // renders the upgrade screen. So a truncated response, an HTML
98        // error page from something in front of WordPress.com, or a shape
99        // change upstream would each show a paying customer an advert for
100        // what they already own, with no error anywhere to explain it.
101        // The docblock above records this exact mechanism firing once
102        // already; that fix repointed the endpoint and left the tolerant
103        // projection in place.
104        //
105        // An *empty* list is not this case. It is a legitimate answer —
106        // the one every site without Backup gives — and refusing it would
107        // put a permanent error in front of precisely the people the
108        // upgrade screen is for.
109        // `wp_is_numeric_array()` and not `is_array()`, because the two
110        // differ on the shape most likely to arrive if upstream drifts: a
111        // keyed map. `is_array()` accepts `{"capabilities":{"backup":true}}`,
112        // and `in_array()` then compares against that map's *values* — so
113        // the site reads as having no plan, which is the outcome this
114        // whole guard exists to prevent. It returns true for an empty
115        // array, so the carve-out below survives.
116        if (
117            ! is_array( $body )
118            || ! isset( $body['capabilities'] )
119            || ! wp_is_numeric_array( $body['capabilities'] )
120        ) {
121            return new WP_Error(
122                'capabilities_unreadable',
123                __( "Could not read this site's plan details.", 'jetpack-backup-pkg' ),
124                // Deliberately not the 502 `Rest_Controller::transport_error()`
125                // uses: the client reads 502 as "the answer went missing",
126                // a meaning it shares with the destructive restore
127                // mutation. Nothing was in flight here. WordPress.com
128                // answered; we could not read what it said.
129                array( 'status' => 500 )
130            );
131        }
132
133        $capabilities = $body['capabilities'];
134        $projected    = array(
135            'hasBackupPlan' => in_array( 'backup', $capabilities, true ),
136            'hasScan'       => in_array( 'scan', $capabilities, true ),
137        );
138
139        // A "no plan" answer is not kept: a reader back from buying one must not meet the upsell again.
140        if ( $projected['hasBackupPlan'] ) {
141            set_transient( Jetpack_Backup::CAPABILITIES_TRANSIENT, $projected, Jetpack_Backup::REWIND_READ_CACHE_TTL );
142        }
143
144        return rest_ensure_response( $projected );
145    }
146}