Completed
Push — add/ratings ( 93b123...83fca1 )
by Andrés
34:53 queued 28:17
created

Manager::disconnect_site_wpcom()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
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\Roles;
12
use Automattic\Jetpack\Tracking;
13
14
/**
15
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
16
 * and Jetpack.
17
 */
18
class Manager {
19
20
	const SECRETS_MISSING        = 'secrets_missing';
21
	const SECRETS_EXPIRED        = 'secrets_expired';
22
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
23
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
24
	const JETPACK_MASTER_USER    = true;
25
26
	/**
27
	 * The procedure that should be run to generate secrets.
28
	 *
29
	 * @var Callable
30
	 */
31
	protected $secret_callable;
32
33
	/**
34
	 * A copy of the raw POST data for signature verification purposes.
35
	 *
36
	 * @var String
37
	 */
38
	protected $raw_post_data;
39
40
	/**
41
	 * Verification data needs to be stored to properly verify everything.
42
	 *
43
	 * @var Object
44
	 */
45
	private $xmlrpc_verification = null;
46
47
	/**
48
	 * Initializes required listeners. This is done separately from the constructors
49
	 * because some objects sometimes need to instantiate separate objects of this class.
50
	 *
51
	 * @todo Implement a proper nonce verification.
52
	 */
53
	public function init() {
54
		$this->setup_xmlrpc_handlers(
55
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
56
			$this->is_active(),
57
			$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...
58
		);
59
60
		if ( $this->is_active() ) {
61
			add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
62
		} else {
63
			add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
64
		}
65
66
		add_action( 'jetpack_clean_nonces', array( $this, 'clean_nonces' ) );
67
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
68
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
69
		}
70
	}
71
72
	/**
73
	 * Sets up the XMLRPC request handlers.
74
	 *
75
	 * @param Array                  $request_params incoming request parameters.
76
	 * @param Boolean                $is_active whether the connection is currently active.
77
	 * @param Boolean                $is_signed whether the signature check has been successful.
78
	 * @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...
79
	 */
80
	public function setup_xmlrpc_handlers(
81
		$request_params,
82
		$is_active,
83
		$is_signed,
84
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
85
	) {
86
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
87
88
		if (
89
			! isset( $request_params['for'] )
90
			|| 'jetpack' !== $request_params['for']
91
		) {
92
			return false;
93
		}
94
95
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
96
		if (
97
			isset( $request_params['jetpack'] )
98
			&& 'comms' === $request_params['jetpack']
99
		) {
100
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
101
				// Use the real constant here for WordPress' sake.
102
				define( 'XMLRPC_REQUEST', true );
103
			}
104
105
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
106
107
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
108
		}
109
110
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
111
			return false;
112
		}
113
		// Display errors can cause the XML to be not well formed.
114
		@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...
115
116
		if ( $xmlrpc_server ) {
117
			$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...
118
		} else {
119
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
120
		}
121
122
		$this->require_jetpack_authentication();
123
124
		if ( $is_active ) {
125
			// Hack to preserve $HTTP_RAW_POST_DATA.
126
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
127
128
			if ( $is_signed ) {
129
				// The actual API methods.
130
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
131
			} else {
132
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
133
				// active Jetpack connection, so that additional users can link their account.
134
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
135
			}
136
		} else {
137
			// The bootstrap API methods.
138
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
139
140
			if ( $is_signed ) {
141
				// The jetpack Provision method is available for blog-token-signed requests.
142
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
143
			} else {
144
				new XMLRPC_Connector( $this );
145
			}
146
		}
147
148
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
149
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
150
		return true;
151
	}
152
153
	/**
154
	 * Initializes the REST API connector on the init hook.
155
	 */
156
	public function initialize_rest_api_registration_connector() {
157
		new REST_Connector( $this );
158
	}
159
160
	/**
161
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
162
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
163
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
164
	 * which is accessible via a different URI. Most of the below is copied directly
165
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
166
	 *
167
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
168
	 */
169
	public function alternate_xmlrpc() {
170
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
171
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
172
		global $HTTP_RAW_POST_DATA;
173
174
		// Some browser-embedded clients send cookies. We don't want them.
175
		$_COOKIE = array();
176
177
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
178
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
179
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
180
		}
181
182
		// phpcs:enable
183
184
		include_once ABSPATH . 'wp-admin/includes/admin.php';
185
		include_once ABSPATH . WPINC . '/class-IXR.php';
186
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
187
188
		/**
189
		 * Filters the class used for handling XML-RPC requests.
190
		 *
191
		 * @since 3.1.0
192
		 *
193
		 * @param string $class The name of the XML-RPC server class.
194
		 */
195
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
196
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
197
198
		// Fire off the request.
199
		nocache_headers();
200
		$wp_xmlrpc_server->serve_request();
201
202
		exit;
203
	}
204
205
	/**
206
	 * Removes all XML-RPC methods that are not `jetpack.*`.
207
	 * Only used in our alternate XML-RPC endpoint, where we want to
208
	 * ensure that Core and other plugins' methods are not exposed.
209
	 *
210
	 * @param array $methods a list of registered WordPress XMLRPC methods.
211
	 * @return array filtered $methods
212
	 */
213
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
214
		$jetpack_methods = array();
215
216
		foreach ( $methods as $method => $callback ) {
217
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
218
				$jetpack_methods[ $method ] = $callback;
219
			}
220
		}
221
222
		return $jetpack_methods;
223
	}
224
225
	/**
226
	 * Removes all other authentication methods not to allow other
227
	 * methods to validate unauthenticated requests.
228
	 */
229
	public function require_jetpack_authentication() {
230
		// Don't let anyone authenticate.
231
		$_COOKIE = array();
232
		remove_all_filters( 'authenticate' );
233
		remove_all_actions( 'wp_login_failed' );
234
235
		if ( $this->is_active() ) {
236
			// Allow Jetpack authentication.
237
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
238
		}
239
	}
240
241
	/**
242
	 * Authenticates XML-RPC and other requests from the Jetpack Server
243
	 *
244
	 * @param WP_User|Mixed $user user object if authenticated.
245
	 * @param String        $username username.
246
	 * @param String        $password password string.
247
	 * @return WP_User|Mixed authenticated user or error.
248
	 */
249
	public function authenticate_jetpack( $user, $username, $password ) {
250
		if ( is_a( $user, '\\WP_User' ) ) {
251
			return $user;
252
		}
253
254
		$token_details = $this->verify_xml_rpc_signature();
255
256
		if ( ! $token_details ) {
257
			return $user;
258
		}
259
260
		if ( 'user' !== $token_details['type'] ) {
261
			return $user;
262
		}
263
264
		if ( ! $token_details['user_id'] ) {
265
			return $user;
266
		}
267
268
		nocache_headers();
269
270
		return new \WP_User( $token_details['user_id'] );
271
	}
272
273
	/**
274
	 * Verifies the signature of the current request.
275
	 *
276
	 * @return false|array
277
	 */
278
	public function verify_xml_rpc_signature() {
279
		if ( is_null( $this->xmlrpc_verification ) ) {
280
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
281
282
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
283
				/**
284
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
285
				 *
286
				 * Error codes:
287
				 * - malformed_token
288
				 * - malformed_user_id
289
				 * - unknown_token
290
				 * - could_not_sign
291
				 * - invalid_nonce
292
				 * - signature_mismatch
293
				 *
294
				 * @since 7.5.0
295
				 *
296
				 * @param WP_Error $signature_verification_error The verification error
297
				 */
298
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
299
			}
300
		}
301
302
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
303
	}
304
305
	/**
306
	 * Verifies the signature of the current request.
307
	 *
308
	 * This function has side effects and should not be used. Instead,
309
	 * use the memoized version `->verify_xml_rpc_signature()`.
310
	 *
311
	 * @internal
312
	 * @todo Refactor to use proper nonce verification.
313
	 */
314
	private function internal_verify_xml_rpc_signature() {
315
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
316
		// It's not for us.
317
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
318
			return false;
319
		}
320
321
		$signature_details = array(
322
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
323
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
324
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
325
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
326
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
327
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
328
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
329
		);
330
331
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
332
		@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...
333
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
334
335
		if (
336
			empty( $token_key )
337
		||
338
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
339
		) {
340
			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...
341
		}
342
343
		if ( '0' === $user_id ) {
344
			$token_type = 'blog';
345
			$user_id    = 0;
346
		} else {
347
			$token_type = 'user';
348
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
349
				return new \WP_Error(
350
					'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...
351
					'Malformed user_id in request',
352
					compact( 'signature_details' )
353
				);
354
			}
355
			$user_id = (int) $user_id;
356
357
			$user = new \WP_User( $user_id );
358
			if ( ! $user || ! $user->exists() ) {
359
				return new \WP_Error(
360
					'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...
361
					sprintf( 'User %d does not exist', $user_id ),
362
					compact( 'signature_details' )
363
				);
364
			}
365
		}
366
367
		$token = $this->get_access_token( $user_id, $token_key, false );
368
		if ( is_wp_error( $token ) ) {
369
			$token->add_data( compact( 'signature_details' ) );
370
			return $token;
371
		} elseif ( ! $token ) {
372
			return new \WP_Error(
373
				'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...
374
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
375
				compact( 'signature_details' )
376
			);
377
		}
378
379
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
380
		// phpcs:disable WordPress.Security.NonceVerification.Missing
381
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
382
			$post_data   = $_POST;
383
			$file_hashes = array();
384
			foreach ( $post_data as $post_data_key => $post_data_value ) {
385
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
386
					continue;
387
				}
388
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
389
				$file_hashes[ $post_data_key ] = $post_data_value;
390
			}
391
392
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
393
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
394
				$post_data[ $post_data_key ] = $post_data_value;
395
			}
396
397
			ksort( $post_data );
398
399
			$body = http_build_query( stripslashes_deep( $post_data ) );
400
		} elseif ( is_null( $this->raw_post_data ) ) {
401
			$body = file_get_contents( 'php://input' );
402
		} else {
403
			$body = null;
404
		}
405
		// phpcs:enable
406
407
		$signature = $jetpack_signature->sign_current_request(
408
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
409
		);
410
411
		$signature_details['url'] = $jetpack_signature->current_request_url;
412
413
		if ( ! $signature ) {
414
			return new \WP_Error(
415
				'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...
416
				'Unknown signature error',
417
				compact( 'signature_details' )
418
			);
419
		} elseif ( is_wp_error( $signature ) ) {
420
			return $signature;
421
		}
422
423
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
424
		$timestamp = (int) $_GET['timestamp'];
425
		$nonce     = stripslashes( (string) $_GET['nonce'] );
426
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
427
428
		// Use up the nonce regardless of whether the signature matches.
429
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
430
			return new \WP_Error(
431
				'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...
432
				'Could not add nonce',
433
				compact( 'signature_details' )
434
			);
435
		}
436
437
		// Be careful about what you do with this debugging data.
438
		// If a malicious requester has access to the expected signature,
439
		// bad things might be possible.
440
		$signature_details['expected'] = $signature;
441
442
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
443
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
444
			return new \WP_Error(
445
				'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...
446
				'Signature mismatch',
447
				compact( 'signature_details' )
448
			);
449
		}
450
451
		/**
452
		 * Action for additional token checking.
453
		 *
454
		 * @since 7.7.0
455
		 *
456
		 * @param Array $post_data request data.
457
		 * @param Array $token_data token data.
458
		 */
459
		return apply_filters(
460
			'jetpack_signature_check_token',
461
			array(
462
				'type'      => $token_type,
463
				'token_key' => $token_key,
464
				'user_id'   => $token->external_user_id,
465
			),
466
			$token,
467
			$this->raw_post_data
468
		);
469
	}
470
471
	/**
472
	 * Returns true if the current site is connected to WordPress.com.
473
	 *
474
	 * @return Boolean is the site connected?
475
	 */
476
	public function is_active() {
477
		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...
478
	}
479
480
	/**
481
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
482
	 *
483
	 * @access public
484
	 *
485
	 * @return bool
486
	 */
487
	public function is_registered() {
488
		$blog_id   = \Jetpack_Options::get_option( 'id' );
489
		$has_token = $this->is_active();
490
		return $blog_id && $has_token;
491
	}
492
493
	/**
494
	 * Checks to see if the connection owner of the site is missing.
495
	 *
496
	 * @return bool
497
	 */
498
	public function is_missing_connection_owner() {
499
		$connection_owner = $this->get_connection_owner_id();
500
		if ( ! get_user_by( 'id', $connection_owner ) ) {
501
			return true;
502
		}
503
504
		return false;
505
	}
506
507
	/**
508
	 * Returns true if the user with the specified identifier is connected to
509
	 * WordPress.com.
510
	 *
511
	 * @param Integer|Boolean $user_id the user identifier.
512
	 * @return Boolean is the user connected?
513
	 */
514
	public function is_user_connected( $user_id = false ) {
515
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
516
		if ( ! $user_id ) {
517
			return false;
518
		}
519
520
		return (bool) $this->get_access_token( $user_id );
521
	}
522
523
	/**
524
	 * Returns the local user ID of the connection owner.
525
	 *
526
	 * @return string|int Returns the ID of the connection owner or False if no connection owner found.
527
	 */
528 View Code Duplication
	public function get_connection_owner_id() {
529
		$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...
530
		$connection_owner = false;
531
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
532
			$connection_owner = $user_token->external_user_id;
533
		}
534
535
		return $connection_owner;
536
	}
537
538
	/**
539
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
540
	 * Able to select by specific capability.
541
	 *
542
	 * @param string $capability The capability of the user.
543
	 * @return array Array of WP_User objects if found.
544
	 */
545
	public function get_connected_users( $capability = 'any' ) {
546
		$connected_users    = array();
547
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
548
549
		if ( ! empty( $connected_user_ids ) ) {
550
			foreach ( $connected_user_ids as $id ) {
551
				// Check for capability.
552
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
553
					continue;
554
				}
555
556
				$connected_users[] = get_userdata( $id );
557
			}
558
		}
559
560
		return $connected_users;
561
	}
562
563
	/**
564
	 * Get the wpcom user data of the current|specified connected user.
565
	 *
566
	 * @todo Refactor to properly load the XMLRPC client independently.
567
	 *
568
	 * @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...
569
	 * @return Object the user object.
570
	 */
571 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
572
		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...
573
			$user_id = get_current_user_id();
574
		}
575
576
		$transient_key    = "jetpack_connected_user_data_$user_id";
577
		$cached_user_data = get_transient( $transient_key );
578
579
		if ( $cached_user_data ) {
580
			return $cached_user_data;
581
		}
582
583
		$xml = new \Jetpack_IXR_Client(
584
			array(
585
				'user_id' => $user_id,
586
			)
587
		);
588
		$xml->query( 'wpcom.getUser' );
589
		if ( ! $xml->isError() ) {
590
			$user_data = $xml->getResponse();
591
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
592
			return $user_data;
593
		}
594
595
		return false;
596
	}
597
598
	/**
599
	 * Returns a user object of the connection owner.
600
	 *
601
	 * @return object|false False if no connection owner found.
602
	 */
603 View Code Duplication
	public function get_connection_owner() {
604
		$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...
605
606
		$connection_owner = false;
607
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
608
			$connection_owner = get_userdata( $user_token->external_user_id );
609
		}
610
611
		return $connection_owner;
612
	}
613
614
	/**
615
	 * Returns true if the provided user is the Jetpack connection owner.
616
	 * If user ID is not specified, the current user will be used.
617
	 *
618
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
619
	 * @return Boolean True the user the connection owner, false otherwise.
620
	 */
621 View Code Duplication
	public function is_connection_owner( $user_id = false ) {
622
		if ( ! $user_id ) {
623
			$user_id = get_current_user_id();
624
		}
625
626
		$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...
627
628
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
629
	}
630
631
	/**
632
	 * Connects the user with a specified ID to a WordPress.com user using the
633
	 * remote login flow.
634
	 *
635
	 * @access public
636
	 *
637
	 * @param Integer $user_id (optional) the user identifier, defaults to current 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...
638
	 * @param String  $redirect_url the URL to redirect the user to for processing, defaults to
0 ignored issues
show
Documentation introduced by
Should the type for parameter $redirect_url not be string|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
	 *                              admin_url().
640
	 * @return WP_Error only in case of a failed user lookup.
641
	 */
642
	public function connect_user( $user_id = null, $redirect_url = null ) {
643
		$user = null;
0 ignored issues
show
Unused Code introduced by
$user is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
644
		if ( null === $user_id ) {
645
			$user = wp_get_current_user();
646
		} else {
647
			$user = get_user_by( 'ID', $user_id );
648
		}
649
650
		if ( empty( $user ) ) {
651
			return new \WP_Error( 'user_not_found', 'Attempting to connect a non-existent user.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_not_found'.

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...
652
		}
653
654
		if ( null === $redirect_url ) {
655
			$redirect_url = admin_url();
0 ignored issues
show
Unused Code introduced by
$redirect_url is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
656
		}
657
658
		// Using wp_redirect intentionally because we're redirecting outside.
659
		wp_redirect( $this->get_authorization_url( $user ) ); // phpcs:ignore WordPress.Security.SafeRedirect
660
		exit();
661
	}
662
663
	/**
664
	 * Unlinks the current user from the linked WordPress.com user.
665
	 *
666
	 * @access public
667
	 * @static
668
	 *
669
	 * @todo Refactor to properly load the XMLRPC client independently.
670
	 *
671
	 * @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...
672
	 * @return Boolean Whether the disconnection of the user was successful.
673
	 */
674
	public static function disconnect_user( $user_id = null ) {
675
		$tokens = \Jetpack_Options::get_option( 'user_tokens' );
676
		if ( ! $tokens ) {
677
			return false;
678
		}
679
680
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
681
682
		if ( \Jetpack_Options::get_option( 'master_user' ) === $user_id ) {
683
			return false;
684
		}
685
686
		if ( ! isset( $tokens[ $user_id ] ) ) {
687
			return false;
688
		}
689
690
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
691
		$xml->query( 'jetpack.unlink_user', $user_id );
692
693
		unset( $tokens[ $user_id ] );
694
695
		\Jetpack_Options::update_option( 'user_tokens', $tokens );
696
697
		/**
698
		 * Fires after the current user has been unlinked from WordPress.com.
699
		 *
700
		 * @since 4.1.0
701
		 *
702
		 * @param int $user_id The current user's ID.
703
		 */
704
		do_action( 'jetpack_unlinked_user', $user_id );
705
706
		return true;
707
	}
708
709
	/**
710
	 * Returns the requested Jetpack API URL.
711
	 *
712
	 * @param String $relative_url the relative API path.
713
	 * @return String API URL.
714
	 */
715
	public function api_url( $relative_url ) {
716
		$api_base = Constants::get_constant( 'JETPACK__API_BASE' );
717
		$version  = Constants::get_constant( 'JETPACK__API_VERSION' );
718
719
		$api_base = $api_base ? $api_base : 'https://jetpack.wordpress.com/jetpack.';
720
		$version  = $version ? '/' . $version . '/' : '/1/';
721
722
		/**
723
		 * Filters the API URL that Jetpack uses for server communication.
724
		 *
725
		 * @since 8.0.0
726
		 *
727
		 * @param String $url the generated URL.
728
		 * @param String $relative_url the relative URL that was passed as an argument.
729
		 * @param String $api_base the API base string that is being used.
730
		 * @param String $version the version string that is being used.
731
		 */
732
		return apply_filters(
733
			'jetpack_api_url',
734
			rtrim( $api_base . $relative_url, '/\\' ) . $version,
735
			$relative_url,
736
			$api_base,
737
			$version
738
		);
739
	}
740
741
	/**
742
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
743
	 *
744
	 * @return String XMLRPC API URL.
745
	 */
746
	public function xmlrpc_api_url() {
747
		$base = preg_replace(
748
			'#(https?://[^?/]+)(/?.*)?$#',
749
			'\\1',
750
			Constants::get_constant( 'JETPACK__API_BASE' )
751
		);
752
		return untrailingslashit( $base ) . '/xmlrpc.php';
753
	}
754
755
	/**
756
	 * Attempts Jetpack registration which sets up the site for connection. Should
757
	 * remain public because the call to action comes from the current site, not from
758
	 * WordPress.com.
759
	 *
760
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
761
	 * @return Integer zero on success, or a bitmask on failure.
762
	 */
763
	public function register( $api_endpoint = 'register' ) {
764
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
765
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
766
767
		if (
768
			empty( $secrets['secret_1'] ) ||
769
			empty( $secrets['secret_2'] ) ||
770
			empty( $secrets['exp'] )
771
		) {
772
			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...
773
		}
774
775
		// Better to try (and fail) to set a higher timeout than this system
776
		// supports than to have register fail for more users than it should.
777
		$timeout = $this->set_min_time_limit( 60 ) / 2;
778
779
		$gmt_offset = get_option( 'gmt_offset' );
780
		if ( ! $gmt_offset ) {
781
			$gmt_offset = 0;
782
		}
783
784
		$stats_options = get_option( 'stats_options' );
785
		$stats_id      = isset( $stats_options['blog_id'] )
786
			? $stats_options['blog_id']
787
			: null;
788
789
		/**
790
		 * Filters the request body for additional property addition.
791
		 *
792
		 * @since 7.7.0
793
		 *
794
		 * @param Array $post_data request data.
795
		 * @param Array $token_data token data.
796
		 */
797
		$body = apply_filters(
798
			'jetpack_register_request_body',
799
			array(
800
				'siteurl'         => site_url(),
801
				'home'            => home_url(),
802
				'gmt_offset'      => $gmt_offset,
803
				'timezone_string' => (string) get_option( 'timezone_string' ),
804
				'site_name'       => (string) get_option( 'blogname' ),
805
				'secret_1'        => $secrets['secret_1'],
806
				'secret_2'        => $secrets['secret_2'],
807
				'site_lang'       => get_locale(),
808
				'timeout'         => $timeout,
809
				'stats_id'        => $stats_id,
810
				'state'           => get_current_user_id(),
811
				'site_created'    => $this->get_assumed_site_creation_date(),
812
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
813
			)
814
		);
815
816
		$args = array(
817
			'method'  => 'POST',
818
			'body'    => $body,
819
			'headers' => array(
820
				'Accept' => 'application/json',
821
			),
822
			'timeout' => $timeout,
823
		);
824
825
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
826
827
		// TODO: fix URLs for bad hosts.
828
		$response = Client::_wp_remote_request(
829
			$this->api_url( $api_endpoint ),
830
			$args,
831
			true
832
		);
833
834
		// Make sure the response is valid and does not contain any Jetpack errors.
835
		$registration_details = $this->validate_remote_register_response( $response );
836
837
		if ( is_wp_error( $registration_details ) ) {
838
			return $registration_details;
839
		} elseif ( ! $registration_details ) {
840
			return new \WP_Error(
841
				'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...
842
				'Unknown error registering your Jetpack site.',
843
				wp_remote_retrieve_response_code( $response )
844
			);
845
		}
846
847
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
848
			return new \WP_Error(
849
				'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...
850
				'Unable to validate registration of your Jetpack site.',
851
				wp_remote_retrieve_response_code( $response )
852
			);
853
		}
854
855
		if ( isset( $registration_details->jetpack_public ) ) {
856
			$jetpack_public = (int) $registration_details->jetpack_public;
857
		} else {
858
			$jetpack_public = false;
859
		}
860
861
		\Jetpack_Options::update_options(
862
			array(
863
				'id'         => (int) $registration_details->jetpack_id,
864
				'blog_token' => (string) $registration_details->jetpack_secret,
865
				'public'     => $jetpack_public,
866
			)
867
		);
868
869
		/**
870
		 * Fires when a site is registered on WordPress.com.
871
		 *
872
		 * @since 3.7.0
873
		 *
874
		 * @param int $json->jetpack_id Jetpack Blog ID.
875
		 * @param string $json->jetpack_secret Jetpack Blog Token.
876
		 * @param int|bool $jetpack_public Is the site public.
877
		 */
878
		do_action(
879
			'jetpack_site_registered',
880
			$registration_details->jetpack_id,
881
			$registration_details->jetpack_secret,
882
			$jetpack_public
883
		);
884
885
		if ( isset( $registration_details->token ) ) {
886
			/**
887
			 * Fires when a user token is sent along with the registration data.
888
			 *
889
			 * @since 7.6.0
890
			 *
891
			 * @param object $token the administrator token for the newly registered site.
892
			 */
893
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
894
		}
895
896
		return true;
897
	}
898
899
	/**
900
	 * Takes the response from the Jetpack register new site endpoint and
901
	 * verifies it worked properly.
902
	 *
903
	 * @since 2.6
904
	 *
905
	 * @param Mixed $response the response object, or the error object.
906
	 * @return string|WP_Error A JSON object on success or Jetpack_Error on failures
907
	 **/
908
	protected function validate_remote_register_response( $response ) {
909
		if ( is_wp_error( $response ) ) {
910
			return new \WP_Error(
911
				'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...
912
				$response->get_error_message()
913
			);
914
		}
915
916
		$code   = wp_remote_retrieve_response_code( $response );
917
		$entity = wp_remote_retrieve_body( $response );
918
919
		if ( $entity ) {
920
			$registration_response = json_decode( $entity );
921
		} else {
922
			$registration_response = false;
923
		}
924
925
		$code_type = intval( $code / 100 );
926
		if ( 5 === $code_type ) {
927
			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...
928
		} elseif ( 408 === $code ) {
929
			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...
930
		} elseif ( ! empty( $registration_response->error ) ) {
931
			if (
932
				'xml_rpc-32700' === $registration_response->error
933
				&& ! function_exists( 'xml_parser_create' )
934
			) {
935
				$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' );
936
			} else {
937
				$error_description = isset( $registration_response->error_description )
938
					? (string) $registration_response->error_description
939
					: '';
940
			}
941
942
			return new \WP_Error(
943
				(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...
944
				$error_description,
945
				$code
946
			);
947
		} elseif ( 200 !== $code ) {
948
			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...
949
		}
950
951
		// Jetpack ID error block.
952
		if ( empty( $registration_response->jetpack_id ) ) {
953
			return new \WP_Error(
954
				'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...
955
				/* translators: %s is an error message string */
956
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
957
				$entity
958
			);
959
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
960
			return new \WP_Error(
961
				'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...
962
				/* translators: %s is an error message string */
963
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
964
				$entity
965
			);
966 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
967
			return new \WP_Error(
968
				'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...
969
				/* translators: %s is an error message string */
970
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
971
				$entity
972
			);
973
		}
974
975
		return $registration_response;
976
	}
977
978
	/**
979
	 * Adds a used nonce to a list of known nonces.
980
	 *
981
	 * @param int    $timestamp the current request timestamp.
982
	 * @param string $nonce the nonce value.
983
	 * @return bool whether the nonce is unique or not.
984
	 */
985
	public function add_nonce( $timestamp, $nonce ) {
986
		global $wpdb;
987
		static $nonces_used_this_request = array();
988
989
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
990
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
991
		}
992
993
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
994
		$timestamp = (int) $timestamp;
995
		$nonce     = esc_sql( $nonce );
996
997
		// Raw query so we can avoid races: add_option will also update.
998
		$show_errors = $wpdb->show_errors( false );
999
1000
		$old_nonce = $wpdb->get_row(
1001
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1002
		);
1003
1004
		if ( is_null( $old_nonce ) ) {
1005
			$return = $wpdb->query(
1006
				$wpdb->prepare(
1007
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1008
					"jetpack_nonce_{$timestamp}_{$nonce}",
1009
					time(),
1010
					'no'
1011
				)
1012
			);
1013
		} else {
1014
			$return = false;
1015
		}
1016
1017
		$wpdb->show_errors( $show_errors );
1018
1019
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1020
1021
		return $return;
1022
	}
1023
1024
	/**
1025
	 * Cleans nonces that were saved when calling ::add_nonce.
1026
	 *
1027
	 * @todo Properly prepare the query before executing it.
1028
	 *
1029
	 * @param bool $all whether to clean even non-expired nonces.
1030
	 */
1031
	public function clean_nonces( $all = false ) {
1032
		global $wpdb;
1033
1034
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1035
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1036
1037
		if ( true !== $all ) {
1038
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1039
			$sql_args[] = time() - 3600;
1040
		}
1041
1042
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1043
1044
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1045
1046
		for ( $i = 0; $i < 1000; $i++ ) {
1047
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1048
				break;
1049
			}
1050
		}
1051
	}
1052
1053
	/**
1054
	 * Builds the timeout limit for queries talking with the wpcom servers.
1055
	 *
1056
	 * Based on local php max_execution_time in php.ini
1057
	 *
1058
	 * @since 5.4
1059
	 * @return int
1060
	 **/
1061
	public function get_max_execution_time() {
1062
		$timeout = (int) ini_get( 'max_execution_time' );
1063
1064
		// Ensure exec time set in php.ini.
1065
		if ( ! $timeout ) {
1066
			$timeout = 30;
1067
		}
1068
		return $timeout;
1069
	}
1070
1071
	/**
1072
	 * Sets a minimum request timeout, and returns the current timeout
1073
	 *
1074
	 * @since 5.4
1075
	 * @param Integer $min_timeout the minimum timeout value.
1076
	 **/
1077 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1078
		$timeout = $this->get_max_execution_time();
1079
		if ( $timeout < $min_timeout ) {
1080
			$timeout = $min_timeout;
1081
			set_time_limit( $timeout );
1082
		}
1083
		return $timeout;
1084
	}
1085
1086
	/**
1087
	 * Get our assumed site creation date.
1088
	 * Calculated based on the earlier date of either:
1089
	 * - Earliest admin user registration date.
1090
	 * - Earliest date of post of any post type.
1091
	 *
1092
	 * @since 7.2.0
1093
	 *
1094
	 * @return string Assumed site creation date and time.
1095
	 */
1096
	public function get_assumed_site_creation_date() {
1097
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1098
		if ( ! empty( $cached_date ) ) {
1099
			return $cached_date;
1100
		}
1101
1102
		$earliest_registered_users  = get_users(
1103
			array(
1104
				'role'    => 'administrator',
1105
				'orderby' => 'user_registered',
1106
				'order'   => 'ASC',
1107
				'fields'  => array( 'user_registered' ),
1108
				'number'  => 1,
1109
			)
1110
		);
1111
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1112
1113
		$earliest_posts = get_posts(
1114
			array(
1115
				'posts_per_page' => 1,
1116
				'post_type'      => 'any',
1117
				'post_status'    => 'any',
1118
				'orderby'        => 'date',
1119
				'order'          => 'ASC',
1120
			)
1121
		);
1122
1123
		// If there are no posts at all, we'll count only on user registration date.
1124
		if ( $earliest_posts ) {
1125
			$earliest_post_date = $earliest_posts[0]->post_date;
1126
		} else {
1127
			$earliest_post_date = PHP_INT_MAX;
1128
		}
1129
1130
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1131
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1132
1133
		return $assumed_date;
1134
	}
1135
1136
	/**
1137
	 * Adds the activation source string as a parameter to passed arguments.
1138
	 *
1139
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1140
	 *
1141
	 * @param Array $args arguments that need to have the source added.
1142
	 * @return Array $amended arguments.
1143
	 */
1144 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1145
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1146
1147
		if ( $activation_source_name ) {
1148
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1149
			$args['_as'] = urlencode( $activation_source_name );
1150
		}
1151
1152
		if ( $activation_source_keyword ) {
1153
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1154
			$args['_ak'] = urlencode( $activation_source_keyword );
1155
		}
1156
1157
		return $args;
1158
	}
1159
1160
	/**
1161
	 * Returns the callable that would be used to generate secrets.
1162
	 *
1163
	 * @return Callable a function that returns a secure string to be used as a secret.
1164
	 */
1165
	protected function get_secret_callable() {
1166
		if ( ! isset( $this->secret_callable ) ) {
1167
			/**
1168
			 * Allows modification of the callable that is used to generate connection secrets.
1169
			 *
1170
			 * @param Callable a function or method that returns a secret string.
1171
			 */
1172
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', 'wp_generate_password' );
1173
		}
1174
1175
		return $this->secret_callable;
1176
	}
1177
1178
	/**
1179
	 * Generates two secret tokens and the end of life timestamp for them.
1180
	 *
1181
	 * @param String  $action  The action name.
1182
	 * @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...
1183
	 * @param Integer $exp     Expiration time in seconds.
1184
	 */
1185
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1186
		if ( false === $user_id ) {
1187
			$user_id = get_current_user_id();
1188
		}
1189
1190
		$callable = $this->get_secret_callable();
1191
1192
		$secrets = \Jetpack_Options::get_raw_option(
1193
			self::SECRETS_OPTION_NAME,
1194
			array()
1195
		);
1196
1197
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1198
1199
		if (
1200
			isset( $secrets[ $secret_name ] ) &&
1201
			$secrets[ $secret_name ]['exp'] > time()
1202
		) {
1203
			return $secrets[ $secret_name ];
1204
		}
1205
1206
		$secret_value = array(
1207
			'secret_1' => call_user_func( $callable ),
1208
			'secret_2' => call_user_func( $callable ),
1209
			'exp'      => time() + $exp,
1210
		);
1211
1212
		$secrets[ $secret_name ] = $secret_value;
1213
1214
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1215
		return $secrets[ $secret_name ];
1216
	}
1217
1218
	/**
1219
	 * Returns two secret tokens and the end of life timestamp for them.
1220
	 *
1221
	 * @param String  $action  The action name.
1222
	 * @param Integer $user_id The user identifier.
1223
	 * @return string|array an array of secrets or an error string.
1224
	 */
1225
	public function get_secrets( $action, $user_id ) {
1226
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1227
		$secrets     = \Jetpack_Options::get_raw_option(
1228
			self::SECRETS_OPTION_NAME,
1229
			array()
1230
		);
1231
1232
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1233
			return self::SECRETS_MISSING;
1234
		}
1235
1236
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1237
			$this->delete_secrets( $action, $user_id );
1238
			return self::SECRETS_EXPIRED;
1239
		}
1240
1241
		return $secrets[ $secret_name ];
1242
	}
1243
1244
	/**
1245
	 * Deletes secret tokens in case they, for example, have expired.
1246
	 *
1247
	 * @param String  $action  The action name.
1248
	 * @param Integer $user_id The user identifier.
1249
	 */
1250
	public function delete_secrets( $action, $user_id ) {
1251
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1252
		$secrets     = \Jetpack_Options::get_raw_option(
1253
			self::SECRETS_OPTION_NAME,
1254
			array()
1255
		);
1256
		if ( isset( $secrets[ $secret_name ] ) ) {
1257
			unset( $secrets[ $secret_name ] );
1258
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1259
		}
1260
	}
1261
1262
	/**
1263
	 * Responds to a WordPress.com call to register the current site.
1264
	 * Should be changed to protected.
1265
	 *
1266
	 * @param array $registration_data Array of [ secret_1, user_id ].
1267
	 */
1268
	public function handle_registration( array $registration_data ) {
1269
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1270
		if ( empty( $registration_user_id ) ) {
1271
			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...
1272
		}
1273
1274
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1275
	}
1276
1277
	/**
1278
	 * Verify a Previously Generated Secret.
1279
	 *
1280
	 * @param string $action   The type of secret to verify.
1281
	 * @param string $secret_1 The secret string to compare to what is stored.
1282
	 * @param int    $user_id  The user ID of the owner of the secret.
1283
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1284
	 */
1285
	public function verify_secrets( $action, $secret_1, $user_id ) {
1286
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1287
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1288
			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...
1289
		}
1290
1291
		$user = get_user_by( 'id', $user_id );
1292
1293
		/**
1294
		 * We've begun verifying the previously generated secret.
1295
		 *
1296
		 * @since 7.5.0
1297
		 *
1298
		 * @param string   $action The type of secret to verify.
1299
		 * @param \WP_User $user The user object.
1300
		 */
1301
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1302
1303
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1304
			/**
1305
			 * Verifying of the previously generated secret has failed.
1306
			 *
1307
			 * @since 7.5.0
1308
			 *
1309
			 * @param string    $action  The type of secret to verify.
1310
			 * @param \WP_User  $user The user object.
1311
			 * @param \WP_Error $error The error object.
1312
			 */
1313
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1314
1315
			return $error;
1316
		};
1317
1318
		$stored_secrets = $this->get_secrets( $action, $user_id );
1319
		$this->delete_secrets( $action, $user_id );
1320
1321
		$error = null;
1322
		if ( empty( $secret_1 ) ) {
1323
			$error = $return_error(
1324
				new \WP_Error(
1325
					'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...
1326
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1327
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1328
					400
1329
				)
1330
			);
1331
		} elseif ( ! is_string( $secret_1 ) ) {
1332
			$error = $return_error(
1333
				new \WP_Error(
1334
					'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...
1335
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1336
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1337
					400
1338
				)
1339
			);
1340
		} elseif ( empty( $user_id ) ) {
1341
			// $user_id is passed around during registration as "state".
1342
			$error = $return_error(
1343
				new \WP_Error(
1344
					'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...
1345
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1346
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1347
					400
1348
				)
1349
			);
1350
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1351
			$error = $return_error(
1352
				new \WP_Error(
1353
					'state_malformed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'state_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...
1354
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1355
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1356
					400
1357
				)
1358
			);
1359
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1360
			$error = $return_error(
1361
				new \WP_Error(
1362
					'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...
1363
					__( 'Verification secrets not found', 'jetpack' ),
1364
					400
1365
				)
1366
			);
1367
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1368
			$error = $return_error(
1369
				new \WP_Error(
1370
					'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...
1371
					__( 'Verification took too long', 'jetpack' ),
1372
					400
1373
				)
1374
			);
1375
		} elseif ( ! $stored_secrets ) {
1376
			$error = $return_error(
1377
				new \WP_Error(
1378
					'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...
1379
					__( 'Verification secrets are empty', 'jetpack' ),
1380
					400
1381
				)
1382
			);
1383
		} elseif ( is_wp_error( $stored_secrets ) ) {
1384
			$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...
1385
			$error = $return_error( $stored_secrets );
1386
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1387
			$error = $return_error(
1388
				new \WP_Error(
1389
					'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...
1390
					__( 'Verification secrets are incomplete', 'jetpack' ),
1391
					400
1392
				)
1393
			);
1394
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1395
			$error = $return_error(
1396
				new \WP_Error(
1397
					'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...
1398
					__( 'Secret mismatch', 'jetpack' ),
1399
					400
1400
				)
1401
			);
1402
		}
1403
1404
		// Something went wrong during the checks, returning the error.
1405
		if ( ! empty( $error ) ) {
1406
			return $error;
1407
		}
1408
1409
		/**
1410
		 * We've succeeded at verifying the previously generated secret.
1411
		 *
1412
		 * @since 7.5.0
1413
		 *
1414
		 * @param string   $action The type of secret to verify.
1415
		 * @param \WP_User $user The user object.
1416
		 */
1417
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1418
1419
		return $stored_secrets['secret_2'];
1420
	}
1421
1422
	/**
1423
	 * Responds to a WordPress.com call to authorize the current user.
1424
	 * Should be changed to protected.
1425
	 */
1426
	public function handle_authorization() {
1427
1428
	}
1429
1430
	/**
1431
	 * Obtains the auth token.
1432
	 *
1433
	 * @param array $data The request data.
1434
	 * @return object|\WP_Error Returns the auth token on success.
1435
	 *                          Returns a \WP_Error on failure.
1436
	 */
1437
	public function get_token( $data ) {
1438
		$roles = new Roles();
1439
		$role  = $roles->translate_current_user_to_role();
1440
1441
		if ( ! $role ) {
1442
			return new \WP_Error( 'role', __( 'An administrator for this blog must set up the Jetpack connection.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'role'.

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...
1443
		}
1444
1445
		$client_secret = $this->get_access_token();
1446
		if ( ! $client_secret ) {
1447
			return new \WP_Error( 'client_secret', __( 'You need to register your Jetpack before connecting it.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'client_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...
1448
		}
1449
1450
		/**
1451
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1452
		 * data processing.
1453
		 *
1454
		 * @since 8.0.0
1455
		 *
1456
		 * @param string $redirect_url Defaults to the site admin URL.
1457
		 */
1458
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1459
1460
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1461
1462
		/**
1463
		* Filter the URL to redirect the user back to when the authentication process
1464
		* is complete.
1465
		*
1466
		* @since 8.0.0
1467
		*
1468
		* @param string $redirect_url Defaults to the site URL.
1469
		*/
1470
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1471
1472
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1473
			? $data['redirect_uri']
1474
			: add_query_arg(
1475
				array(
1476
					'action'   => 'authorize',
1477
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1478
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1479
				),
1480
				esc_url( $processing_url )
1481
			);
1482
1483
		/**
1484
		 * Filters the token request data.
1485
		 *
1486
		 * @since 8.0.0
1487
		 *
1488
		 * @param Array $request_data request data.
1489
		 */
1490
		$body = apply_filters(
1491
			'jetpack_token_request_body',
1492
			array(
1493
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1494
				'client_secret' => $client_secret->secret,
1495
				'grant_type'    => 'authorization_code',
1496
				'code'          => $data['code'],
1497
				'redirect_uri'  => $redirect_uri,
1498
			)
1499
		);
1500
1501
		$args = array(
1502
			'method'  => 'POST',
1503
			'body'    => $body,
1504
			'headers' => array(
1505
				'Accept' => 'application/json',
1506
			),
1507
		);
1508
1509
		$response = Client::_wp_remote_request( Utils::fix_url_for_bad_hosts( $this->api_url( 'token' ) ), $args );
1510
1511
		if ( is_wp_error( $response ) ) {
1512
			return new \WP_Error( 'token_http_request_failed', $response->get_error_message() );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_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...
1513
		}
1514
1515
		$code   = wp_remote_retrieve_response_code( $response );
1516
		$entity = wp_remote_retrieve_body( $response );
1517
1518
		if ( $entity ) {
1519
			$json = json_decode( $entity );
1520
		} else {
1521
			$json = false;
1522
		}
1523
1524
		if ( 200 !== $code || ! empty( $json->error ) ) {
1525
			if ( empty( $json->error ) ) {
1526
				return new \WP_Error( 'unknown', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown'.

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...
1527
			}
1528
1529
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1530
1531
			return new \WP_Error( (string) $json->error, $error_description, $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with (string) $json->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...
1532
		}
1533
1534
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1535
			return new \WP_Error( 'access_token', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'access_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...
1536
		}
1537
1538
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1539
			return new \WP_Error( 'token_type', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_type'.

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...
1540
		}
1541
1542
		if ( empty( $json->scope ) ) {
1543
			return new \WP_Error( 'scope', 'No Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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
		@list( $role, $hmac ) = explode( ':', $json->scope );
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...
1547
		if ( empty( $role ) || empty( $hmac ) ) {
1548
			return new \WP_Error( 'scope', 'Malformed Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1549
		}
1550
1551
		if ( $this->sign_role( $role ) !== $json->scope ) {
1552
			return new \WP_Error( 'scope', 'Invalid Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1553
		}
1554
1555
		$cap = $roles->translate_role_to_cap( $role );
1556
		if ( ! $cap ) {
1557
			return new \WP_Error( 'scope', 'No Cap', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1558
		}
1559
1560
		if ( ! current_user_can( $cap ) ) {
1561
			return new \WP_Error( 'scope', 'current_user_cannot', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1562
		}
1563
1564
		/**
1565
		 * Fires after user has successfully received an auth token.
1566
		 *
1567
		 * @since 3.9.0
1568
		 */
1569
		do_action( 'jetpack_user_authorized' );
1570
1571
		return (string) $json->access_token;
1572
	}
1573
1574
	/**
1575
	 * Builds a URL to the Jetpack connection auth page.
1576
	 *
1577
	 * @param WP_User $user (optional) defaults to the current logged in user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user not be WP_User|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...
1578
	 * @param String  $redirect (optional) a redirect URL to use instead of the default.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $redirect not be string|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...
1579
	 * @return string Connect URL.
1580
	 */
1581
	public function get_authorization_url( $user = null, $redirect = null ) {
1582
1583
		if ( empty( $user ) ) {
1584
			$user = wp_get_current_user();
1585
		}
1586
1587
		$roles       = new Roles();
1588
		$role        = $roles->translate_user_to_role( $user );
1589
		$signed_role = $this->sign_role( $role );
1590
1591
		/**
1592
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1593
		 * data processing.
1594
		 *
1595
		 * @since 8.0.0
1596
		 *
1597
		 * @param string $redirect_url Defaults to the site admin URL.
1598
		 */
1599
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1600
1601
		/**
1602
		 * Filter the URL to redirect the user back to when the authorization process
1603
		 * is complete.
1604
		 *
1605
		 * @since 8.0.0
1606
		 *
1607
		 * @param string $redirect_url Defaults to the site URL.
1608
		 */
1609
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1610
1611
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1612
1613
		/**
1614
		 * Filter the type of authorization.
1615
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1616
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1617
		 *
1618
		 * @since 4.3.3
1619
		 *
1620
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1621
		 */
1622
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1623
1624
		/**
1625
		 * Filters the user connection request data for additional property addition.
1626
		 *
1627
		 * @since 8.0.0
1628
		 *
1629
		 * @param Array $request_data request data.
1630
		 */
1631
		$body = apply_filters(
1632
			'jetpack_connect_request_body',
1633
			array(
1634
				'response_type' => 'code',
1635
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1636
				'redirect_uri'  => add_query_arg(
1637
					array(
1638
						'action'   => 'authorize',
1639
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1640
						'redirect' => rawurlencode( $redirect ),
1641
					),
1642
					esc_url( $processing_url )
1643
				),
1644
				'state'         => $user->ID,
1645
				'scope'         => $signed_role,
1646
				'user_email'    => $user->user_email,
1647
				'user_login'    => $user->user_login,
1648
				'is_active'     => $this->is_active(),
1649
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1650
				'auth_type'     => $auth_type,
1651
				'secret'        => $secrets['secret_1'],
1652
				'blogname'      => get_option( 'blogname' ),
1653
				'site_url'      => site_url(),
1654
				'home_url'      => home_url(),
1655
				'site_icon'     => get_site_icon_url(),
1656
				'site_lang'     => get_locale(),
1657
				'site_created'  => $this->get_assumed_site_creation_date(),
1658
			)
1659
		);
1660
1661
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1662
1663
		$api_url = $this->api_url( 'authorize' );
1664
1665
		return add_query_arg( $body, $api_url );
1666
	}
1667
1668
	/**
1669
	 * Authorizes the user by obtaining and storing the user token.
1670
	 *
1671
	 * @param array $data The request data.
1672
	 * @return string|\WP_Error Returns a string on success.
1673
	 *                          Returns a \WP_Error on failure.
1674
	 */
1675
	public function authorize( $data = array() ) {
1676
		/**
1677
		 * Action fired when user authorization starts.
1678
		 *
1679
		 * @since 8.0.0
1680
		 */
1681
		do_action( 'jetpack_authorize_starting' );
1682
1683
		$roles = new Roles();
1684
		$role  = $roles->translate_current_user_to_role();
1685
1686
		if ( ! $role ) {
1687
			return new \WP_Error( 'no_role', 'Invalid request.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_role'.

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...
1688
		}
1689
1690
		$cap = $roles->translate_role_to_cap( $role );
1691
		if ( ! $cap ) {
1692
			return new \WP_Error( 'no_cap', 'Invalid request.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_cap'.

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...
1693
		}
1694
1695
		if ( ! empty( $data['error'] ) ) {
1696
			return new \WP_Error( $data['error'], 'Error included in the request.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $data['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...
1697
		}
1698
1699
		if ( ! isset( $data['state'] ) ) {
1700
			return new \WP_Error( 'no_state', 'Request must include state.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_state'.

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...
1701
		}
1702
1703
		if ( ! ctype_digit( $data['state'] ) ) {
1704
			return new \WP_Error( $data['error'], 'State must be an integer.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $data['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...
1705
		}
1706
1707
		$current_user_id = get_current_user_id();
1708
		if ( $current_user_id !== (int) $data['state'] ) {
1709
			return new \WP_Error( 'wrong_state', 'State does not match current user.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wrong_state'.

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...
1710
		}
1711
1712
		if ( empty( $data['code'] ) ) {
1713
			return new \WP_Error( 'no_code', 'Request must include an authorization code.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_code'.

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...
1714
		}
1715
1716
		$token = $this->get_token( $data );
1717
1718 View Code Duplication
		if ( is_wp_error( $token ) ) {
1719
			$code = $token->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

Loading history...
1720
			if ( empty( $code ) ) {
1721
				$code = 'invalid_token';
1722
			}
1723
			return new \WP_Error( $code, $token->get_error_message(), 400 );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

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

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

Loading history...
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $code.

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...
1724
		}
1725
1726
		if ( ! $token ) {
1727
			return new \WP_Error( 'no_token', 'Error generating token.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_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...
1728
		}
1729
1730
		$is_master_user = ! $this->is_active();
1731
1732
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
1733
1734
		if ( ! $is_master_user ) {
1735
			/**
1736
			 * Action fired when a secondary user has been authorized.
1737
			 *
1738
			 * @since 8.0.0
1739
			 */
1740
			do_action( 'jetpack_authorize_ending_linked' );
1741
			return 'linked';
1742
		}
1743
1744
		/**
1745
		 * Action fired when the master user has been authorized.
1746
		 *
1747
		 * @since 8.0.0
1748
		 *
1749
		 * @param array $data The request data.
1750
		 */
1751
		do_action( 'jetpack_authorize_ending_authorized', $data );
1752
1753
		return 'authorized';
1754
	}
1755
1756
	/**
1757
	 * Disconnects from the Jetpack servers.
1758
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1759
	 */
1760
	public function disconnect_site() {
1761
1762
	}
1763
1764
	/**
1765
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1766
	 *
1767
	 * @param string $text The string to hash.
1768
	 * @return string
1769
	 */
1770
	public function sha1_base64( $text ) {
1771
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1772
	}
1773
1774
	/**
1775
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1776
	 *
1777
	 * @param string $domain The domain to check.
1778
	 *
1779
	 * @return bool|WP_Error
1780
	 */
1781
	public function is_usable_domain( $domain ) {
1782
1783
		// If it's empty, just fail out.
1784
		if ( ! $domain ) {
1785
			return new \WP_Error(
1786
				'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...
1787
				/* translators: %1$s is a domain name. */
1788
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1789
			);
1790
		}
1791
1792
		/**
1793
		 * Skips the usuable domain check when connecting a site.
1794
		 *
1795
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1796
		 *
1797
		 * @since 4.1.0
1798
		 *
1799
		 * @param bool If the check should be skipped. Default false.
1800
		 */
1801
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1802
			return true;
1803
		}
1804
1805
		// None of the explicit localhosts.
1806
		$forbidden_domains = array(
1807
			'wordpress.com',
1808
			'localhost',
1809
			'localhost.localdomain',
1810
			'127.0.0.1',
1811
			'local.wordpress.test',         // VVV pattern.
1812
			'local.wordpress-trunk.test',   // VVV pattern.
1813
			'src.wordpress-develop.test',   // VVV pattern.
1814
			'build.wordpress-develop.test', // VVV pattern.
1815
		);
1816 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1817
			return new \WP_Error(
1818
				'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...
1819
				sprintf(
1820
					/* translators: %1$s is a domain name. */
1821
					__(
1822
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1823
						'jetpack'
1824
					),
1825
					$domain
1826
				)
1827
			);
1828
		}
1829
1830
		// No .test or .local domains.
1831 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1832
			return new \WP_Error(
1833
				'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...
1834
				sprintf(
1835
					/* translators: %1$s is a domain name. */
1836
					__(
1837
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1838
						'jetpack'
1839
					),
1840
					$domain
1841
				)
1842
			);
1843
		}
1844
1845
		// No WPCOM subdomains.
1846 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1847
			return new \WP_Error(
1848
				'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...
1849
				sprintf(
1850
					/* translators: %1$s is a domain name. */
1851
					__(
1852
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1853
						'jetpack'
1854
					),
1855
					$domain
1856
				)
1857
			);
1858
		}
1859
1860
		// If PHP was compiled without support for the Filter module (very edge case).
1861
		if ( ! function_exists( 'filter_var' ) ) {
1862
			// Just pass back true for now, and let wpcom sort it out.
1863
			return true;
1864
		}
1865
1866
		return true;
1867
	}
1868
1869
	/**
1870
	 * Gets the requested token.
1871
	 *
1872
	 * Tokens are one of two types:
1873
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
1874
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
1875
	 *    are not associated with a user account. They represent the site's connection with
1876
	 *    the Jetpack servers.
1877
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
1878
	 *
1879
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
1880
	 * token, and $private is a secret that should never be displayed anywhere or sent
1881
	 * over the network; it's used only for signing things.
1882
	 *
1883
	 * Blog Tokens can be "Normal" or "Special".
1884
	 * * Normal: The result of a normal connection flow. They look like
1885
	 *   "{$random_string_1}.{$random_string_2}"
1886
	 *   That is, $token_key and $private are both random strings.
1887
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
1888
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
1889
	 *   constant (rare).
1890
	 * * Special: A connection token for sites that have gone through an alternative
1891
	 *   connection flow. They look like:
1892
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
1893
	 *   That is, $private is a random string and $token_key has a special structure with
1894
	 *   lots of semicolons.
1895
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
1896
	 *   JETPACK_BLOG_TOKEN constant.
1897
	 *
1898
	 * In particular, note that Normal Blog Tokens never start with ";" and that
1899
	 * Special Blog Tokens always do.
1900
	 *
1901
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
1902
	 * order:
1903
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
1904
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
1905
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
1906
	 *
1907
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1908
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1909
	 * @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.
1910
	 *
1911
	 * @return object|false
1912
	 */
1913
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1914
		$possible_special_tokens = array();
1915
		$possible_normal_tokens  = array();
1916
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
1917
1918
		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...
1919
			if ( ! $user_tokens ) {
1920
				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...
1921
			}
1922
			if ( self::JETPACK_MASTER_USER === $user_id ) {
1923
				$user_id = \Jetpack_Options::get_option( 'master_user' );
1924
				if ( ! $user_id ) {
1925
					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...
1926
				}
1927
			}
1928
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
1929
				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...
1930
			}
1931
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
1932 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
1933
				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...
1934
			}
1935 View Code Duplication
			if ( $user_token_chunks[2] !== (string) $user_id ) {
1936
				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...
1937
			}
1938
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
1939
		} else {
1940
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
1941
			if ( $stored_blog_token ) {
1942
				$possible_normal_tokens[] = $stored_blog_token;
1943
			}
1944
1945
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
1946
1947
			if ( $defined_tokens_string ) {
1948
				$defined_tokens = explode( ',', $defined_tokens_string );
1949
				foreach ( $defined_tokens as $defined_token ) {
1950
					if ( ';' === $defined_token[0] ) {
1951
						$possible_special_tokens[] = $defined_token;
1952
					} else {
1953
						$possible_normal_tokens[] = $defined_token;
1954
					}
1955
				}
1956
			}
1957
		}
1958
1959
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1960
			$possible_tokens = $possible_normal_tokens;
1961
		} else {
1962
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
1963
		}
1964
1965
		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...
1966
			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...
1967
		}
1968
1969
		$valid_token = false;
1970
1971
		if ( false === $token_key ) {
1972
			// Use first token.
1973
			$valid_token = $possible_tokens[0];
1974
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1975
			// Use first normal token.
1976
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
1977
		} else {
1978
			// Use the token matching $token_key or false if none.
1979
			// Ensure we check the full key.
1980
			$token_check = rtrim( $token_key, '.' ) . '.';
1981
1982
			foreach ( $possible_tokens as $possible_token ) {
1983
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
1984
					$valid_token = $possible_token;
1985
					break;
1986
				}
1987
			}
1988
		}
1989
1990
		if ( ! $valid_token ) {
1991
			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...
1992
		}
1993
1994
		return (object) array(
1995
			'secret'           => $valid_token,
1996
			'external_user_id' => (int) $user_id,
1997
		);
1998
	}
1999
2000
	/**
2001
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2002
	 * since it is passed by reference to various methods.
2003
	 * Capture it here so we can verify the signature later.
2004
	 *
2005
	 * @param Array $methods an array of available XMLRPC methods.
2006
	 * @return Array the same array, since this method doesn't add or remove anything.
2007
	 */
2008
	public function xmlrpc_methods( $methods ) {
2009
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
2010
		return $methods;
2011
	}
2012
2013
	/**
2014
	 * Resets the raw post data parameter for testing purposes.
2015
	 */
2016
	public function reset_raw_post_data() {
2017
		$this->raw_post_data = null;
2018
	}
2019
2020
	/**
2021
	 * Registering an additional method.
2022
	 *
2023
	 * @param Array $methods an array of available XMLRPC methods.
2024
	 * @return Array the amended array in case the method is added.
2025
	 */
2026
	public function public_xmlrpc_methods( $methods ) {
2027
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2028
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2029
		}
2030
		return $methods;
2031
	}
2032
2033
	/**
2034
	 * Handles a getOptions XMLRPC method call.
2035
	 *
2036
	 * @param Array $args method call arguments.
2037
	 * @return an amended XMLRPC server options array.
2038
	 */
2039
	public function jetpack_get_options( $args ) {
2040
		global $wp_xmlrpc_server;
2041
2042
		$wp_xmlrpc_server->escape( $args );
2043
2044
		$username = $args[1];
2045
		$password = $args[2];
2046
2047
		$user = $wp_xmlrpc_server->login( $username, $password );
2048
		if ( ! $user ) {
2049
			return $wp_xmlrpc_server->error;
2050
		}
2051
2052
		$options   = array();
2053
		$user_data = $this->get_connected_user_data();
2054
		if ( is_array( $user_data ) ) {
2055
			$options['jetpack_user_id']         = array(
2056
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2057
				'readonly' => true,
2058
				'value'    => $user_data['ID'],
2059
			);
2060
			$options['jetpack_user_login']      = array(
2061
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2062
				'readonly' => true,
2063
				'value'    => $user_data['login'],
2064
			);
2065
			$options['jetpack_user_email']      = array(
2066
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2067
				'readonly' => true,
2068
				'value'    => $user_data['email'],
2069
			);
2070
			$options['jetpack_user_site_count'] = array(
2071
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2072
				'readonly' => true,
2073
				'value'    => $user_data['site_count'],
2074
			);
2075
		}
2076
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2077
		$args                           = stripslashes_deep( $args );
2078
		return $wp_xmlrpc_server->wp_getOptions( $args );
2079
	}
2080
2081
	/**
2082
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2083
	 *
2084
	 * @param Array $options standard Core options.
2085
	 * @return Array amended options.
2086
	 */
2087
	public function xmlrpc_options( $options ) {
2088
		$jetpack_client_id = false;
2089
		if ( $this->is_active() ) {
2090
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2091
		}
2092
		$options['jetpack_version'] = array(
2093
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2094
			'readonly' => true,
2095
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2096
		);
2097
2098
		$options['jetpack_client_id'] = array(
2099
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2100
			'readonly' => true,
2101
			'value'    => $jetpack_client_id,
2102
		);
2103
		return $options;
2104
	}
2105
2106
	/**
2107
	 * Resets the saved authentication state in between testing requests.
2108
	 */
2109
	public function reset_saved_auth_state() {
2110
		$this->xmlrpc_verification = null;
2111
	}
2112
2113
	/**
2114
	 * Sign a user role with the master access token.
2115
	 * If not specified, will default to the current user.
2116
	 *
2117
	 * @access public
2118
	 *
2119
	 * @param string $role    User role.
2120
	 * @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...
2121
	 * @return string Signed user role.
2122
	 */
2123
	public function sign_role( $role, $user_id = null ) {
2124
		if ( empty( $user_id ) ) {
2125
			$user_id = (int) get_current_user_id();
2126
		}
2127
2128
		if ( ! $user_id ) {
2129
			return false;
2130
		}
2131
2132
		$token = $this->get_access_token();
2133
		if ( ! $token || is_wp_error( $token ) ) {
2134
			return false;
2135
		}
2136
2137
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2138
	}
2139
}
2140