Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
86.35% covered (warning)
86.35%
234 / 271
56.25% covered (warning)
56.25%
9 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
Tokens
86.35% covered (warning)
86.35%
234 / 271
56.25% covered (warning)
56.25%
9 / 16
131.53
0.00% covered (danger)
0.00%
0 / 1
 delete_all
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 validate
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
9
 validate_blog_token
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
8
 get
80.26% covered (warning)
80.26%
61 / 76
0.00% covered (danger)
0.00%
0 / 1
27.07
 update_user_token
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 sign_role
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 return_30
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_access_token
78.18% covered (warning)
78.18%
43 / 55
0.00% covered (danger)
0.00%
0 / 1
42.64
 update_blog_token
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 disconnect_user
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
3.14
 get_connected_users
n/a
0 / 0
n/a
0 / 0
1
 get_signed_token
96.88% covered (success)
96.88%
31 / 32
0.00% covered (danger)
0.00%
0 / 1
5
 get_user_tokens
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 update_user_tokens
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 set_lock
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
2.50
 remove_lock
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 is_locked
77.78% covered (warning)
77.78%
14 / 18
0.00% covered (danger)
0.00%
0 / 1
7.54
1<?php
2/**
3 * The Jetpack Connection Tokens class file.
4 *
5 * @package automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack\Connection;
9
10use Automattic\Jetpack\Constants;
11use Automattic\Jetpack\Roles;
12use DateInterval;
13use DateTime;
14use Exception;
15use Jetpack_Options;
16use WP_Error;
17
18/**
19 * The Jetpack Connection Tokens class that manages tokens.
20 */
21class Tokens {
22
23    const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
24
25    /**
26     * Datetime format.
27     */
28    const DATE_FORMAT_ATOM = 'Y-m-d\TH:i:sP';
29
30    /**
31     * Deletes all connection tokens and transients from the local Jetpack site.
32     */
33    public function delete_all() {
34        Jetpack_Options::delete_option(
35            array(
36                'blog_token',
37                'user_token',
38                'user_tokens',
39            )
40        );
41
42        $this->remove_lock();
43
44        /**
45         * Fires after all connection tokens have been deleted from the local site.
46         *
47         * `Jetpack_Options::delete_option()` fires no action of its own, so this is the only
48         * signal that the tokens backing the connection are gone. Anything holding derived
49         * state — a memoized connection status, a cached credential — must recompute from here.
50         *
51         * @since 9.1.1
52         */
53        do_action( 'jetpack_connection_tokens_deleted' );
54    }
55
56    /**
57     * Perform the API request to validate the blog and user tokens.
58     *
59     * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
60     *
61     * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
62     */
63    public function validate( $user_id = null ) {
64        $blog_id = Jetpack_Options::get_option( 'id' );
65        if ( ! $blog_id ) {
66            return new WP_Error( 'site_not_registered', 'Site not registered.' );
67        }
68        $url = sprintf(
69            '%s/%s/v%s/%s',
70            Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
71            'wpcom',
72            '2',
73            'sites/' . $blog_id . '/jetpack-token-health'
74        );
75
76        $user_token = $this->get_access_token( $user_id ? $user_id : get_current_user_id() );
77        $blog_token = $this->get_access_token();
78
79        // Cannot validate non-existent tokens.
80        if ( false === $user_token || false === $blog_token ) {
81            return false;
82        }
83
84        $method   = 'POST';
85        $body     = array(
86            'user_token' => $this->get_signed_token( $user_token ),
87            'blog_token' => $this->get_signed_token( $blog_token ),
88        );
89        $response = Client::_wp_remote_request( $url, compact( 'body', 'method' ) );
90
91        if ( is_wp_error( $response ) || ! wp_remote_retrieve_body( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
92            return false;
93        }
94
95        $body = json_decode( wp_remote_retrieve_body( $response ), true );
96
97        return $body ? $body : false;
98    }
99
100    /**
101     * Perform the API request to validate only the blog.
102     *
103     * @since 9.8.0 Returns a WP_Error, not false, when the request fails.
104     *
105     * @return bool|WP_Error Boolean with the test result. WP_Error if test cannot be performed.
106     */
107    public function validate_blog_token() {
108        $blog_id = Jetpack_Options::get_option( 'id' );
109        if ( ! $blog_id ) {
110            return new WP_Error( 'site_not_registered', 'Site not registered.' );
111        }
112
113        // A missing blog token is broken, not unverifiable: the signed request would fail before it is sent.
114        if ( ! $this->get_access_token() ) {
115            return false;
116        }
117
118        $url = sprintf(
119            '%s/%s/v%s/%s',
120            Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
121            'wpcom',
122            '2',
123            'sites/' . $blog_id . '/jetpack-token-health/blog'
124        );
125
126        $method   = 'GET';
127        $response = Client::remote_request( compact( 'url', 'method' ) );
128
129        if ( is_wp_error( $response ) ) {
130            return $response;
131        }
132
133        if ( ! wp_remote_retrieve_body( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
134            return new WP_Error( 'blog_token_check_failed', 'The blog token health check could not be performed.' );
135        }
136
137        $body = json_decode( wp_remote_retrieve_body( $response ), true );
138
139        return is_array( $body ) && isset( $body['is_healthy'] ) && true === $body['is_healthy'];
140    }
141
142    /**
143     * Obtains the auth token.
144     *
145     * @since 9.18.0 Added the `$extra_body` and `$token_details` parameters.
146     *
147     * @param array      $data          The request data.
148     * @param string     $token_api_url The URL of the Jetpack "token" API.
149     * @param array      $extra_body    Fields to send with the token request, next to `client_id` and `code`.
150     * @param array|null $token_details Set to what WordPress.com reported beyond the token: `connection_owner`
151     *                                  (bool), only when the response includes it. Left untouched on failure.
152     * @return object|WP_Error Returns the auth token on success.
153     *                          Returns a WP_Error on failure.
154     */
155    public function get( $data, $token_api_url, $extra_body = array(), &$token_details = null ) {
156        $roles = new Roles();
157        $role  = $roles->translate_current_user_to_role();
158
159        if ( ! $role ) {
160            return new WP_Error( 'role', __( 'An administrator for this blog must set up the Jetpack connection.', 'jetpack-connection' ) );
161        }
162
163        $client_secret = $this->get_access_token();
164        if ( ! $client_secret ) {
165            return new WP_Error( 'client_secret', __( 'You need to register your Jetpack before connecting it.', 'jetpack-connection' ) );
166        }
167
168        /**
169         * Filter the URL of the first time the user gets redirected back to your site for connection
170         * data processing.
171         *
172         * @since 1.7.0
173         * @since-jetpack 8.0.0
174         *
175         * @param string $redirect_url Defaults to the site admin URL.
176         */
177        $processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
178
179        $redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
180
181        /**
182        * Filter the URL to redirect the user back to when the authentication process
183        * is complete.
184        *
185        * @since 1.7.0
186        * @since-jetpack 8.0.0
187        *
188        * @param string $redirect_url Defaults to the site URL.
189        */
190        $redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
191
192        $redirect_uri = ( 'calypso' === $data['auth_type'] )
193            ? $data['redirect_uri']
194            : add_query_arg(
195                array(
196                    'handler'  => 'jetpack-connection-webhooks',
197                    'action'   => 'authorize',
198                    '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
199                    'redirect' => $redirect ? rawurlencode( $redirect ) : false,
200                ),
201                esc_url( $processing_url )
202            );
203
204        /**
205         * Filters the token request data.
206         *
207         * @since 1.7.0
208         * @since-jetpack 8.0.0
209         *
210         * @param array $request_data request data.
211         */
212        $body = apply_filters(
213            'jetpack_token_request_body',
214            array_merge(
215                $extra_body,
216                array(
217                    'client_id'     => Jetpack_Options::get_option( 'id' ),
218                    'client_secret' => $client_secret->secret,
219                    'grant_type'    => 'authorization_code',
220                    'code'          => $data['code'],
221                    'redirect_uri'  => $redirect_uri,
222                )
223            )
224        );
225
226        $args = array(
227            'method'  => 'POST',
228            'body'    => $body,
229            'headers' => array(
230                'Accept' => 'application/json',
231            ),
232        );
233        add_filter( 'http_request_timeout', array( $this, 'return_30' ), PHP_INT_MAX - 1 );
234        $response = Client::_wp_remote_request( $token_api_url, $args );
235        remove_filter( 'http_request_timeout', array( $this, 'return_30' ), PHP_INT_MAX - 1 );
236
237        if ( is_wp_error( $response ) ) {
238            return new WP_Error( 'token_http_request_failed', $response->get_error_message() );
239        }
240
241        $code   = wp_remote_retrieve_response_code( $response );
242        $entity = wp_remote_retrieve_body( $response );
243
244        if ( $entity ) {
245            $json = json_decode( $entity );
246        } else {
247            $json = false;
248        }
249
250        if ( 200 !== $code || ! empty( $json->error ) ) {
251            if ( empty( $json->error ) ) {
252                return new WP_Error( 'unknown', '', $code );
253            }
254
255            /* translators: Error description string. */
256            $error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack-connection' ), (string) $json->error_description ) : '';
257
258            return new WP_Error( (string) $json->error, $error_description, $code );
259        }
260
261        if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
262            return new WP_Error( 'access_token', '', $code );
263        }
264
265        if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
266            return new WP_Error( 'token_type', '', $code );
267        }
268
269        if ( empty( $json->scope ) ) {
270            return new WP_Error( 'scope', 'No Scope', $code );
271        }
272
273        // TODO: get rid of the error silencer.
274        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
275        @list( $role, $hmac ) = explode( ':', $json->scope );
276        if ( empty( $role ) || empty( $hmac ) ) {
277            return new WP_Error( 'scope', 'Malformed Scope', $code );
278        }
279
280        if ( $this->sign_role( $role ) !== $json->scope ) {
281            return new WP_Error( 'scope', 'Invalid Scope', $code );
282        }
283
284        $cap = $roles->translate_role_to_cap( $role );
285        if ( ! $cap ) {
286            return new WP_Error( 'scope', 'No Cap', $code );
287        }
288
289        if ( ! current_user_can( $cap ) ) {
290            return new WP_Error( 'scope', 'current_user_cannot', $code );
291        }
292
293        // A missing field means WordPress.com didn't decide, which is not the same as `false`.
294        $token_details = array();
295        if ( isset( $json->connection_owner ) ) {
296            $token_details['connection_owner'] = (bool) $json->connection_owner;
297        }
298
299        return (string) $json->access_token;
300    }
301
302    /**
303     * Enters a user token into the user_tokens option
304     *
305     * @param int    $user_id The user id.
306     * @param string $token The user token.
307     * @param bool   $is_master_user Whether the user is the master user.
308     * @return bool
309     */
310    public function update_user_token( $user_id, $token, $is_master_user ) {
311        // Not designed for concurrent updates.
312        $user_tokens = $this->get_user_tokens();
313        if ( ! is_array( $user_tokens ) ) {
314            $user_tokens = array();
315        }
316        $user_tokens[ $user_id ] = $token;
317        if ( $is_master_user ) {
318            $master_user = $user_id;
319            $options     = compact( 'user_tokens', 'master_user' );
320        } else {
321            $options = compact( 'user_tokens' );
322        }
323        $updated = Jetpack_Options::update_options( $options );
324
325        /**
326         * Fires when the user token gets replaced.
327         *
328         * @since 1.29.0
329         * @since 9.8.1 Fired from Tokens::update_user_token() so every write path (authorize, provisioning, CLI) clears stale connection errors, not just the REST endpoint.
330         *
331         * @param int    $user_id User ID.
332         * @param string $token   New user token.
333         */
334        do_action( 'jetpack_updated_user_token', $user_id, $token );
335
336        return $updated;
337    }
338
339    /**
340     * Sign a user role with the master access token.
341     * If not specified, will default to the current user.
342     *
343     * @access public
344     *
345     * @param string $role    User role.
346     * @param int    $user_id ID of the user.
347     * @return string Signed user role.
348     */
349    public function sign_role( $role, $user_id = null ) {
350        if ( empty( $user_id ) ) {
351            $user_id = (int) get_current_user_id();
352        }
353
354        if ( ! $user_id ) {
355            return false;
356        }
357
358        $token = $this->get_access_token();
359        if ( ! $token || is_wp_error( $token ) ) {
360            return false;
361        }
362
363        return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
364    }
365
366    /**
367     * Increases the request timeout value to 30 seconds.
368     *
369     * @return int Returns 30.
370     */
371    public function return_30() {
372        return 30;
373    }
374
375    /**
376     * Gets the requested token.
377     *
378     * Tokens are one of two types:
379     * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
380     *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
381     *    are not associated with a user account. They represent the site's connection with
382     *    the Jetpack servers.
383     * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
384     *
385     * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
386     * token, and $private is a secret that should never be displayed anywhere or sent
387     * over the network; it's used only for signing things.
388     *
389     * Blog Tokens can be "Normal" or "Special".
390     * * Normal: The result of a normal connection flow. They look like
391     *   "{$random_string_1}.{$random_string_2}"
392     *   That is, $token_key and $private are both random strings.
393     *   Sites only have one Normal Blog Token. Normal Tokens are found in either
394     *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
395     *   constant (rare).
396     * * Special: A connection token for sites that have gone through an alternative
397     *   connection flow. They look like:
398     *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
399     *   That is, $private is a random string and $token_key has a special structure with
400     *   lots of semicolons.
401     *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
402     *   JETPACK_BLOG_TOKEN constant.
403     *
404     * In particular, note that Normal Blog Tokens never start with ";" and that
405     * Special Blog Tokens always do.
406     *
407     * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
408     * order:
409     * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
410     * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
411     * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
412     *
413     * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
414     * @param string|false $token_key If provided, check that the token matches the provided input.
415     * @param bool|true    $suppress_errors If true, return a falsy value when the token isn't found; When false, return a descriptive WP_Error when the token isn't found.
416     *
417     * @return object|false|WP_Error
418     */
419    public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
420        if ( $this->is_locked() ) {
421            $this->delete_all();
422            return false;
423        }
424
425        $possible_special_tokens = array();
426        $possible_normal_tokens  = array();
427        $user_tokens             = $this->get_user_tokens();
428
429        if ( $user_id ) {
430            $resolved_user_id = true === $user_id ? (int) Jetpack_Options::get_option( 'master_user' ) : (int) $user_id;
431
432            if ( ! $user_tokens ) {
433                return $suppress_errors ? false : new WP_Error( 'no_user_tokens', __( 'No user tokens found', 'jetpack-connection' ), array( 'user_id' => $resolved_user_id ) );
434            }
435            if ( true === $user_id ) { // connection owner.
436                if ( ! $resolved_user_id ) {
437                    return $suppress_errors ? false : new WP_Error( 'empty_master_user_option', __( 'No primary user defined', 'jetpack-connection' ) );
438                }
439                $user_id = $resolved_user_id;
440            }
441            if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
442                // translators: %s is the user ID.
443                return $suppress_errors ? false : new WP_Error( 'no_token_for_user', sprintf( __( 'No token for user %d', 'jetpack-connection' ), $user_id ), array( 'user_id' => (int) $user_id ) );
444            }
445            $user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
446            if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
447                // translators: %s is the user ID.
448                return $suppress_errors ? false : new WP_Error( 'token_malformed', sprintf( __( 'Token for user %d is malformed', 'jetpack-connection' ), $user_id ), array( 'user_id' => (int) $user_id ) );
449            }
450            if ( $user_token_chunks[2] !== (string) $user_id ) {
451                // translators: %1$d is the ID of the requested user. %2$d is the user ID found in the token.
452                return $suppress_errors ? false : new WP_Error( 'user_id_mismatch', sprintf( __( 'Requesting user_id %1$d does not match token user_id %2$d', 'jetpack-connection' ), $user_id, $user_token_chunks[2] ), array( 'user_id' => (int) $user_id ) );
453            }
454            $possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
455        } else {
456            $stored_blog_token = Jetpack_Options::get_option( 'blog_token' );
457            if ( $stored_blog_token ) {
458                $possible_normal_tokens[] = $stored_blog_token;
459            }
460
461            $defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
462
463            if ( $defined_tokens_string ) {
464                $defined_tokens = explode( ',', $defined_tokens_string );
465                foreach ( $defined_tokens as $defined_token ) {
466                    if ( ';' === $defined_token[0] ) {
467                        $possible_special_tokens[] = $defined_token;
468                    } else {
469                        $possible_normal_tokens[] = $defined_token;
470                    }
471                }
472            }
473        }
474
475        if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
476            $possible_tokens = $possible_normal_tokens;
477        } else {
478            $possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
479        }
480
481        if ( ! $possible_tokens ) {
482            // If no user tokens were found, it would have failed earlier, so this is about blog token.
483            return $suppress_errors ? false : new WP_Error( 'no_possible_tokens', __( 'No blog token found', 'jetpack-connection' ) );
484        }
485
486        $valid_token = false;
487
488        if ( false === $token_key ) {
489            // Use first token.
490            $valid_token = $possible_tokens[0];
491        } elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
492            // Use first normal token.
493            $valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
494        } else {
495            // Use the token matching $token_key or false if none.
496            // Ensure we check the full key.
497            $token_check = rtrim( $token_key, '.' ) . '.';
498
499            foreach ( $possible_tokens as $possible_token ) {
500                if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
501                    $valid_token = $possible_token;
502                    break;
503                }
504            }
505        }
506
507        if ( ! $valid_token ) {
508            if ( $user_id ) {
509                // translators: %d is the user ID.
510                return $suppress_errors ? false : new WP_Error( 'no_valid_user_token', sprintf( __( 'Invalid token for user %d', 'jetpack-connection' ), $user_id ), array( 'user_id' => (int) $user_id ) );
511            } else {
512                return $suppress_errors ? false : new WP_Error( 'no_valid_blog_token', __( 'Invalid blog token', 'jetpack-connection' ) );
513            }
514        }
515
516        return (object) array(
517            'secret'           => $valid_token,
518            'external_user_id' => (int) $user_id,
519        );
520    }
521
522    /**
523     * Updates the blog token to a new value.
524     *
525     * @access public
526     *
527     * @param string $token the new blog token value.
528     * @return Boolean Whether updating the blog token was successful.
529     */
530    public function update_blog_token( $token ) {
531        return Jetpack_Options::update_option( 'blog_token', $token );
532    }
533
534    /**
535     * Unlinks the current user from the linked WordPress.com user.
536     *
537     * @access public
538     * @static
539     *
540     * @todo Refactor to properly load the XMLRPC client independently.
541     *
542     * @param int $user_id The user identifier.
543     *
544     * @return bool Whether the disconnection of the user was successful.
545     */
546    public function disconnect_user( $user_id ) {
547        $tokens = $this->get_user_tokens();
548        if ( ! $tokens ) {
549            return false;
550        }
551
552        if ( ! isset( $tokens[ $user_id ] ) ) {
553            return false;
554        }
555
556        unset( $tokens[ $user_id ] );
557
558        $this->update_user_tokens( $tokens );
559
560        return true;
561    }
562
563    /**
564     * Returns an array of user_id's that have user tokens for communicating with wpcom.
565     * Able to select by specific capability.
566     *
567     * @deprecated 1.30.0
568     * @see Manager::get_connected_users
569     *
570     * @param string   $capability The capability of the user.
571     * @param int|null $limit How many connected users to get before returning.
572     * @return array Array of WP_User objects if found.
573     */
574    public function get_connected_users( $capability = 'any', $limit = null ) {
575        _deprecated_function( __METHOD__, '1.30.0' );
576        return ( new Manager( 'jetpack' ) )->get_connected_users( $capability, $limit );
577    }
578
579    /**
580     * Fetches a signed token.
581     *
582     * @param object $token the token.
583     * @return WP_Error|string a signed token
584     */
585    public function get_signed_token( $token ) {
586        if ( ! isset( $token->secret ) || empty( $token->secret ) ) {
587            return new WP_Error( 'invalid_token' );
588        }
589
590        list( $token_key, $token_secret ) = explode( '.', $token->secret );
591
592        $token_key = sprintf(
593            '%s:%d:%d',
594            $token_key,
595            Constants::get_constant( 'JETPACK__API_VERSION' ),
596            $token->external_user_id
597        );
598
599        $timestamp = time();
600
601        if ( function_exists( 'wp_generate_password' ) ) {
602            $nonce = wp_generate_password( 10, false );
603        } else {
604            $nonce = substr( sha1( (string) wp_rand( 0, 1000000 ) ), 0, 10 );
605        }
606
607        $normalized_request_string = implode(
608            "\n",
609            array(
610                $token_key,
611                $timestamp,
612                $nonce,
613            )
614        ) . "\n";
615
616        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
617        $signature = base64_encode( hash_hmac( 'sha1', $normalized_request_string, $token_secret, true ) );
618
619        $auth = array(
620            'token'     => $token_key,
621            'timestamp' => $timestamp,
622            'nonce'     => $nonce,
623            'signature' => $signature,
624        );
625
626        $header_pieces = array();
627        foreach ( $auth as $key => $value ) {
628            $header_pieces[] = sprintf( '%s="%s"', $key, $value );
629        }
630
631        return implode( ' ', $header_pieces );
632    }
633
634    /**
635     * Gets the list of user tokens
636     *
637     * @since 1.30.0
638     *
639     * @return bool|array An array of user tokens where keys are user IDs and values are the tokens. False if no user token is found.
640     */
641    public function get_user_tokens() {
642        return Jetpack_Options::get_option( 'user_tokens' );
643    }
644
645    /**
646     * Updates the option that stores the user tokens
647     *
648     * @since 1.30.0
649     *
650     * @param array $tokens An array of user tokens where keys are user IDs and values are the tokens.
651     * @return bool Was the option successfully updated?
652     *
653     * @todo add validate the input.
654     */
655    public function update_user_tokens( $tokens ) {
656        return Jetpack_Options::update_option( 'user_tokens', $tokens );
657    }
658
659    /**
660     * Lock the tokens to the current site URL.
661     *
662     * @param int $timespan How long the tokens should be locked, in seconds.
663     *
664     * @return bool
665     */
666    public function set_lock( $timespan = HOUR_IN_SECONDS ) {
667        try {
668            $expires = ( new DateTime() )->add( DateInterval::createFromDateString( (int) $timespan . ' seconds' ) );
669        } catch ( Exception $e ) {
670            return false;
671        }
672
673        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
674        return Jetpack_Options::update_option( 'token_lock', $expires->format( static::DATE_FORMAT_ATOM ) . '|||' . base64_encode( Urls::site_url() ) );
675    }
676
677    /**
678     * Remove the site lock from tokens.
679     *
680     * @return bool
681     */
682    public function remove_lock() {
683        Jetpack_Options::delete_option( 'token_lock' );
684
685        return true;
686    }
687
688    /**
689     * Check if the domain is locked, remove the lock if needed.
690     * Possible scenarios:
691     * - lock expired, site URL matches the lock URL: remove the lock, return false.
692     * - lock not expired, site URL matches the lock URL: return false.
693     * - site URL does not match the lock URL (expiration date is ignored): return true, do not remove the lock.
694     *
695     * @return bool
696     */
697    public function is_locked() {
698        $the_lock = Jetpack_Options::get_option( 'token_lock' );
699        if ( ! $the_lock ) {
700            // Not locked.
701            return false;
702        }
703
704        $the_lock = explode( '|||', $the_lock, 2 );
705        if ( count( $the_lock ) !== 2 ) {
706            // Something's wrong with the lock.
707            $this->remove_lock();
708            return false;
709        }
710
711        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
712        $locked_site_url = base64_decode( $the_lock[1] );
713        $expires         = $the_lock[0];
714
715        $expiration_date = DateTime::createFromFormat( static::DATE_FORMAT_ATOM, $expires );
716        if ( false === $expiration_date || ! $locked_site_url ) {
717            // Something's wrong with the lock.
718            $this->remove_lock();
719            return false;
720        }
721
722        if ( Urls::site_url() === $locked_site_url ) {
723            if ( new DateTime() > $expiration_date ) {
724                // Site lock expired.
725                // Site URL matches, removing the lock.
726                $this->remove_lock();
727            }
728
729            return false;
730        }
731
732        // Site URL doesn't match.
733        return true;
734    }
735}