Completed
Push — branch-7.8 ( 3deae6...2d21b7 )
by Jeremy
08:25
created

Manager::verify_secrets()   C

Complexity

Conditions 14
Paths 12

Size

Total Lines 132

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
nc 12
nop 3
dl 0
loc 132
rs 5.0133
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 automattic/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 {
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
	 * A copy of the raw POST data for signature verification purposes.
34
	 *
35
	 * @var String
36
	 */
37
	protected $raw_post_data;
38
39
	/**
40
	 * Verification data needs to be stored to properly verify everything.
41
	 *
42
	 * @var Object
43
	 */
44
	private $xmlrpc_verification = null;
45
46
	/**
47
	 * Initializes required listeners. This is done separately from the constructors
48
	 * because some objects sometimes need to instantiate separate objects of this class.
49
	 *
50
	 * @todo Implement a proper nonce verification.
51
	 */
52
	public function init() {
53
		$this->setup_xmlrpc_handlers(
54
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
55
			$this->is_active(),
56
			$this->verify_xml_rpc_signature()
0 ignored issues
show
Bug introduced by
It seems like $this->verify_xml_rpc_signature() targeting Automattic\Jetpack\Conne...ify_xml_rpc_signature() can also be of type array; however, Automattic\Jetpack\Conne...setup_xmlrpc_handlers() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
57
		);
58
59
		if ( $this->is_active() ) {
60
			add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
61
		} else {
62
			add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
63
		}
64
65
		add_action( 'jetpack_clean_nonces', array( $this, 'clean_nonces' ) );
66
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
67
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
68
		}
69
	}
70
71
	/**
72
	 * Sets up the XMLRPC request handlers.
73
	 *
74
	 * @param Array                  $request_params incoming request parameters.
75
	 * @param Boolean                $is_active whether the connection is currently active.
76
	 * @param Boolean                $is_signed whether the signature check has been successful.
77
	 * @param \Jetpack_XMLRPC_Server $xmlrpc_server (optional) an instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|\Jetpack_XMLRPC_Server?

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...
78
	 */
79
	public function setup_xmlrpc_handlers(
80
		$request_params,
81
		$is_active,
82
		$is_signed,
83
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
84
	) {
85
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
86
87
		if (
88
			! isset( $request_params['for'] )
89
			|| 'jetpack' !== $request_params['for']
90
		) {
91
			return false;
92
		}
93
94
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
95
		if (
96
			isset( $request_params['jetpack'] )
97
			&& 'comms' === $request_params['jetpack']
98
		) {
99
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
100
				// Use the real constant here for WordPress' sake.
101
				define( 'XMLRPC_REQUEST', true );
102
			}
103
104
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
105
106
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
107
		}
108
109
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
110
			return false;
111
		}
112
		// Display errors can cause the XML to be not well formed.
113
		@ini_set( 'display_errors', false ); // phpcs:ignore
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...
114
115
		if ( $xmlrpc_server ) {
116
			$this->xmlrpc_server = $xmlrpc_server;
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...
117
		} else {
118
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
119
		}
120
121
		$this->require_jetpack_authentication();
122
123
		if ( $is_active ) {
124
			// Hack to preserve $HTTP_RAW_POST_DATA.
125
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
126
127
			if ( $is_signed ) {
128
				// The actual API methods.
129
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
130
			} else {
131
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
132
				// active Jetpack connection, so that additional users can link their account.
133
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
134
			}
135
		} else {
136
			// The bootstrap API methods.
137
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
138
139
			if ( $is_signed ) {
140
				// The jetpack Provision method is available for blog-token-signed requests.
141
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
142
			} else {
143
				new XMLRPC_Connector( $this );
144
			}
145
		}
146
147
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
148
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
149
		return true;
150
	}
151
152
	/**
153
	 * Initializes the REST API connector on the init hook.
154
	 */
155
	public function initialize_rest_api_registration_connector() {
156
		new REST_Connector( $this );
157
	}
158
159
	/**
160
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
161
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
162
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
163
	 * which is accessible via a different URI. Most of the below is copied directly
164
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
165
	 *
166
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
167
	 */
168
	public function alternate_xmlrpc() {
169
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
170
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
171
		global $HTTP_RAW_POST_DATA;
172
173
		// Some browser-embedded clients send cookies. We don't want them.
174
		$_COOKIE = array();
175
176
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
177
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
178
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
179
		}
180
181
		// phpcs:enable
182
183
		include_once ABSPATH . 'wp-admin/includes/admin.php';
184
		include_once ABSPATH . WPINC . '/class-IXR.php';
185
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
186
187
		/**
188
		 * Filters the class used for handling XML-RPC requests.
189
		 *
190
		 * @since 3.1.0
191
		 *
192
		 * @param string $class The name of the XML-RPC server class.
193
		 */
194
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
195
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
196
197
		// Fire off the request.
198
		nocache_headers();
199
		$wp_xmlrpc_server->serve_request();
200
201
		exit;
202
	}
203
204
	/**
205
	 * Removes all XML-RPC methods that are not `jetpack.*`.
206
	 * Only used in our alternate XML-RPC endpoint, where we want to
207
	 * ensure that Core and other plugins' methods are not exposed.
208
	 *
209
	 * @param array $methods a list of registered WordPress XMLRPC methods.
210
	 * @return array filtered $methods
211
	 */
212
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
213
		$jetpack_methods = array();
214
215
		foreach ( $methods as $method => $callback ) {
216
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
217
				$jetpack_methods[ $method ] = $callback;
218
			}
219
		}
220
221
		return $jetpack_methods;
222
	}
223
224
	/**
225
	 * Removes all other authentication methods not to allow other
226
	 * methods to validate unauthenticated requests.
227
	 */
228
	public function require_jetpack_authentication() {
229
		// Don't let anyone authenticate.
230
		$_COOKIE = array();
231
		remove_all_filters( 'authenticate' );
232
		remove_all_actions( 'wp_login_failed' );
233
234
		if ( $this->is_active() ) {
235
			// Allow Jetpack authentication.
236
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
237
		}
238
	}
239
240
	/**
241
	 * Authenticates XML-RPC and other requests from the Jetpack Server
242
	 *
243
	 * @param WP_User|Mixed $user user object if authenticated.
244
	 * @param String        $username username.
245
	 * @param String        $password password string.
246
	 * @return WP_User|Mixed authenticated user or error.
247
	 */
248
	public function authenticate_jetpack( $user, $username, $password ) {
249
		if ( is_a( $user, '\\WP_User' ) ) {
250
			return $user;
251
		}
252
253
		$token_details = $this->verify_xml_rpc_signature();
254
255
		if ( ! $token_details ) {
256
			return $user;
257
		}
258
259
		if ( 'user' !== $token_details['type'] ) {
260
			return $user;
261
		}
262
263
		if ( ! $token_details['user_id'] ) {
264
			return $user;
265
		}
266
267
		nocache_headers();
268
269
		return new \WP_User( $token_details['user_id'] );
270
	}
271
272
	/**
273
	 * Verifies the signature of the current request.
274
	 *
275
	 * @return false|array
276
	 */
277
	public function verify_xml_rpc_signature() {
278
		if ( is_null( $this->xmlrpc_verification ) ) {
279
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
280
281
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
282
				/**
283
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
284
				 *
285
				 * Error codes:
286
				 * - malformed_token
287
				 * - malformed_user_id
288
				 * - unknown_token
289
				 * - could_not_sign
290
				 * - invalid_nonce
291
				 * - signature_mismatch
292
				 *
293
				 * @since 7.5.0
294
				 *
295
				 * @param WP_Error $signature_verification_error The verification error
296
				 */
297
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
298
			}
299
		}
300
301
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
302
	}
303
304
	/**
305
	 * Verifies the signature of the current request.
306
	 *
307
	 * This function has side effects and should not be used. Instead,
308
	 * use the memoized version `->verify_xml_rpc_signature()`.
309
	 *
310
	 * @internal
311
	 * @todo Refactor to use proper nonce verification.
312
	 */
313
	private function internal_verify_xml_rpc_signature() {
314
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
315
		// It's not for us.
316
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
317
			return false;
318
		}
319
320
		$signature_details = array(
321
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
322
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
323
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
324
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
325
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
326
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
327
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
328
		);
329
330
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
331
		@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...
332
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
333
334
		if (
335
			empty( $token_key )
336
		||
337
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
338
		) {
339
			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...
340
		}
341
342
		if ( '0' === $user_id ) {
343
			$token_type = 'blog';
344
			$user_id    = 0;
345
		} else {
346
			$token_type = 'user';
347
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
348
				return new \WP_Error(
349
					'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...
350
					'Malformed user_id in request',
351
					compact( 'signature_details' )
352
				);
353
			}
354
			$user_id = (int) $user_id;
355
356
			$user = new \WP_User( $user_id );
357
			if ( ! $user || ! $user->exists() ) {
358
				return new \WP_Error(
359
					'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...
360
					sprintf( 'User %d does not exist', $user_id ),
361
					compact( 'signature_details' )
362
				);
363
			}
364
		}
365
366
		$token = $this->get_access_token( $user_id, $token_key, false );
367
		if ( is_wp_error( $token ) ) {
368
			$token->add_data( compact( 'signature_details' ) );
369
			return $token;
370
		} elseif ( ! $token ) {
371
			return new \WP_Error(
372
				'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...
373
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
374
				compact( 'signature_details' )
375
			);
376
		}
377
378
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
379
		// phpcs:disable WordPress.Security.NonceVerification.Missing
380
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
381
			$post_data   = $_POST;
382
			$file_hashes = array();
383
			foreach ( $post_data as $post_data_key => $post_data_value ) {
384
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
385
					continue;
386
				}
387
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
388
				$file_hashes[ $post_data_key ] = $post_data_value;
389
			}
390
391
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
392
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
393
				$post_data[ $post_data_key ] = $post_data_value;
394
			}
395
396
			ksort( $post_data );
397
398
			$body = http_build_query( stripslashes_deep( $post_data ) );
399
		} elseif ( is_null( $this->raw_post_data ) ) {
400
			$body = file_get_contents( 'php://input' );
401
		} else {
402
			$body = null;
403
		}
404
		// phpcs:enable
405
406
		$signature = $jetpack_signature->sign_current_request(
407
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
408
		);
409
410
		$signature_details['url'] = $jetpack_signature->current_request_url;
411
412
		if ( ! $signature ) {
413
			return new \WP_Error(
414
				'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...
415
				'Unknown signature error',
416
				compact( 'signature_details' )
417
			);
418
		} elseif ( is_wp_error( $signature ) ) {
419
			return $signature;
420
		}
421
422
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
423
		$timestamp = (int) $_GET['timestamp'];
424
		$nonce     = stripslashes( (string) $_GET['nonce'] );
425
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
426
427
		// Use up the nonce regardless of whether the signature matches.
428
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
429
			return new \WP_Error(
430
				'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...
431
				'Could not add nonce',
432
				compact( 'signature_details' )
433
			);
434
		}
435
436
		// Be careful about what you do with this debugging data.
437
		// If a malicious requester has access to the expected signature,
438
		// bad things might be possible.
439
		$signature_details['expected'] = $signature;
440
441
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
442
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
443
			return new \WP_Error(
444
				'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...
445
				'Signature mismatch',
446
				compact( 'signature_details' )
447
			);
448
		}
449
450
		/**
451
		 * Action for additional token checking.
452
		 *
453
		 * @since 7.7.0
454
		 *
455
		 * @param Array $post_data request data.
456
		 * @param Array $token_data token data.
457
		 */
458
		return apply_filters(
459
			'jetpack_signature_check_token',
460
			array(
461
				'type'      => $token_type,
462
				'token_key' => $token_key,
463
				'user_id'   => $token->external_user_id,
464
			),
465
			$token,
466
			$this->raw_post_data
467
		);
468
	}
469
470
	/**
471
	 * Returns true if the current site is connected to WordPress.com.
472
	 *
473
	 * @return Boolean is the site connected?
474
	 */
475
	public function is_active() {
476
		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...
477
	}
478
479
	/**
480
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
481
	 *
482
	 * @access public
483
	 *
484
	 * @return bool
485
	 */
486
	public function is_registered() {
487
		$blog_id   = \Jetpack_Options::get_option( 'id' );
488
		$has_token = $this->is_active();
489
		return $blog_id && $has_token;
490
	}
491
492
	/**
493
	 * Checks to see if the connection owner of the site is missing.
494
	 *
495
	 * @return bool
496
	 */
497
	public function is_missing_connection_owner() {
498
		$connection_owner = $this->get_connection_owner_id();
499
		if ( ! get_user_by( 'id', $connection_owner ) ) {
500
			return true;
501
		}
502
503
		return false;
504
	}
505
506
	/**
507
	 * Returns true if the user with the specified identifier is connected to
508
	 * WordPress.com.
509
	 *
510
	 * @param Integer|Boolean $user_id the user identifier.
511
	 * @return Boolean is the user connected?
512
	 */
513
	public function is_user_connected( $user_id = false ) {
514
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
515
		if ( ! $user_id ) {
516
			return false;
517
		}
518
519
		return (bool) $this->get_access_token( $user_id );
520
	}
521
522
	/**
523
	 * Returns the local user ID of the connection owner.
524
	 *
525
	 * @return string|int Returns the ID of the connection owner or False if no connection owner found.
526
	 */
527 View Code Duplication
	public function get_connection_owner_id() {
528
		$user_token       = $this->get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
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...
529
		$connection_owner = false;
530
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
531
			$connection_owner = $user_token->external_user_id;
532
		}
533
534
		return $connection_owner;
535
	}
536
537
	/**
538
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
539
	 * Able to select by specific capability.
540
	 *
541
	 * @param string $capability The capability of the user.
542
	 * @return array Array of WP_User objects if found.
543
	 */
544
	public function get_connected_users( $capability = 'any' ) {
545
		$connected_users    = array();
546
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
547
548
		if ( ! empty( $connected_user_ids ) ) {
549
			foreach ( $connected_user_ids as $id ) {
550
				// Check for capability.
551
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
552
					continue;
553
				}
554
555
				$connected_users[] = get_userdata( $id );
556
			}
557
		}
558
559
		return $connected_users;
560
	}
561
562
	/**
563
	 * Get the wpcom user data of the current|specified connected user.
564
	 *
565
	 * @todo Refactor to properly load the XMLRPC client independently.
566
	 *
567
	 * @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...
568
	 * @return Object the user object.
569
	 */
570 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
571
		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...
572
			$user_id = get_current_user_id();
573
		}
574
575
		$transient_key    = "jetpack_connected_user_data_$user_id";
576
		$cached_user_data = get_transient( $transient_key );
577
578
		if ( $cached_user_data ) {
579
			return $cached_user_data;
580
		}
581
582
		$xml = new \Jetpack_IXR_Client(
583
			array(
584
				'user_id' => $user_id,
585
			)
586
		);
587
		$xml->query( 'wpcom.getUser' );
588
		if ( ! $xml->isError() ) {
589
			$user_data = $xml->getResponse();
590
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
591
			return $user_data;
592
		}
593
594
		return false;
595
	}
596
597
	/**
598
	 * Returns a user object of the connection owner.
599
	 *
600
	 * @return object|false False if no connection owner found.
601
	 */
602 View Code Duplication
	public function get_connection_owner() {
603
		$user_token = $this->get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
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...
604
605
		$connection_owner = false;
606
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
607
			$connection_owner = get_userdata( $user_token->external_user_id );
608
		}
609
610
		return $connection_owner;
611
	}
612
613
	/**
614
	 * Returns true if the provided user is the Jetpack connection owner.
615
	 * If user ID is not specified, the current user will be used.
616
	 *
617
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
618
	 * @return Boolean True the user the connection owner, false otherwise.
619
	 */
620 View Code Duplication
	public function is_connection_owner( $user_id = false ) {
621
		if ( ! $user_id ) {
622
			$user_id = get_current_user_id();
623
		}
624
625
		$user_token = $this->get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
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...
626
627
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
628
	}
629
630
	/**
631
	 * Unlinks the current user from the linked WordPress.com user.
632
	 *
633
	 * @access public
634
	 * @static
635
	 *
636
	 * @todo Refactor to properly load the XMLRPC client independently.
637
	 *
638
	 * @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...
639
	 * @return Boolean Whether the disconnection of the user was successful.
640
	 */
641
	public static function disconnect_user( $user_id = null ) {
642
		$tokens = \Jetpack_Options::get_option( 'user_tokens' );
643
		if ( ! $tokens ) {
644
			return false;
645
		}
646
647
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
648
649
		if ( \Jetpack_Options::get_option( 'master_user' ) === $user_id ) {
650
			return false;
651
		}
652
653
		if ( ! isset( $tokens[ $user_id ] ) ) {
654
			return false;
655
		}
656
657
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
658
		$xml->query( 'jetpack.unlink_user', $user_id );
659
660
		unset( $tokens[ $user_id ] );
661
662
		\Jetpack_Options::update_option( 'user_tokens', $tokens );
663
664
		/**
665
		 * Fires after the current user has been unlinked from WordPress.com.
666
		 *
667
		 * @since 4.1.0
668
		 *
669
		 * @param int $user_id The current user's ID.
670
		 */
671
		do_action( 'jetpack_unlinked_user', $user_id );
672
673
		return true;
674
	}
675
676
	/**
677
	 * Returns the requested Jetpack API URL.
678
	 *
679
	 * @param String $relative_url the relative API path.
680
	 * @return String API URL.
681
	 */
682
	public function api_url( $relative_url ) {
683
		$api_base = Constants::get_constant( 'JETPACK__API_BASE' );
684
		$version  = Constants::get_constant( 'JETPACK__API_VERSION' );
685
686
		$api_base = $api_base ? $api_base : 'https://jetpack.wordpress.com/jetpack.';
687
		$version  = $version ? '/' . $version . '/' : '/1/';
688
689
		return rtrim( $api_base . $relative_url, '/\\' ) . $version;
690
	}
691
692
	/**
693
	 * Attempts Jetpack registration which sets up the site for connection. Should
694
	 * remain public because the call to action comes from the current site, not from
695
	 * WordPress.com.
696
	 *
697
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
698
	 * @return Integer zero on success, or a bitmask on failure.
699
	 */
700
	public function register( $api_endpoint = 'register' ) {
701
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
702
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
703
704
		if (
705
			empty( $secrets['secret_1'] ) ||
706
			empty( $secrets['secret_2'] ) ||
707
			empty( $secrets['exp'] )
708
		) {
709
			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...
710
		}
711
712
		// Better to try (and fail) to set a higher timeout than this system
713
		// supports than to have register fail for more users than it should.
714
		$timeout = $this->set_min_time_limit( 60 ) / 2;
715
716
		$gmt_offset = get_option( 'gmt_offset' );
717
		if ( ! $gmt_offset ) {
718
			$gmt_offset = 0;
719
		}
720
721
		$stats_options = get_option( 'stats_options' );
722
		$stats_id      = isset( $stats_options['blog_id'] )
723
			? $stats_options['blog_id']
724
			: null;
725
726
		/**
727
		 * Filters the request body for additional property addition.
728
		 *
729
		 * @since 7.7.0
730
		 *
731
		 * @param Array $post_data request data.
732
		 * @param Array $token_data token data.
733
		 */
734
		$body = apply_filters(
735
			'jetpack_register_request_body',
736
			array(
737
				'siteurl'         => site_url(),
738
				'home'            => home_url(),
739
				'gmt_offset'      => $gmt_offset,
740
				'timezone_string' => (string) get_option( 'timezone_string' ),
741
				'site_name'       => (string) get_option( 'blogname' ),
742
				'secret_1'        => $secrets['secret_1'],
743
				'secret_2'        => $secrets['secret_2'],
744
				'site_lang'       => get_locale(),
745
				'timeout'         => $timeout,
746
				'stats_id'        => $stats_id,
747
				'state'           => get_current_user_id(),
748
				'site_created'    => $this->get_assumed_site_creation_date(),
749
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
750
			)
751
		);
752
753
		$args = array(
754
			'method'  => 'POST',
755
			'body'    => $body,
756
			'headers' => array(
757
				'Accept' => 'application/json',
758
			),
759
			'timeout' => $timeout,
760
		);
761
762
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
763
764
		// TODO: fix URLs for bad hosts.
765
		$response = Client::_wp_remote_request(
766
			$this->api_url( $api_endpoint ),
767
			$args,
768
			true
769
		);
770
771
		// Make sure the response is valid and does not contain any Jetpack errors.
772
		$registration_details = $this->validate_remote_register_response( $response );
773
774
		if ( is_wp_error( $registration_details ) ) {
775
			return $registration_details;
776
		} elseif ( ! $registration_details ) {
777
			return new \WP_Error(
778
				'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...
779
				'Unknown error registering your Jetpack site.',
780
				wp_remote_retrieve_response_code( $response )
781
			);
782
		}
783
784
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
785
			return new \WP_Error(
786
				'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...
787
				'Unable to validate registration of your Jetpack site.',
788
				wp_remote_retrieve_response_code( $response )
789
			);
790
		}
791
792
		if ( isset( $registration_details->jetpack_public ) ) {
793
			$jetpack_public = (int) $registration_details->jetpack_public;
794
		} else {
795
			$jetpack_public = false;
796
		}
797
798
		\Jetpack_Options::update_options(
799
			array(
800
				'id'         => (int) $registration_details->jetpack_id,
801
				'blog_token' => (string) $registration_details->jetpack_secret,
802
				'public'     => $jetpack_public,
803
			)
804
		);
805
806
		/**
807
		 * Fires when a site is registered on WordPress.com.
808
		 *
809
		 * @since 3.7.0
810
		 *
811
		 * @param int $json->jetpack_id Jetpack Blog ID.
812
		 * @param string $json->jetpack_secret Jetpack Blog Token.
813
		 * @param int|bool $jetpack_public Is the site public.
814
		 */
815
		do_action(
816
			'jetpack_site_registered',
817
			$registration_details->jetpack_id,
818
			$registration_details->jetpack_secret,
819
			$jetpack_public
820
		);
821
822
		if ( isset( $registration_details->token ) ) {
823
			/**
824
			 * Fires when a user token is sent along with the registration data.
825
			 *
826
			 * @since 7.6.0
827
			 *
828
			 * @param object $token the administrator token for the newly registered site.
829
			 */
830
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
831
		}
832
833
		return true;
834
	}
835
836
	/**
837
	 * Takes the response from the Jetpack register new site endpoint and
838
	 * verifies it worked properly.
839
	 *
840
	 * @since 2.6
841
	 *
842
	 * @param Mixed $response the response object, or the error object.
843
	 * @return string|WP_Error A JSON object on success or Jetpack_Error on failures
844
	 **/
845
	protected function validate_remote_register_response( $response ) {
846
		if ( is_wp_error( $response ) ) {
847
			return new \WP_Error(
848
				'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...
849
				$response->get_error_message()
850
			);
851
		}
852
853
		$code   = wp_remote_retrieve_response_code( $response );
854
		$entity = wp_remote_retrieve_body( $response );
855
856
		if ( $entity ) {
857
			$registration_response = json_decode( $entity );
858
		} else {
859
			$registration_response = false;
860
		}
861
862
		$code_type = intval( $code / 100 );
863
		if ( 5 === $code_type ) {
864
			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...
865
		} elseif ( 408 === $code ) {
866
			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...
867
		} elseif ( ! empty( $registration_response->error ) ) {
868
			if (
869
				'xml_rpc-32700' === $registration_response->error
870
				&& ! function_exists( 'xml_parser_create' )
871
			) {
872
				$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' );
873
			} else {
874
				$error_description = isset( $registration_response->error_description )
875
					? (string) $registration_response->error_description
876
					: '';
877
			}
878
879
			return new \WP_Error(
880
				(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...
881
				$error_description,
882
				$code
883
			);
884
		} elseif ( 200 !== $code ) {
885
			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...
886
		}
887
888
		// Jetpack ID error block.
889
		if ( empty( $registration_response->jetpack_id ) ) {
890
			return new \WP_Error(
891
				'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...
892
				/* translators: %s is an error message string */
893
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
894
				$entity
895
			);
896
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
897
			return new \WP_Error(
898
				'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...
899
				/* translators: %s is an error message string */
900
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
901
				$entity
902
			);
903 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
904
			return new \WP_Error(
905
				'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...
906
				/* translators: %s is an error message string */
907
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
908
				$entity
909
			);
910
		}
911
912
		return $registration_response;
913
	}
914
915
	/**
916
	 * Adds a used nonce to a list of known nonces.
917
	 *
918
	 * @param int    $timestamp the current request timestamp.
919
	 * @param string $nonce the nonce value.
920
	 * @return bool whether the nonce is unique or not.
921
	 */
922
	public function add_nonce( $timestamp, $nonce ) {
923
		global $wpdb;
924
		static $nonces_used_this_request = array();
925
926
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
927
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
928
		}
929
930
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
931
		$timestamp = (int) $timestamp;
932
		$nonce     = esc_sql( $nonce );
933
934
		// Raw query so we can avoid races: add_option will also update.
935
		$show_errors = $wpdb->show_errors( false );
936
937
		$old_nonce = $wpdb->get_row(
938
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
939
		);
940
941
		if ( is_null( $old_nonce ) ) {
942
			$return = $wpdb->query(
943
				$wpdb->prepare(
944
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
945
					"jetpack_nonce_{$timestamp}_{$nonce}",
946
					time(),
947
					'no'
948
				)
949
			);
950
		} else {
951
			$return = false;
952
		}
953
954
		$wpdb->show_errors( $show_errors );
955
956
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
957
958
		return $return;
959
	}
960
961
	/**
962
	 * Cleans nonces that were saved when calling ::add_nonce.
963
	 *
964
	 * @todo Properly prepare the query before executing it.
965
	 *
966
	 * @param bool $all whether to clean even non-expired nonces.
967
	 */
968
	public function clean_nonces( $all = false ) {
969
		global $wpdb;
970
971
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
972
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
973
974
		if ( true !== $all ) {
975
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
976
			$sql_args[] = time() - 3600;
977
		}
978
979
		$sql .= ' ORDER BY `option_id` LIMIT 100';
980
981
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
982
983
		for ( $i = 0; $i < 1000; $i++ ) {
984
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
985
				break;
986
			}
987
		}
988
	}
989
990
	/**
991
	 * Builds the timeout limit for queries talking with the wpcom servers.
992
	 *
993
	 * Based on local php max_execution_time in php.ini
994
	 *
995
	 * @since 5.4
996
	 * @return int
997
	 **/
998
	public function get_max_execution_time() {
999
		$timeout = (int) ini_get( 'max_execution_time' );
1000
1001
		// Ensure exec time set in php.ini.
1002
		if ( ! $timeout ) {
1003
			$timeout = 30;
1004
		}
1005
		return $timeout;
1006
	}
1007
1008
	/**
1009
	 * Sets a minimum request timeout, and returns the current timeout
1010
	 *
1011
	 * @since 5.4
1012
	 * @param Integer $min_timeout the minimum timeout value.
1013
	 **/
1014 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1015
		$timeout = $this->get_max_execution_time();
1016
		if ( $timeout < $min_timeout ) {
1017
			$timeout = $min_timeout;
1018
			set_time_limit( $timeout );
1019
		}
1020
		return $timeout;
1021
	}
1022
1023
	/**
1024
	 * Get our assumed site creation date.
1025
	 * Calculated based on the earlier date of either:
1026
	 * - Earliest admin user registration date.
1027
	 * - Earliest date of post of any post type.
1028
	 *
1029
	 * @since 7.2.0
1030
	 *
1031
	 * @return string Assumed site creation date and time.
1032
	 */
1033
	public function get_assumed_site_creation_date() {
1034
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1035
		if ( ! empty( $cached_date ) ) {
1036
			return $cached_date;
1037
		}
1038
1039
		$earliest_registered_users  = get_users(
1040
			array(
1041
				'role'    => 'administrator',
1042
				'orderby' => 'user_registered',
1043
				'order'   => 'ASC',
1044
				'fields'  => array( 'user_registered' ),
1045
				'number'  => 1,
1046
			)
1047
		);
1048
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1049
1050
		$earliest_posts = get_posts(
1051
			array(
1052
				'posts_per_page' => 1,
1053
				'post_type'      => 'any',
1054
				'post_status'    => 'any',
1055
				'orderby'        => 'date',
1056
				'order'          => 'ASC',
1057
			)
1058
		);
1059
1060
		// If there are no posts at all, we'll count only on user registration date.
1061
		if ( $earliest_posts ) {
1062
			$earliest_post_date = $earliest_posts[0]->post_date;
1063
		} else {
1064
			$earliest_post_date = PHP_INT_MAX;
1065
		}
1066
1067
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1068
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1069
1070
		return $assumed_date;
1071
	}
1072
1073
	/**
1074
	 * Adds the activation source string as a parameter to passed arguments.
1075
	 *
1076
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1077
	 *
1078
	 * @param Array $args arguments that need to have the source added.
1079
	 * @return Array $amended arguments.
1080
	 */
1081 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1082
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1083
1084
		if ( $activation_source_name ) {
1085
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1086
			$args['_as'] = urlencode( $activation_source_name );
1087
		}
1088
1089
		if ( $activation_source_keyword ) {
1090
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1091
			$args['_ak'] = urlencode( $activation_source_keyword );
1092
		}
1093
1094
		return $args;
1095
	}
1096
1097
	/**
1098
	 * Returns the callable that would be used to generate secrets.
1099
	 *
1100
	 * @return Callable a function that returns a secure string to be used as a secret.
1101
	 */
1102
	protected function get_secret_callable() {
1103
		if ( ! isset( $this->secret_callable ) ) {
1104
			/**
1105
			 * Allows modification of the callable that is used to generate connection secrets.
1106
			 *
1107
			 * @param Callable a function or method that returns a secret string.
1108
			 */
1109
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', 'wp_generate_password' );
1110
		}
1111
1112
		return $this->secret_callable;
1113
	}
1114
1115
	/**
1116
	 * Generates two secret tokens and the end of life timestamp for them.
1117
	 *
1118
	 * @param String  $action  The action name.
1119
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be false|integer?

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...
1120
	 * @param Integer $exp     Expiration time in seconds.
1121
	 */
1122
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1123
		$callable = $this->get_secret_callable();
1124
1125
		$secrets = \Jetpack_Options::get_raw_option(
1126
			self::SECRETS_OPTION_NAME,
1127
			array()
1128
		);
1129
1130
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1131
1132
		if (
1133
			isset( $secrets[ $secret_name ] ) &&
1134
			$secrets[ $secret_name ]['exp'] > time()
1135
		) {
1136
			return $secrets[ $secret_name ];
1137
		}
1138
1139
		$secret_value = array(
1140
			'secret_1' => call_user_func( $callable ),
1141
			'secret_2' => call_user_func( $callable ),
1142
			'exp'      => time() + $exp,
1143
		);
1144
1145
		$secrets[ $secret_name ] = $secret_value;
1146
1147
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1148
		return $secrets[ $secret_name ];
1149
	}
1150
1151
	/**
1152
	 * Returns two secret tokens and the end of life timestamp for them.
1153
	 *
1154
	 * @param String  $action  The action name.
1155
	 * @param Integer $user_id The user identifier.
1156
	 * @return string|array an array of secrets or an error string.
1157
	 */
1158
	public function get_secrets( $action, $user_id ) {
1159
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1160
		$secrets     = \Jetpack_Options::get_raw_option(
1161
			self::SECRETS_OPTION_NAME,
1162
			array()
1163
		);
1164
1165
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1166
			return self::SECRETS_MISSING;
1167
		}
1168
1169
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1170
			$this->delete_secrets( $action, $user_id );
1171
			return self::SECRETS_EXPIRED;
1172
		}
1173
1174
		return $secrets[ $secret_name ];
1175
	}
1176
1177
	/**
1178
	 * Deletes secret tokens in case they, for example, have expired.
1179
	 *
1180
	 * @param String  $action  The action name.
1181
	 * @param Integer $user_id The user identifier.
1182
	 */
1183
	public function delete_secrets( $action, $user_id ) {
1184
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1185
		$secrets     = \Jetpack_Options::get_raw_option(
1186
			self::SECRETS_OPTION_NAME,
1187
			array()
1188
		);
1189
		if ( isset( $secrets[ $secret_name ] ) ) {
1190
			unset( $secrets[ $secret_name ] );
1191
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1192
		}
1193
	}
1194
1195
	/**
1196
	 * Responds to a WordPress.com call to register the current site.
1197
	 * Should be changed to protected.
1198
	 *
1199
	 * @param array $registration_data Array of [ secret_1, user_id ].
1200
	 */
1201
	public function handle_registration( array $registration_data ) {
1202
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1203
		if ( empty( $registration_user_id ) ) {
1204
			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...
1205
		}
1206
1207
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1208
	}
1209
1210
	/**
1211
	 * Verify a Previously Generated Secret.
1212
	 *
1213
	 * @param string $action   The type of secret to verify.
1214
	 * @param string $secret_1 The secret string to compare to what is stored.
1215
	 * @param int    $user_id  The user ID of the owner of the secret.
1216
	 */
1217
	protected function verify_secrets( $action, $secret_1, $user_id ) {
1218
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1219
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1220
			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...
1221
		}
1222
1223
		$user = get_user_by( 'id', $user_id );
1224
1225
		/**
1226
		 * We've begun verifying the previously generated secret.
1227
		 *
1228
		 * @since 7.5.0
1229
		 *
1230
		 * @param string   $action The type of secret to verify.
1231
		 * @param \WP_User $user The user object.
1232
		 */
1233
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1234
1235
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1236
			/**
1237
			 * Verifying of the previously generated secret has failed.
1238
			 *
1239
			 * @since 7.5.0
1240
			 *
1241
			 * @param string    $action  The type of secret to verify.
1242
			 * @param \WP_User  $user The user object.
1243
			 * @param \WP_Error $error The error object.
1244
			 */
1245
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1246
1247
			return $error;
1248
		};
1249
1250
		$stored_secrets = $this->get_secrets( $action, $user_id );
1251
		$this->delete_secrets( $action, $user_id );
1252
1253
		if ( empty( $secret_1 ) ) {
1254
			return $return_error(
1255
				new \WP_Error(
1256
					'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...
1257
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1258
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1259
					400
1260
				)
1261
			);
1262
		} elseif ( ! is_string( $secret_1 ) ) {
1263
			return $return_error(
1264
				new \WP_Error(
1265
					'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...
1266
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1267
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1268
					400
1269
				)
1270
			);
1271
		} elseif ( empty( $user_id ) ) {
1272
			// $user_id is passed around during registration as "state".
1273
			return $return_error(
1274
				new \WP_Error(
1275
					'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...
1276
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1277
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1278
					400
1279
				)
1280
			);
1281
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1282
			return $return_error(
1283
				new \WP_Error(
1284
					'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...
1285
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1286
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1287
					400
1288
				)
1289
			);
1290
		}
1291
1292
		if ( self::SECRETS_MISSING === $stored_secrets ) {
1293
			return $return_error(
1294
				new \WP_Error(
1295
					'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...
1296
					__( 'Verification secrets not found', 'jetpack' ),
1297
					400
1298
				)
1299
			);
1300
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1301
			return $return_error(
1302
				new \WP_Error(
1303
					'verify_secrets_expired',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

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...
1304
					__( 'Verification took too long', 'jetpack' ),
1305
					400
1306
				)
1307
			);
1308
		} elseif ( ! $stored_secrets ) {
1309
			return $return_error(
1310
				new \WP_Error(
1311
					'verify_secrets_empty',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_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...
1312
					__( 'Verification secrets are empty', 'jetpack' ),
1313
					400
1314
				)
1315
			);
1316
		} elseif ( is_wp_error( $stored_secrets ) ) {
1317
			$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...
1318
			return $return_error( $stored_secrets );
1319
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1320
			return $return_error(
1321
				new \WP_Error(
1322
					'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...
1323
					__( 'Verification secrets are incomplete', 'jetpack' ),
1324
					400
1325
				)
1326
			);
1327
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1328
			return $return_error(
1329
				new \WP_Error(
1330
					'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...
1331
					__( 'Secret mismatch', 'jetpack' ),
1332
					400
1333
				)
1334
			);
1335
		}
1336
1337
		/**
1338
		 * We've succeeded at verifying the previously generated secret.
1339
		 *
1340
		 * @since 7.5.0
1341
		 *
1342
		 * @param string   $action The type of secret to verify.
1343
		 * @param \WP_User $user The user object.
1344
		 */
1345
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1346
1347
		return $stored_secrets['secret_2'];
1348
	}
1349
1350
	/**
1351
	 * Responds to a WordPress.com call to authorize the current user.
1352
	 * Should be changed to protected.
1353
	 */
1354
	public function handle_authorization() {
1355
1356
	}
1357
1358
	/**
1359
	 * Builds a URL to the Jetpack connection auth page.
1360
	 * This needs rethinking.
1361
	 *
1362
	 * @param bool        $raw If true, URL will not be escaped.
1363
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
1364
	 *                              If string, will be a custom redirect.
1365
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
1366
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0.
1367
	 *
1368
	 * @return string Connect URL
1369
	 */
1370
	public function build_connect_url( $raw, $redirect, $from, $register ) {
1371
		return array( $raw, $redirect, $from, $register );
1372
	}
1373
1374
	/**
1375
	 * Disconnects from the Jetpack servers.
1376
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1377
	 */
1378
	public function disconnect_site() {
1379
1380
	}
1381
1382
	/**
1383
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1384
	 *
1385
	 * @param string $text The string to hash.
1386
	 * @return string
1387
	 */
1388
	public function sha1_base64( $text ) {
1389
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1390
	}
1391
1392
	/**
1393
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1394
	 *
1395
	 * @param string $domain The domain to check.
1396
	 *
1397
	 * @return bool|WP_Error
1398
	 */
1399
	public function is_usable_domain( $domain ) {
1400
1401
		// If it's empty, just fail out.
1402
		if ( ! $domain ) {
1403
			return new \WP_Error(
1404
				'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...
1405
				/* translators: %1$s is a domain name. */
1406
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1407
			);
1408
		}
1409
1410
		/**
1411
		 * Skips the usuable domain check when connecting a site.
1412
		 *
1413
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1414
		 *
1415
		 * @since 4.1.0
1416
		 *
1417
		 * @param bool If the check should be skipped. Default false.
1418
		 */
1419
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1420
			return true;
1421
		}
1422
1423
		// None of the explicit localhosts.
1424
		$forbidden_domains = array(
1425
			'wordpress.com',
1426
			'localhost',
1427
			'localhost.localdomain',
1428
			'127.0.0.1',
1429
			'local.wordpress.test',         // VVV pattern.
1430
			'local.wordpress-trunk.test',   // VVV pattern.
1431
			'src.wordpress-develop.test',   // VVV pattern.
1432
			'build.wordpress-develop.test', // VVV pattern.
1433
		);
1434 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1435
			return new \WP_Error(
1436
				'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...
1437
				sprintf(
1438
					/* translators: %1$s is a domain name. */
1439
					__(
1440
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1441
						'jetpack'
1442
					),
1443
					$domain
1444
				)
1445
			);
1446
		}
1447
1448
		// No .test or .local domains.
1449 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1450
			return new \WP_Error(
1451
				'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...
1452
				sprintf(
1453
					/* translators: %1$s is a domain name. */
1454
					__(
1455
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1456
						'jetpack'
1457
					),
1458
					$domain
1459
				)
1460
			);
1461
		}
1462
1463
		// No WPCOM subdomains.
1464 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1465
			return new \WP_Error(
1466
				'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...
1467
				sprintf(
1468
					/* translators: %1$s is a domain name. */
1469
					__(
1470
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1471
						'jetpack'
1472
					),
1473
					$domain
1474
				)
1475
			);
1476
		}
1477
1478
		// If PHP was compiled without support for the Filter module (very edge case).
1479
		if ( ! function_exists( 'filter_var' ) ) {
1480
			// Just pass back true for now, and let wpcom sort it out.
1481
			return true;
1482
		}
1483
1484
		return true;
1485
	}
1486
1487
	/**
1488
	 * Gets the requested token.
1489
	 *
1490
	 * Tokens are one of two types:
1491
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
1492
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
1493
	 *    are not associated with a user account. They represent the site's connection with
1494
	 *    the Jetpack servers.
1495
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
1496
	 *
1497
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
1498
	 * token, and $private is a secret that should never be displayed anywhere or sent
1499
	 * over the network; it's used only for signing things.
1500
	 *
1501
	 * Blog Tokens can be "Normal" or "Special".
1502
	 * * Normal: The result of a normal connection flow. They look like
1503
	 *   "{$random_string_1}.{$random_string_2}"
1504
	 *   That is, $token_key and $private are both random strings.
1505
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
1506
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
1507
	 *   constant (rare).
1508
	 * * Special: A connection token for sites that have gone through an alternative
1509
	 *   connection flow. They look like:
1510
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
1511
	 *   That is, $private is a random string and $token_key has a special structure with
1512
	 *   lots of semicolons.
1513
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
1514
	 *   JETPACK_BLOG_TOKEN constant.
1515
	 *
1516
	 * In particular, note that Normal Blog Tokens never start with ";" and that
1517
	 * Special Blog Tokens always do.
1518
	 *
1519
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
1520
	 * order:
1521
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
1522
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
1523
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
1524
	 *
1525
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1526
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1527
	 * @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.
1528
	 *
1529
	 * @return object|false
1530
	 */
1531
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1532
		$possible_special_tokens = array();
1533
		$possible_normal_tokens  = array();
1534
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
1535
1536
		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...
1537
			if ( ! $user_tokens ) {
1538
				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...
1539
			}
1540
			if ( self::JETPACK_MASTER_USER === $user_id ) {
1541
				$user_id = \Jetpack_Options::get_option( 'master_user' );
1542
				if ( ! $user_id ) {
1543
					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...
1544
				}
1545
			}
1546
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
1547
				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...
1548
			}
1549
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
1550 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
1551
				return $suppress_errors ? false : new \WP_Error( 'token_malformed', sprintf( 'Token for user %d is malformed', $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...
1552
			}
1553 View Code Duplication
			if ( $user_token_chunks[2] !== (string) $user_id ) {
1554
				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...
1555
			}
1556
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
1557
		} else {
1558
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
1559
			if ( $stored_blog_token ) {
1560
				$possible_normal_tokens[] = $stored_blog_token;
1561
			}
1562
1563
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
1564
1565
			if ( $defined_tokens_string ) {
1566
				$defined_tokens = explode( ',', $defined_tokens_string );
1567
				foreach ( $defined_tokens as $defined_token ) {
1568
					if ( ';' === $defined_token[0] ) {
1569
						$possible_special_tokens[] = $defined_token;
1570
					} else {
1571
						$possible_normal_tokens[] = $defined_token;
1572
					}
1573
				}
1574
			}
1575
		}
1576
1577
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1578
			$possible_tokens = $possible_normal_tokens;
1579
		} else {
1580
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
1581
		}
1582
1583
		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...
1584
			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...
1585
		}
1586
1587
		$valid_token = false;
1588
1589
		if ( false === $token_key ) {
1590
			// Use first token.
1591
			$valid_token = $possible_tokens[0];
1592
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1593
			// Use first normal token.
1594
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
1595
		} else {
1596
			// Use the token matching $token_key or false if none.
1597
			// Ensure we check the full key.
1598
			$token_check = rtrim( $token_key, '.' ) . '.';
1599
1600
			foreach ( $possible_tokens as $possible_token ) {
1601
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
1602
					$valid_token = $possible_token;
1603
					break;
1604
				}
1605
			}
1606
		}
1607
1608
		if ( ! $valid_token ) {
1609
			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...
1610
		}
1611
1612
		return (object) array(
1613
			'secret'           => $valid_token,
1614
			'external_user_id' => (int) $user_id,
1615
		);
1616
	}
1617
1618
	/**
1619
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
1620
	 * since it is passed by reference to various methods.
1621
	 * Capture it here so we can verify the signature later.
1622
	 *
1623
	 * @param Array $methods an array of available XMLRPC methods.
1624
	 * @return Array the same array, since this method doesn't add or remove anything.
1625
	 */
1626
	public function xmlrpc_methods( $methods ) {
1627
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
1628
		return $methods;
1629
	}
1630
1631
	/**
1632
	 * Resets the raw post data parameter for testing purposes.
1633
	 */
1634
	public function reset_raw_post_data() {
1635
		$this->raw_post_data = null;
1636
	}
1637
1638
	/**
1639
	 * Registering an additional method.
1640
	 *
1641
	 * @param Array $methods an array of available XMLRPC methods.
1642
	 * @return Array the amended array in case the method is added.
1643
	 */
1644
	public function public_xmlrpc_methods( $methods ) {
1645
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
1646
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
1647
		}
1648
		return $methods;
1649
	}
1650
1651
	/**
1652
	 * Handles a getOptions XMLRPC method call.
1653
	 *
1654
	 * @param Array $args method call arguments.
1655
	 * @return an amended XMLRPC server options array.
1656
	 */
1657
	public function jetpack_get_options( $args ) {
1658
		global $wp_xmlrpc_server;
1659
1660
		$wp_xmlrpc_server->escape( $args );
1661
1662
		$username = $args[1];
1663
		$password = $args[2];
1664
1665
		$user = $wp_xmlrpc_server->login( $username, $password );
1666
		if ( ! $user ) {
1667
			return $wp_xmlrpc_server->error;
1668
		}
1669
1670
		$options   = array();
1671
		$user_data = $this->get_connected_user_data();
1672
		if ( is_array( $user_data ) ) {
1673
			$options['jetpack_user_id']         = array(
1674
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
1675
				'readonly' => true,
1676
				'value'    => $user_data['ID'],
1677
			);
1678
			$options['jetpack_user_login']      = array(
1679
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
1680
				'readonly' => true,
1681
				'value'    => $user_data['login'],
1682
			);
1683
			$options['jetpack_user_email']      = array(
1684
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
1685
				'readonly' => true,
1686
				'value'    => $user_data['email'],
1687
			);
1688
			$options['jetpack_user_site_count'] = array(
1689
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
1690
				'readonly' => true,
1691
				'value'    => $user_data['site_count'],
1692
			);
1693
		}
1694
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
1695
		$args                           = stripslashes_deep( $args );
1696
		return $wp_xmlrpc_server->wp_getOptions( $args );
1697
	}
1698
1699
	/**
1700
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
1701
	 *
1702
	 * @param Array $options standard Core options.
1703
	 * @return Array amended options.
1704
	 */
1705
	public function xmlrpc_options( $options ) {
1706
		$jetpack_client_id = false;
1707
		if ( $this->is_active() ) {
1708
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
1709
		}
1710
		$options['jetpack_version'] = array(
1711
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
1712
			'readonly' => true,
1713
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
1714
		);
1715
1716
		$options['jetpack_client_id'] = array(
1717
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
1718
			'readonly' => true,
1719
			'value'    => $jetpack_client_id,
1720
		);
1721
		return $options;
1722
	}
1723
1724
	/**
1725
	 * Resets the saved authentication state in between testing requests.
1726
	 */
1727
	public function reset_saved_auth_state() {
1728
		$this->xmlrpc_verification = null;
1729
	}
1730
1731
	/**
1732
	 * Sign a user role with the master access token.
1733
	 * If not specified, will default to the current user.
1734
	 *
1735
	 * @access public
1736
	 *
1737
	 * @param string $role    User role.
1738
	 * @param int    $user_id ID of the user.
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...
1739
	 * @return string Signed user role.
1740
	 */
1741
	public function sign_role( $role, $user_id = null ) {
1742
		if ( empty( $user_id ) ) {
1743
			$user_id = (int) get_current_user_id();
1744
		}
1745
1746
		if ( ! $user_id ) {
1747
			return false;
1748
		}
1749
1750
		$token = $this->get_access_token();
1751
		if ( ! $token || is_wp_error( $token ) ) {
1752
			return false;
1753
		}
1754
1755
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
1756
	}
1757
}
1758