Completed
Push — add/user-authentication ( 34ed8f...93b97f )
by
unknown
288:07 queued 279:09
created

Manager::internal_verify_xml_rpc_signature()   F

Complexity

Conditions 28
Paths 1185

Size

Total Lines 147

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 28
nc 1185
nop 0
dl 0
loc 147
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * The Jetpack Connection manager class file.
4
 *
5
 * @package jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Tracking;
12
13
/**
14
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
15
 * and Jetpack.
16
 */
17
class Manager implements Manager_Interface {
18
19
	const SECRETS_MISSING        = 'secrets_missing';
20
	const SECRETS_EXPIRED        = 'secrets_expired';
21
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
22
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
23
	const JETPACK_MASTER_USER    = true;
24
25
	/**
26
	 * The procedure that should be run to generate secrets.
27
	 *
28
	 * @var Callable
29
	 */
30
	protected $secret_callable;
31
32
	/**
33
	 * Creates an instance of the connection manager.
34
	 */
35
	public function __construct() {
36
	}
37
38
	/**
39
	 * Initializes required listeners. This is done separately from the constructors
40
	 * because some objects sometimes need to instantiate separate objects of this class.
41
	 */
42
	public function init() {
43
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
44
		if (
45
			isset( $_GET['jetpack'] )
46
			&& 'comms' === $_GET['jetpack']
47
			&& isset( $_GET['for'] )
48
			&& 'jetpack' === $_GET['for']
49
		) {
50
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
51
				define( 'XMLRPC_REQUEST', true );
52
			}
53
54
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
55
56
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
57
		}
58
59
		if (
60
			defined( 'XMLRPC_REQUEST' )
61
			&& XMLRPC_REQUEST
62
			&& isset( $_GET['for'] )
63
			&& 'jetpack' == $_GET['for']
64
		) {
65
			// Display errors can cause the XML to be not well formed.
66
			// @ini_set( 'display_errors', false ); // phpcs:ignore
67
68
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server( $this );
0 ignored issues
show
Bug introduced by
The property xmlrpc_server does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
69
70
			$this->require_jetpack_authentication();
71
72
			if ( $this->is_active() ) {
73
				// Hack to preserve $HTTP_RAW_POST_DATA.
74
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
75
76 View Code Duplication
				if ( $this->verify_xml_rpc_signature() ) {
77
					// The actual API methods.
78
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
79
				} else {
80
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
81
					// active Jetpack connection, so that additional users can link their account.
82
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
83
				}
84 View Code Duplication
			} else {
85
				new XMLRPC_Connector( $this );
86
87
				// The bootstrap API methods.
88
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
89
90
				if ( $this->verify_xml_rpc_signature() ) {
91
					// The jetpack Provision method is available for blog-token-signed requests.
92
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
93
				}
94
			}
95
96
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
97
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
98
		} elseif (
99
			is_admin() &&
100
			isset( $_POST['action'] ) && (
101
				'jetpack_upload_file' == $_POST['action'] ||
102
				'jetpack_update_file' == $_POST['action']
103
			)
104
		) {
105
			$this->require_jetpack_authentication();
106
			$this->add_remote_request_handlers();
0 ignored issues
show
Bug introduced by
The method add_remote_request_handlers() does not seem to exist on object<Automattic\Jetpack\Connection\Manager>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
107
		} else {
108
			if ( $this->is_active() ) {
109
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
110
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
111
			} else {
112
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
113
			}
114
		}
115
	}
116
117
	/**
118
	 * Initializes the REST API connector on the init hook.
119
	 */
120
	public function initialize_rest_api_registration_connector() {
121
		new REST_Connector( $this );
122
	}
123
124
	/**
125
	 * Initializes all needed hooks and request handlers. Handles API calls, upload
126
	 * requests, authentication requests. Also XMLRPC options requests.
127
	 * Fallback XMLRPC is also a bridge, but probably can be a class that inherits
128
	 * this one. Among other things it should strip existing methods.
129
	 *
130
	 * @param Array $methods an array of API method names for the Connection to accept and
131
	 *                       pass on to existing callables. It's possible to specify whether
132
	 *                       each method should be available for unauthenticated calls or not.
133
	 * @see Jetpack::__construct
134
	 */
135
	public function initialize( $methods ) {
136
		$methods;
137
	}
138
139
	/**
140
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
141
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
142
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
143
	 * which is accessible via a different URI. Most of the below is copied directly
144
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
145
	 */
146
	public function alternate_xmlrpc() {
147
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
148
		global $HTTP_RAW_POST_DATA;
149
150
		// Some browser-embedded clients send cookies. We don't want them.
151
		$_COOKIE = array();
152
153
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
154
		// but we can do it ourself.
155
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
156
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
157
		}
158
159
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
160
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
161
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
162
		}
163
164
		// phpcs:enable
165
166
		include_once ABSPATH . 'wp-admin/includes/admin.php';
167
		include_once ABSPATH . WPINC . '/class-IXR.php';
168
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
169
170
		/**
171
		 * Filters the class used for handling XML-RPC requests.
172
		 *
173
		 * @since 3.1.0
174
		 *
175
		 * @param string $class The name of the XML-RPC server class.
176
		 */
177
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
178
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
179
180
		// Fire off the request.
181
		nocache_headers();
182
		$wp_xmlrpc_server->serve_request();
183
184
		exit;
185
	}
186
187
	/**
188
	 * Removes all XML-RPC methods that are not `jetpack.*`.
189
	 * Only used in our alternate XML-RPC endpoint, where we want to
190
	 * ensure that Core and other plugins' methods are not exposed.
191
	 *
192
	 * @param array $methods
193
	 * @return array filtered $methods
194
	 */
195
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
196
		$jetpack_methods = array();
197
198
		foreach ( $methods as $method => $callback ) {
199
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
200
				$jetpack_methods[ $method ] = $callback;
201
			}
202
		}
203
204
		return $jetpack_methods;
205
	}
206
207
	/**
208
	 * Removes all other authentication methods not to allow other
209
	 * methods to validate unauthenticated requests.
210
	 */
211
	public function require_jetpack_authentication() {
212
		// Don't let anyone authenticate
213
		$_COOKIE = array();
214
		remove_all_filters( 'authenticate' );
215
		remove_all_actions( 'wp_login_failed' );
216
217
		if ( $this->is_active() ) {
218
			// Allow Jetpack authentication.
219
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
220
		}
221
	}
222
223
	/**
224
	 * Authenticates XML-RPC and other requests from the Jetpack Server
225
	 *
226
	 * @param WP_User|Mixed $user user object if authenticated.
227
	 * @param String        $username username.
228
	 * @param String        $password password string.
229
	 * @return WP_User|Mixed authenticated user or error.
230
	 */
231
	public function authenticate_jetpack( $user, $username, $password ) {
232
		if ( is_a( $user, 'WP_User' ) ) {
233
			return $user;
234
		}
235
236
		$token_details = $this->verify_xml_rpc_signature();
237
238
		if ( ! $token_details ) {
239
			return $user;
240
		}
241
242
		if ( 'user' !== $token_details['type'] ) {
243
			return $user;
244
		}
245
246
		if ( ! $token_details['user_id'] ) {
247
			return $user;
248
		}
249
250
		nocache_headers();
251
252
		return new WP_User( $token_details['user_id'] );
253
	}
254
255
	/**
256
	 * Verifies the signature of the current request.
257
	 *
258
	 * @return false|array
259
	 */
260
	public function verify_xml_rpc_signature() {
261
		if ( is_null( $this->xmlrpc_verification ) ) {
262
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
0 ignored issues
show
Bug introduced by
The property xmlrpc_verification does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
263
264
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
265
				/**
266
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
267
				 *
268
				 * Error codes:
269
				 * - malformed_token
270
				 * - malformed_user_id
271
				 * - unknown_token
272
				 * - could_not_sign
273
				 * - invalid_nonce
274
				 * - signature_mismatch
275
				 *
276
				 * @since 7.5.0
277
				 *
278
				 * @param WP_Error $signature_verification_error The verification error
279
				 */
280
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
281
			}
282
		}
283
284
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
285
	}
286
287
	/**
288
	 * Verifies the signature of the current request.
289
	 *
290
	 * This function has side effects and should not be used. Instead,
291
	 * use the memoized version `->verify_xml_rpc_signature()`.
292
	 *
293
	 * @internal
294
	 */
295
	private function internal_verify_xml_rpc_signature() {
296
		// It's not for us
297
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
298
			return false;
299
		}
300
301
		$signature_details = array(
302
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
303
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
304
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
305
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
306
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
307
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
308
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
309
		);
310
311
		@list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
312
		if (
313
			empty( $token_key )
314
		||
315
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
316
		) {
317
			return new \WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
318
		}
319
320
		if ( '0' === $user_id ) {
321
			$token_type = 'blog';
322
			$user_id    = 0;
323
		} else {
324
			$token_type = 'user';
325
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
326
				return new \WP_Error(
327
					'malformed_user_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_user_id'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
328
					'Malformed user_id in request',
329
					compact( 'signature_details' )
330
				);
331
			}
332
			$user_id = (int) $user_id;
333
334
			$user = new \WP_User( $user_id );
335
			if ( ! $user || ! $user->exists() ) {
336
				return new \WP_Error(
337
					'unknown_user',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_user'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
338
					sprintf( 'User %d does not exist', $user_id ),
339
					compact( 'signature_details' )
340
				);
341
			}
342
		}
343
344
		$token = $this->get_access_token( $user_id, $token_key, false );
345
		if ( is_wp_error( $token ) ) {
346
			$token->add_data( compact( 'signature_details' ) );
347
			return $token;
348
		} elseif ( ! $token ) {
349
			return new \WP_Error(
350
				'unknown_token',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
351
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
352
				compact( 'signature_details' )
353
			);
354
		}
355
356
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
357
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
358
			$post_data   = $_POST;
359
			$file_hashes = array();
360
			foreach ( $post_data as $post_data_key => $post_data_value ) {
361
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
362
					continue;
363
				}
364
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
365
				$file_hashes[ $post_data_key ] = $post_data_value;
366
			}
367
368
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
369
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
370
				$post_data[ $post_data_key ] = $post_data_value;
371
			}
372
373
			ksort( $post_data );
374
375
			$body = http_build_query( stripslashes_deep( $post_data ) );
376
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
0 ignored issues
show
Bug introduced by
The property HTTP_RAW_POST_DATA does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
377
			$body = file_get_contents( 'php://input' );
378
		} else {
379
			$body = null;
380
		}
381
382
		$signature = $jetpack_signature->sign_current_request(
383
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body )
384
		);
385
386
		$signature_details['url'] = $jetpack_signature->current_request_url;
387
388
		if ( ! $signature ) {
389
			return new \WP_Error(
390
				'could_not_sign',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'could_not_sign'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
391
				'Unknown signature error',
392
				compact( 'signature_details' )
393
			);
394
		} elseif ( is_wp_error( $signature ) ) {
395
			return $signature;
396
		}
397
398
		$timestamp = (int) $_GET['timestamp'];
399
		$nonce     = stripslashes( (string) $_GET['nonce'] );
400
401
		// Use up the nonce regardless of whether the signature matches.
402
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
0 ignored issues
show
Bug introduced by
The method add_nonce() does not seem to exist on object<Automattic\Jetpack\Connection\Manager>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
403
			return new \WP_Error(
404
				'invalid_nonce',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
405
				'Could not add nonce',
406
				compact( 'signature_details' )
407
			);
408
		}
409
410
		// Be careful about what you do with this debugging data.
411
		// If a malicious requester has access to the expected signature,
412
		// bad things might be possible.
413
		$signature_details['expected'] = $signature;
414
415
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
416
			return new \WP_Error(
417
				'signature_mismatch',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'signature_mismatch'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
418
				'Signature mismatch',
419
				compact( 'signature_details' )
420
			);
421
		}
422
423
		/**
424
		 * Action for additional token checking.
425
		 *
426
		 * @since 7.5.0
427
		 *
428
		 * @param Array $post_data request data.
429
		 * @param Array $token_data token data.
430
		 */
431
		return apply_filter(
432
			'jetpack_signature_check_token',
433
			array(
434
				'type'      => $token_type,
435
				'token_key' => $token_key,
436
				'user_id'   => $token->external_user_id,
437
			),
438
			$token,
439
			$this->HTTP_RAW_POST_DATA
440
		);
441
	}
442
443
	/**
444
	 * Returns true if the current site is connected to WordPress.com.
445
	 *
446
	 * @return Boolean is the site connected?
447
	 */
448
	public function is_active() {
449
		return (bool) $this->get_access_token( self::JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
self::JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
450
	}
451
452
	/**
453
	 * Returns true if the user with the specified identifier is connected to
454
	 * WordPress.com.
455
	 *
456
	 * @param Integer|Boolean $user_id the user identifier.
457
	 * @return Boolean is the user connected?
458
	 */
459
	public function is_user_connected( $user_id = false ) {
460
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
461
		if ( ! $user_id ) {
462
			return false;
463
		}
464
465
		return (bool) $this->get_access_token( $user_id );
466
	}
467
468
	/**
469
	 * Get the wpcom user data of the current|specified connected user.
470
	 *
471
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
472
	 * @return Object the user object.
473
	 */
474 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
475
		if ( ! $user_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user_id of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
476
			$user_id = get_current_user_id();
477
		}
478
479
		$transient_key    = "jetpack_connected_user_data_$user_id";
480
		$cached_user_data = get_transient( $transient_key );
481
482
		if ( $cached_user_data ) {
483
			return $cached_user_data;
484
		}
485
486
		\Jetpack::load_xml_rpc_client();
487
		$xml = new \Jetpack_IXR_Client(
488
			array(
489
				'user_id' => $user_id,
490
			)
491
		);
492
		$xml->query( 'wpcom.getUser' );
493
		if ( ! $xml->isError() ) {
494
			$user_data = $xml->getResponse();
495
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
496
			return $user_data;
497
		}
498
499
		return false;
500
	}
501
502
	/**
503
	 * Is the user the connection owner.
504
	 *
505
	 * @param Integer $user_id the user identifier.
506
	 * @return Boolean is the user the connection owner?
507
	 */
508
	public function is_connection_owner( $user_id ) {
509
		return $user_id;
510
	}
511
512
	/**
513
	 * Unlinks the current user from the linked WordPress.com user
514
	 *
515
	 * @param Integer $user_id the user identifier.
516
	 */
517
	public static function disconnect_user( $user_id ) {
518
		return $user_id;
519
	}
520
521
	/**
522
	 * Initializes a transport server, whatever it may be, saves into the object property.
523
	 * Should be changed to be protected.
524
	 */
525
	public function initialize_server() {
526
527
	}
528
529
	/**
530
	 * Checks if the current request is properly authenticated, bails if not.
531
	 * Should be changed to be protected.
532
	 */
533
	public function require_authentication() {
534
535
	}
536
537
	/**
538
	 * Verifies the correctness of the request signature.
539
	 * Should be changed to be protected.
540
	 */
541
	public function verify_signature() {
542
543
	}
544
545
	/**
546
	 * Returns the requested Jetpack API URL.
547
	 *
548
	 * @param String $relative_url the relative API path.
549
	 * @return String API URL.
550
	 */
551
	public function api_url( $relative_url ) {
552
		$api_base = Constants::get_constant( 'JETPACK__API_BASE' );
553
		$version  = Constants::get_constant( 'JETPACK__API_VERSION' );
554
555
		$api_base = $api_base ? $api_base : 'https://jetpack.wordpress.com/jetpack.';
556
		$version  = $version ? '/' . $version . '/' : '/1/';
557
558
		return rtrim( $api_base . $relative_url, '/\\' ) . $version;
559
	}
560
561
	/**
562
	 * Attempts Jetpack registration which sets up the site for connection. Should
563
	 * remain public because the call to action comes from the current site, not from
564
	 * WordPress.com.
565
	 *
566
	 * @return Integer zero on success, or a bitmask on failure.
567
	 */
568
	public function register() {
569
		// TODO: Tracking can't yet function without static Jetpack methods.
570
571
		add_action( 'pre_update_jetpack_option_register', array( '\Jetpack_Options', 'delete_option' ) );
572
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
573
574 View Code Duplication
		if (
575
			empty( $secrets['secret_1'] ) ||
576
			empty( $secrets['secret_2'] ) ||
577
			empty( $secrets['exp'] )
578
		) {
579
			return new \WP_Error( 'missing_secrets' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_secrets'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
580
		}
581
582
		// Better to try (and fail) to set a higher timeout than this system
583
		// supports than to have register fail for more users than it should.
584
		$timeout = $this->set_min_time_limit( 60 ) / 2;
585
586
		$gmt_offset = get_option( 'gmt_offset' );
587
		if ( ! $gmt_offset ) {
588
			$gmt_offset = 0;
589
		}
590
591
		$stats_options = get_option( 'stats_options' );
592
		$stats_id      = isset( $stats_options['blog_id'] )
593
			? $stats_options['blog_id']
594
			: null;
595
596
		$args = array(
597
			'method'  => 'POST',
598
			'body'    => array(
599
				'siteurl'         => site_url(),
600
				'home'            => home_url(),
601
				'gmt_offset'      => $gmt_offset,
602
				'timezone_string' => (string) get_option( 'timezone_string' ),
603
				'site_name'       => (string) get_option( 'blogname' ),
604
				'secret_1'        => $secrets['secret_1'],
605
				'secret_2'        => $secrets['secret_2'],
606
				'site_lang'       => get_locale(),
607
				'timeout'         => $timeout,
608
				'stats_id'        => $stats_id,
609
				'state'           => get_current_user_id(),
610
				'site_created'    => $this->get_assumed_site_creation_date(),
611
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
612
			),
613
			'headers' => array(
614
				'Accept' => 'application/json',
615
			),
616
			'timeout' => $timeout,
617
		);
618
619
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
620
621
		// TODO: fix URLs for bad hosts.
622
		$response = Client::_wp_remote_request(
623
			$this->api_url( 'register' ),
624
			$args,
625
			true
626
		);
627
628
		// Make sure the response is valid and does not contain any Jetpack errors.
629
		$registration_details = $this->validate_remote_register_response( $response );
630
631
		if ( is_wp_error( $registration_details ) ) {
632
			return $registration_details;
633
		} elseif ( ! $registration_details ) {
634
			return new \WP_Error(
635
				'unknown_error',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
636
				'',
637
				wp_remote_retrieve_response_code( $response )
638
			);
639
		}
640
641 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
642
			return new \WP_Error(
643
				'jetpack_secret',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_secret'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
644
				'',
645
				wp_remote_retrieve_response_code( $response )
646
			);
647
		}
648
649
		if ( isset( $registration_details->jetpack_public ) ) {
650
			$jetpack_public = (int) $registration_details->jetpack_public;
651
		} else {
652
			$jetpack_public = false;
653
		}
654
655
		\Jetpack_Options::update_options(
656
			array(
657
				'id'         => (int) $registration_details->jetpack_id,
658
				'blog_token' => (string) $registration_details->jetpack_secret,
659
				'public'     => $jetpack_public,
660
			)
661
		);
662
663
		/**
664
		 * Fires when a site is registered on WordPress.com.
665
		 *
666
		 * @since 3.7.0
667
		 *
668
		 * @param int $json->jetpack_id Jetpack Blog ID.
669
		 * @param string $json->jetpack_secret Jetpack Blog Token.
670
		 * @param int|bool $jetpack_public Is the site public.
671
		 */
672
		do_action(
673
			'jetpack_site_registered',
674
			$registration_details->jetpack_id,
675
			$registration_details->jetpack_secret,
676
			$jetpack_public
677
		);
678
679
		// TODO: Make jumpstart run on jetpack_site_registered action.
680
681
		return true;
682
	}
683
684
	/**
685
	 * Takes the response from the Jetpack register new site endpoint and
686
	 * verifies it worked properly.
687
	 *
688
	 * @since 2.6
689
	 *
690
	 * @param Mixed $response the response object, or the error object.
691
	 * @return string|WP_Error A JSON object on success or Jetpack_Error on failures
692
	 **/
693
	protected function validate_remote_register_response( $response ) {
694
		if ( is_wp_error( $response ) ) {
695
			return new \WP_Error(
696
				'register_http_request_failed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'register_http_request_failed'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
697
				$response->get_error_message()
698
			);
699
		}
700
701
		$code   = wp_remote_retrieve_response_code( $response );
702
		$entity = wp_remote_retrieve_body( $response );
703
704
		if ( $entity ) {
705
			$registration_response = json_decode( $entity );
706
		} else {
707
			$registration_response = false;
708
		}
709
710
		$code_type = intval( $code / 100 );
711
		if ( 5 === $code_type ) {
712
			return new \WP_Error( 'wpcom_5??', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wpcom_5??'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
713
		} elseif ( 408 === $code ) {
714
			return new \WP_Error( 'wpcom_408', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wpcom_408'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
715
		} elseif ( ! empty( $registration_response->error ) ) {
716
			if (
717
				'xml_rpc-32700' === $registration_response->error
718
				&& ! function_exists( 'xml_parser_create' )
719
			) {
720
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
721
			} else {
722
				$error_description = isset( $registration_response->error_description )
723
					? (string) $registration_response->error_description
724
					: '';
725
			}
726
727
			return new \WP_Error(
728
				(string) $registration_response->error,
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with (string) $registration_response->error.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
729
				$error_description,
730
				$code
731
			);
732
		} elseif ( 200 !== $code ) {
733
			return new \WP_Error( 'wpcom_bad_response', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wpcom_bad_response'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
734
		}
735
736
		// Jetpack ID error block.
737 View Code Duplication
		if ( empty( $registration_response->jetpack_id ) ) {
738
			return new \WP_Error(
739
				'jetpack_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_id'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
740
				/* translators: %s is an error message string */
741
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
742
				$entity
743
			);
744
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
745
			return new \WP_Error(
746
				'jetpack_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_id'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
747
				/* translators: %s is an error message string */
748
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
749
				$entity
750
			);
751
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
752
			return new \WP_Error(
753
				'jetpack_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_id'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
754
				/* translators: %s is an error message string */
755
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
756
				$entity
757
			);
758
		}
759
760
		return $registration_response;
761
	}
762
763
	/**
764
	 * Builds the timeout limit for queries talking with the wpcom servers.
765
	 *
766
	 * Based on local php max_execution_time in php.ini
767
	 *
768
	 * @since 5.4
769
	 * @return int
770
	 **/
771
	public function get_max_execution_time() {
772
		$timeout = (int) ini_get( 'max_execution_time' );
773
774
		// Ensure exec time set in php.ini.
775
		if ( ! $timeout ) {
776
			$timeout = 30;
777
		}
778
		return $timeout;
779
	}
780
781
	/**
782
	 * Sets a minimum request timeout, and returns the current timeout
783
	 *
784
	 * @since 5.4
785
	 * @param Integer $min_timeout the minimum timeout value.
786
	 **/
787 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
788
		$timeout = $this->get_max_execution_time();
789
		if ( $timeout < $min_timeout ) {
790
			$timeout = $min_timeout;
791
			set_time_limit( $timeout );
792
		}
793
		return $timeout;
794
	}
795
796
	/**
797
	 * Get our assumed site creation date.
798
	 * Calculated based on the earlier date of either:
799
	 * - Earliest admin user registration date.
800
	 * - Earliest date of post of any post type.
801
	 *
802
	 * @since 7.2.0
803
	 *
804
	 * @return string Assumed site creation date and time.
805
	 */
806 View Code Duplication
	public function get_assumed_site_creation_date() {
807
		$earliest_registered_users  = get_users(
808
			array(
809
				'role'    => 'administrator',
810
				'orderby' => 'user_registered',
811
				'order'   => 'ASC',
812
				'fields'  => array( 'user_registered' ),
813
				'number'  => 1,
814
			)
815
		);
816
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
817
818
		$earliest_posts = get_posts(
819
			array(
820
				'posts_per_page' => 1,
821
				'post_type'      => 'any',
822
				'post_status'    => 'any',
823
				'orderby'        => 'date',
824
				'order'          => 'ASC',
825
			)
826
		);
827
828
		// If there are no posts at all, we'll count only on user registration date.
829
		if ( $earliest_posts ) {
830
			$earliest_post_date = $earliest_posts[0]->post_date;
831
		} else {
832
			$earliest_post_date = PHP_INT_MAX;
833
		}
834
835
		return min( $earliest_registration_date, $earliest_post_date );
836
	}
837
838
	/**
839
	 * Adds the activation source string as a parameter to passed arguments.
840
	 *
841
	 * @param Array $args arguments that need to have the source added.
842
	 * @return Array $amended arguments.
843
	 */
844 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
845
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
846
847
		if ( $activation_source_name ) {
848
			$args['_as'] = urlencode( $activation_source_name );
849
		}
850
851
		if ( $activation_source_keyword ) {
852
			$args['_ak'] = urlencode( $activation_source_keyword );
853
		}
854
855
		return $args;
856
	}
857
858
	/**
859
	 * Returns the callable that would be used to generate secrets.
860
	 *
861
	 * @return Callable a function that returns a secure string to be used as a secret.
862
	 */
863
	protected function get_secret_callable() {
864
		if ( ! isset( $this->secret_callable ) ) {
865
			/**
866
			 * Allows modification of the callable that is used to generate connection secrets.
867
			 *
868
			 * @param Callable a function or method that returns a secret string.
869
			 */
870
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', 'wp_generate_password' );
871
		}
872
873
		return $this->secret_callable;
874
	}
875
876
	/**
877
	 * Generates two secret tokens and the end of life timestamp for them.
878
	 *
879
	 * @param String  $action  The action name.
880
	 * @param Integer $user_id The user identifier.
881
	 * @param Integer $exp     Expiration time in seconds.
882
	 */
883
	public function generate_secrets( $action, $user_id, $exp ) {
884
		$callable = $this->get_secret_callable();
885
886
		$secrets = \Jetpack_Options::get_raw_option(
887
			self::SECRETS_OPTION_NAME,
888
			array()
889
		);
890
891
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
892
893
		if (
894
			isset( $secrets[ $secret_name ] ) &&
895
			$secrets[ $secret_name ]['exp'] > time()
896
		) {
897
			return $secrets[ $secret_name ];
898
		}
899
900
		$secret_value = array(
901
			'secret_1' => call_user_func( $callable ),
902
			'secret_2' => call_user_func( $callable ),
903
			'exp'      => time() + $exp,
904
		);
905
906
		$secrets[ $secret_name ] = $secret_value;
907
908
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
909
		return $secrets[ $secret_name ];
910
	}
911
912
	/**
913
	 * Returns two secret tokens and the end of life timestamp for them.
914
	 *
915
	 * @param String  $action  The action name.
916
	 * @param Integer $user_id The user identifier.
917
	 * @return string|array an array of secrets or an error string.
918
	 */
919
	public function get_secrets( $action, $user_id ) {
920
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
921
		$secrets     = \Jetpack_Options::get_raw_option(
922
			self::SECRETS_OPTION_NAME,
923
			array()
924
		);
925
926
		if ( ! isset( $secrets[ $secret_name ] ) ) {
927
			return self::SECRETS_MISSING;
928
		}
929
930
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
931
			$this->delete_secrets( $action, $user_id );
932
			return self::SECRETS_EXPIRED;
933
		}
934
935
		return $secrets[ $secret_name ];
936
	}
937
938
	/**
939
	 * Deletes secret tokens in case they, for example, have expired.
940
	 *
941
	 * @param String  $action  The action name.
942
	 * @param Integer $user_id The user identifier.
943
	 */
944
	public function delete_secrets( $action, $user_id ) {
945
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
946
		$secrets     = \Jetpack_Options::get_raw_option(
947
			self::SECRETS_OPTION_NAME,
948
			array()
949
		);
950
		if ( isset( $secrets[ $secret_name ] ) ) {
951
			unset( $secrets[ $secret_name ] );
952
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
953
		}
954
	}
955
956
	/**
957
	 * Responds to a WordPress.com call to register the current site.
958
	 * Should be changed to protected.
959
	 *
960
	 * @param array $registration_data Array of [ secret_1, user_id ].
961
	 */
962
	public function handle_registration( array $registration_data ) {
963
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
964
		if ( empty( $registration_user_id ) ) {
965
			return new \WP_Error( 'registration_state_invalid', __( 'Invalid Registration State', 'jetpack' ), 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'registration_state_invalid'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
966
		}
967
968
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
969
	}
970
971
	/**
972
	 * Verify a Previously Generated Secret.
973
	 *
974
	 * @param string $action   The type of secret to verify.
975
	 * @param string $secret_1 The secret string to compare to what is stored.
976
	 * @param int    $user_id  The user ID of the owner of the secret.
977
	 */
978
	protected function verify_secrets( $action, $secret_1, $user_id ) {
979
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
980
		if ( ! in_array( $action, $allowed_actions, true ) ) {
981
			return new \WP_Error( 'unknown_verification_action', 'Unknown Verification Action', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_verification_action'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
982
		}
983
984
		$user = get_user_by( 'id', $user_id );
985
986
		/**
987
		 * We've begun verifying the previously generated secret.
988
		 *
989
		 * @since 7.5.0
990
		 *
991
		 * @param string   $action The type of secret to verify.
992
		 * @param \WP_User $user The user object.
993
		 */
994
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
995
996
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
997
			/**
998
			 * Verifying of the previously generated secret has failed.
999
			 *
1000
			 * @since 7.5.0
1001
			 *
1002
			 * @param string    $action  The type of secret to verify.
1003
			 * @param \WP_User  $user The user object.
1004
			 * @param \WP_Error $error The error object.
1005
			 */
1006
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1007
1008
			return $error;
1009
		};
1010
1011
		$stored_secrets = $this->get_secrets( $action, $user_id );
1012
		$this->delete_secrets( $action, $user_id );
1013
1014
		if ( empty( $secret_1 ) ) {
1015
			return $return_error(
1016
				new \WP_Error(
1017
					'verify_secret_1_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secret_1_missing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1018
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1019
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1020
					400
1021
				)
1022
			);
1023
		} elseif ( ! is_string( $secret_1 ) ) {
1024
			return $return_error(
1025
				new \WP_Error(
1026
					'verify_secret_1_malformed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secret_1_malformed'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1027
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1028
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1029
					400
1030
				)
1031
			);
1032
		} elseif ( empty( $user_id ) ) {
1033
			// $user_id is passed around during registration as "state".
1034
			return $return_error(
1035
				new \WP_Error(
1036
					'state_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'state_missing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1037
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1038
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1039
					400
1040
				)
1041
			);
1042
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1043
			return $return_error(
1044
				new \WP_Error(
1045
					'verify_secret_1_malformed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secret_1_malformed'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1046
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1047
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1048
					400
1049
				)
1050
			);
1051
		}
1052
1053
		if ( ! $stored_secrets ) {
1054
			return $return_error(
1055
				new \WP_Error(
1056
					'verify_secrets_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1057
					__( 'Verification secrets not found', 'jetpack' ),
1058
					400
1059
				)
1060
			);
1061
		} elseif ( is_wp_error( $stored_secrets ) ) {
1062
			$stored_secrets->add_data( 400 );
0 ignored issues
show
Bug introduced by
The method add_data cannot be called on $stored_secrets (of type string|array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1063
			return $return_error( $stored_secrets );
1064
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1065
			return $return_error(
1066
				new \WP_Error(
1067
					'verify_secrets_incomplete',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_incomplete'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1068
					__( 'Verification secrets are incomplete', 'jetpack' ),
1069
					400
1070
				)
1071
			);
1072
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1073
			return $return_error(
1074
				new \WP_Error(
1075
					'verify_secrets_mismatch',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_mismatch'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1076
					__( 'Secret mismatch', 'jetpack' ),
1077
					400
1078
				)
1079
			);
1080
		}
1081
1082
		/**
1083
		 * We've succeeded at verifying the previously generated secret.
1084
		 *
1085
		 * @since 7.5.0
1086
		 *
1087
		 * @param string   $action The type of secret to verify.
1088
		 * @param \WP_User $user The user object.
1089
		 */
1090
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1091
1092
		return $stored_secrets['secret_2'];
1093
	}
1094
1095
	/**
1096
	 * Responds to a WordPress.com call to authorize the current user.
1097
	 * Should be changed to protected.
1098
	 */
1099
	public function handle_authorization() {
1100
1101
	}
1102
1103
	/**
1104
	 * Builds a URL to the Jetpack connection auth page.
1105
	 * This needs rethinking.
1106
	 *
1107
	 * @param bool        $raw If true, URL will not be escaped.
1108
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
1109
	 *                              If string, will be a custom redirect.
1110
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
1111
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0.
1112
	 *
1113
	 * @return string Connect URL
1114
	 */
1115
	public function build_connect_url( $raw, $redirect, $from, $register ) {
1116
		return array( $raw, $redirect, $from, $register );
1117
	}
1118
1119
	/**
1120
	 * Disconnects from the Jetpack servers.
1121
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1122
	 */
1123
	public function disconnect_site() {
1124
1125
	}
1126
1127
	/**
1128
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1129
	 *
1130
	 * @param string $text The string to hash.
1131
	 * @return string
1132
	 */
1133
	public function sha1_base64( $text ) {
1134
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1135
	}
1136
1137
	/**
1138
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1139
	 *
1140
	 * @param string $domain The domain to check.
1141
	 *
1142
	 * @return bool|WP_Error
1143
	 */
1144
	public function is_usable_domain( $domain ) {
1145
1146
		// If it's empty, just fail out.
1147
		if ( ! $domain ) {
1148
			return new \WP_Error(
1149
				'fail_domain_empty',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'fail_domain_empty'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1150
				/* translators: %1$s is a domain name. */
1151
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1152
			);
1153
		}
1154
1155
		/**
1156
		 * Skips the usuable domain check when connecting a site.
1157
		 *
1158
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1159
		 *
1160
		 * @since 4.1.0
1161
		 *
1162
		 * @param bool If the check should be skipped. Default false.
1163
		 */
1164
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1165
			return true;
1166
		}
1167
1168
		// None of the explicit localhosts.
1169
		$forbidden_domains = array(
1170
			'wordpress.com',
1171
			'localhost',
1172
			'localhost.localdomain',
1173
			'127.0.0.1',
1174
			'local.wordpress.test',         // VVV pattern.
1175
			'local.wordpress-trunk.test',   // VVV pattern.
1176
			'src.wordpress-develop.test',   // VVV pattern.
1177
			'build.wordpress-develop.test', // VVV pattern.
1178
		);
1179 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1180
			return new \WP_Error(
1181
				'fail_domain_forbidden',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'fail_domain_forbidden'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1182
				sprintf(
1183
					/* translators: %1$s is a domain name. */
1184
					__(
1185
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1186
						'jetpack'
1187
					),
1188
					$domain
1189
				)
1190
			);
1191
		}
1192
1193
		// No .test or .local domains.
1194 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1195
			return new \WP_Error(
1196
				'fail_domain_tld',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'fail_domain_tld'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1197
				sprintf(
1198
					/* translators: %1$s is a domain name. */
1199
					__(
1200
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1201
						'jetpack'
1202
					),
1203
					$domain
1204
				)
1205
			);
1206
		}
1207
1208
		// No WPCOM subdomains.
1209 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1210
			return new \WP_Error(
1211
				'fail_subdomain_wpcom',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'fail_subdomain_wpcom'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1212
				sprintf(
1213
					/* translators: %1$s is a domain name. */
1214
					__(
1215
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1216
						'jetpack'
1217
					),
1218
					$domain
1219
				)
1220
			);
1221
		}
1222
1223
		// If PHP was compiled without support for the Filter module (very edge case).
1224
		if ( ! function_exists( 'filter_var' ) ) {
1225
			// Just pass back true for now, and let wpcom sort it out.
1226
			return true;
1227
		}
1228
1229
		return true;
1230
	}
1231
1232
	/**
1233
	 * Gets the requested token.
1234
	 *
1235
	 * Tokens are one of two types:
1236
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
1237
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
1238
	 *    are not associated with a user account. They represent the site's connection with
1239
	 *    the Jetpack servers.
1240
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
1241
	 *
1242
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
1243
	 * token, and $private is a secret that should never be displayed anywhere or sent
1244
	 * over the network; it's used only for signing things.
1245
	 *
1246
	 * Blog Tokens can be "Normal" or "Special".
1247
	 * * Normal: The result of a normal connection flow. They look like
1248
	 *   "{$random_string_1}.{$random_string_2}"
1249
	 *   That is, $token_key and $private are both random strings.
1250
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
1251
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
1252
	 *   constant (rare).
1253
	 * * Special: A connection token for sites that have gone through an alternative
1254
	 *   connection flow. They look like:
1255
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
1256
	 *   That is, $private is a random string and $token_key has a special structure with
1257
	 *   lots of semicolons.
1258
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
1259
	 *   JETPACK_BLOG_TOKEN constant.
1260
	 *
1261
	 * In particular, note that Normal Blog Tokens never start with ";" and that
1262
	 * Special Blog Tokens always do.
1263
	 *
1264
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
1265
	 * order:
1266
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
1267
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
1268
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
1269
	 *
1270
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1271
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1272
	 * @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.
1273
	 *
1274
	 * @return object|false
1275
	 */
1276
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1277
		$possible_special_tokens = array();
1278
		$possible_normal_tokens  = array();
1279
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
1280
1281
		if ( $user_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user_id of type false|integer is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1282
			if ( ! $user_tokens ) {
1283
				return $suppress_errors ? false : new \WP_Error( 'no_user_tokens' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_user_tokens'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1284
			}
1285
			if ( self::JETPACK_MASTER_USER === $user_id ) {
1286
				$user_id = \Jetpack_Options::get_option( 'master_user' );
1287
				if ( ! $user_id ) {
1288
					return $suppress_errors ? false : new \WP_Error( 'empty_master_user_option' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'empty_master_user_option'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1289
				}
1290
			}
1291
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
1292
				return $suppress_errors ? false : new \WP_Error( 'no_token_for_user', sprintf( 'No token for user %d', $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_token_for_user'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1293
			}
1294
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
1295 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
1296
				return $suppress_errors ? false : new \WP_Error( 'token_malformed', sprintf( 'Token \'%s\' for user %d is malformed', $user_tokens[ $user_id ], $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_malformed'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1297
			}
1298 View Code Duplication
			if ( $user_token_chunks[2] !== (string) $user_id ) {
1299
				return $suppress_errors ? false : new \WP_Error( 'user_id_mismatch', sprintf( 'Requesting user_id %d does not match token user_id %d', $user_id, $user_token_chunks[2] ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_id_mismatch'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1300
			}
1301
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
1302
		} else {
1303
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
1304
			if ( $stored_blog_token ) {
1305
				$possible_normal_tokens[] = $stored_blog_token;
1306
			}
1307
1308
			$defined_tokens = Constants::is_defined( 'JETPACK_BLOG_TOKEN' )
1309
				? explode( ',', Constants::get_constant( 'JETPACK_BLOG_TOKEN' ) )
1310
				: array();
1311
1312
			foreach ( $defined_tokens as $defined_token ) {
1313
				if ( ';' === $defined_token[0] ) {
1314
					$possible_special_tokens[] = $defined_token;
1315
				} else {
1316
					$possible_normal_tokens[] = $defined_token;
1317
				}
1318
			}
1319
		}
1320
1321
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1322
			$possible_tokens = $possible_normal_tokens;
1323
		} else {
1324
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
1325
		}
1326
1327
		if ( ! $possible_tokens ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $possible_tokens of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1328
			return $suppress_errors ? false : new \WP_Error( 'no_possible_tokens' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_possible_tokens'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1329
		}
1330
1331
		$valid_token = false;
1332
1333
		if ( false === $token_key ) {
1334
			// Use first token.
1335
			$valid_token = $possible_tokens[0];
1336
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1337
			// Use first normal token.
1338
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
1339
		} else {
1340
			// Use the token matching $token_key or false if none.
1341
			// Ensure we check the full key.
1342
			$token_check = rtrim( $token_key, '.' ) . '.';
1343
1344
			foreach ( $possible_tokens as $possible_token ) {
1345
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
1346
					$valid_token = $possible_token;
1347
					break;
1348
				}
1349
			}
1350
		}
1351
1352
		if ( ! $valid_token ) {
1353
			return $suppress_errors ? false : new \WP_Error( 'no_valid_token' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_valid_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1354
		}
1355
1356
		return (object) array(
1357
			'secret'           => $valid_token,
1358
			'external_user_id' => (int) $user_id,
1359
		);
1360
	}
1361
}
1362