Completed
Push — add/mailchimp-groups-merge-fie... ( c88508...48f203 )
by
unknown
07:48 queued 01:05
created

Manager::remove_non_jetpack_xmlrpc_methods()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 11
rs 9.9
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\Tracking;
12
13
/**
14
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
15
 * and Jetpack.
16
 */
17
class Manager {
18
19
	const SECRETS_MISSING        = 'secrets_missing';
20
	const SECRETS_EXPIRED        = 'secrets_expired';
21
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
22
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
23
	const JETPACK_MASTER_USER    = true;
24
25
	/**
26
	 * The procedure that should be run to generate secrets.
27
	 *
28
	 * @var Callable
29
	 */
30
	protected $secret_callable;
31
32
	/**
33
	 * A copy of the raw POST data for signature verification purposes.
34
	 *
35
	 * @var String
36
	 */
37
	protected $raw_post_data;
38
39
	/**
40
	 * Verification data needs to be stored to properly verify everything.
41
	 *
42
	 * @var Object
43
	 */
44
	private $xmlrpc_verification = null;
45
46
	/**
47
	 * Initializes required listeners. This is done separately from the constructors
48
	 * because some objects sometimes need to instantiate separate objects of this class.
49
	 *
50
	 * @todo Implement a proper nonce verification.
51
	 */
52
	public function init() {
53
		$this->setup_xmlrpc_handlers(
54
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
55
			$this->is_active(),
56
			$this->verify_xml_rpc_signature()
0 ignored issues
show
Bug introduced by
It seems like $this->verify_xml_rpc_signature() targeting Automattic\Jetpack\Conne...ify_xml_rpc_signature() can also be of type array; however, Automattic\Jetpack\Conne...setup_xmlrpc_handlers() does only seem to accept boolean, maybe add an additional type check?

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

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

An additional type check may prevent trouble.

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

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

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

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

Loading history...
78
	 */
79
	public function setup_xmlrpc_handlers(
80
		$request_params,
81
		$is_active,
82
		$is_signed,
83
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
84
	) {
85
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
86
87
		if (
88
			! isset( $request_params['for'] )
89
			|| 'jetpack' !== $request_params['for']
90
		) {
91
			return false;
92
		}
93
94
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
95
		if (
96
			isset( $request_params['jetpack'] )
97
			&& 'comms' === $request_params['jetpack']
98
		) {
99
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
100
				// Use the real constant here for WordPress' sake.
101
				define( 'XMLRPC_REQUEST', true );
102
			}
103
104
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
105
106
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
107
		}
108
109
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
110
			return false;
111
		}
112
		// Display errors can cause the XML to be not well formed.
113
		@ini_set( 'display_errors', false ); // phpcs:ignore
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
114
115
		if ( $xmlrpc_server ) {
116
			$this->xmlrpc_server = $xmlrpc_server;
0 ignored issues
show
Bug introduced by
The property xmlrpc_server does not exist. Did you maybe forget to declare it?

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
117
		} else {
118
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
119
		}
120
121
		$this->require_jetpack_authentication();
122
123
		if ( $is_active ) {
124
			// Hack to preserve $HTTP_RAW_POST_DATA.
125
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
126
127
			if ( $is_signed ) {
128
				// The actual API methods.
129
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
130
			} else {
131
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
132
				// active Jetpack connection, so that additional users can link their account.
133
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
134
			}
135
		} else {
136
			// The bootstrap API methods.
137
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
138
139
			if ( $is_signed ) {
140
				// The jetpack Provision method is available for blog-token-signed requests.
141
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
142
			} else {
143
				new XMLRPC_Connector( $this );
144
			}
145
		}
146
147
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
148
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
149
		return true;
150
	}
151
152
	/**
153
	 * Initializes the REST API connector on the init hook.
154
	 */
155
	public function initialize_rest_api_registration_connector() {
156
		new REST_Connector( $this );
157
	}
158
159
	/**
160
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
161
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
162
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
163
	 * which is accessible via a different URI. Most of the below is copied directly
164
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
165
	 *
166
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
167
	 */
168
	public function alternate_xmlrpc() {
169
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
170
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
171
		global $HTTP_RAW_POST_DATA;
172
173
		// Some browser-embedded clients send cookies. We don't want them.
174
		$_COOKIE = array();
175
176
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
177
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
178
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
179
		}
180
181
		// phpcs:enable
182
183
		include_once ABSPATH . 'wp-admin/includes/admin.php';
184
		include_once ABSPATH . WPINC . '/class-IXR.php';
185
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
186
187
		/**
188
		 * Filters the class used for handling XML-RPC requests.
189
		 *
190
		 * @since 3.1.0
191
		 *
192
		 * @param string $class The name of the XML-RPC server class.
193
		 */
194
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
195
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
196
197
		// Fire off the request.
198
		nocache_headers();
199
		$wp_xmlrpc_server->serve_request();
200
201
		exit;
202
	}
203
204
	/**
205
	 * Removes all XML-RPC methods that are not `jetpack.*`.
206
	 * Only used in our alternate XML-RPC endpoint, where we want to
207
	 * ensure that Core and other plugins' methods are not exposed.
208
	 *
209
	 * @param array $methods a list of registered WordPress XMLRPC methods.
210
	 * @return array filtered $methods
211
	 */
212
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
213
		$jetpack_methods = array();
214
215
		foreach ( $methods as $method => $callback ) {
216
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
217
				$jetpack_methods[ $method ] = $callback;
218
			}
219
		}
220
221
		return $jetpack_methods;
222
	}
223
224
	/**
225
	 * Removes all other authentication methods not to allow other
226
	 * methods to validate unauthenticated requests.
227
	 */
228
	public function require_jetpack_authentication() {
229
		// Don't let anyone authenticate.
230
		$_COOKIE = array();
231
		remove_all_filters( 'authenticate' );
232
		remove_all_actions( 'wp_login_failed' );
233
234
		if ( $this->is_active() ) {
235
			// Allow Jetpack authentication.
236
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
237
		}
238
	}
239
240
	/**
241
	 * Authenticates XML-RPC and other requests from the Jetpack Server
242
	 *
243
	 * @param WP_User|Mixed $user user object if authenticated.
244
	 * @param String        $username username.
245
	 * @param String        $password password string.
246
	 * @return WP_User|Mixed authenticated user or error.
247
	 */
248
	public function authenticate_jetpack( $user, $username, $password ) {
249
		if ( is_a( $user, '\\WP_User' ) ) {
250
			return $user;
251
		}
252
253
		$token_details = $this->verify_xml_rpc_signature();
254
255
		if ( ! $token_details ) {
256
			return $user;
257
		}
258
259
		if ( 'user' !== $token_details['type'] ) {
260
			return $user;
261
		}
262
263
		if ( ! $token_details['user_id'] ) {
264
			return $user;
265
		}
266
267
		nocache_headers();
268
269
		return new \WP_User( $token_details['user_id'] );
270
	}
271
272
	/**
273
	 * Verifies the signature of the current request.
274
	 *
275
	 * @return false|array
276
	 */
277
	public function verify_xml_rpc_signature() {
278
		if ( is_null( $this->xmlrpc_verification ) ) {
279
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
280
281
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
282
				/**
283
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
284
				 *
285
				 * Error codes:
286
				 * - malformed_token
287
				 * - malformed_user_id
288
				 * - unknown_token
289
				 * - could_not_sign
290
				 * - invalid_nonce
291
				 * - signature_mismatch
292
				 *
293
				 * @since 7.5.0
294
				 *
295
				 * @param WP_Error $signature_verification_error The verification error
296
				 */
297
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
298
			}
299
		}
300
301
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
302
	}
303
304
	/**
305
	 * Verifies the signature of the current request.
306
	 *
307
	 * This function has side effects and should not be used. Instead,
308
	 * use the memoized version `->verify_xml_rpc_signature()`.
309
	 *
310
	 * @internal
311
	 * @todo Refactor to use proper nonce verification.
312
	 */
313
	private function internal_verify_xml_rpc_signature() {
314
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
315
		// It's not for us.
316
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
317
			return false;
318
		}
319
320
		$signature_details = array(
321
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
322
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
323
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
324
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
325
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
326
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
327
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
328
		);
329
330
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
331
		@list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
332
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
333
334
		if (
335
			empty( $token_key )
336
		||
337
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
338
		) {
339
			return new \WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_token'.

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

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

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

Loading history...
340
		}
341
342
		if ( '0' === $user_id ) {
343
			$token_type = 'blog';
344
			$user_id    = 0;
345
		} else {
346
			$token_type = 'user';
347
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
348
				return new \WP_Error(
349
					'malformed_user_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_user_id'.

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

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

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

Loading history...
350
					'Malformed user_id in request',
351
					compact( 'signature_details' )
352
				);
353
			}
354
			$user_id = (int) $user_id;
355
356
			$user = new \WP_User( $user_id );
357
			if ( ! $user || ! $user->exists() ) {
358
				return new \WP_Error(
359
					'unknown_user',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_user'.

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

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

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

Loading history...
360
					sprintf( 'User %d does not exist', $user_id ),
361
					compact( 'signature_details' )
362
				);
363
			}
364
		}
365
366
		$token = $this->get_access_token( $user_id, $token_key, false );
367
		if ( is_wp_error( $token ) ) {
368
			$token->add_data( compact( 'signature_details' ) );
369
			return $token;
370
		} elseif ( ! $token ) {
371
			return new \WP_Error(
372
				'unknown_token',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
373
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
374
				compact( 'signature_details' )
375
			);
376
		}
377
378
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
379
		// phpcs:disable WordPress.Security.NonceVerification.Missing
380
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
381
			$post_data   = $_POST;
382
			$file_hashes = array();
383
			foreach ( $post_data as $post_data_key => $post_data_value ) {
384
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
385
					continue;
386
				}
387
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
388
				$file_hashes[ $post_data_key ] = $post_data_value;
389
			}
390
391
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
392
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
393
				$post_data[ $post_data_key ] = $post_data_value;
394
			}
395
396
			ksort( $post_data );
397
398
			$body = http_build_query( stripslashes_deep( $post_data ) );
399
		} elseif ( is_null( $this->raw_post_data ) ) {
400
			$body = file_get_contents( 'php://input' );
401
		} else {
402
			$body = null;
403
		}
404
		// phpcs:enable
405
406
		$signature = $jetpack_signature->sign_current_request(
407
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
408
		);
409
410
		$signature_details['url'] = $jetpack_signature->current_request_url;
411
412
		if ( ! $signature ) {
413
			return new \WP_Error(
414
				'could_not_sign',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'could_not_sign'.

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

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

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

Loading history...
415
				'Unknown signature error',
416
				compact( 'signature_details' )
417
			);
418
		} elseif ( is_wp_error( $signature ) ) {
419
			return $signature;
420
		}
421
422
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
423
		$timestamp = (int) $_GET['timestamp'];
424
		$nonce     = stripslashes( (string) $_GET['nonce'] );
425
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
426
427
		// Use up the nonce regardless of whether the signature matches.
428
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
429
			return new \WP_Error(
430
				'invalid_nonce',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

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

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

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

Loading history...
431
				'Could not add nonce',
432
				compact( 'signature_details' )
433
			);
434
		}
435
436
		// Be careful about what you do with this debugging data.
437
		// If a malicious requester has access to the expected signature,
438
		// bad things might be possible.
439
		$signature_details['expected'] = $signature;
440
441
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
442
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
443
			return new \WP_Error(
444
				'signature_mismatch',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'signature_mismatch'.

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

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

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

Loading history...
445
				'Signature mismatch',
446
				compact( 'signature_details' )
447
			);
448
		}
449
450
		/**
451
		 * Action for additional token checking.
452
		 *
453
		 * @since 7.7.0
454
		 *
455
		 * @param Array $post_data request data.
456
		 * @param Array $token_data token data.
457
		 */
458
		return apply_filters(
459
			'jetpack_signature_check_token',
460
			array(
461
				'type'      => $token_type,
462
				'token_key' => $token_key,
463
				'user_id'   => $token->external_user_id,
464
			),
465
			$token,
466
			$this->raw_post_data
467
		);
468
	}
469
470
	/**
471
	 * Returns true if the current site is connected to WordPress.com.
472
	 *
473
	 * @return Boolean is the site connected?
474
	 */
475
	public function is_active() {
476
		return (bool) $this->get_access_token( self::JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
self::JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
477
	}
478
479
	/**
480
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
481
	 *
482
	 * @access public
483
	 *
484
	 * @return bool
485
	 */
486
	public function is_registered() {
487
		$blog_id   = \Jetpack_Options::get_option( 'id' );
488
		$has_token = $this->is_active();
489
		return $blog_id && $has_token;
490
	}
491
492
	/**
493
	 * Checks to see if the connection owner of the site is missing.
494
	 *
495
	 * @return bool
496
	 */
497
	public function is_missing_connection_owner() {
498
		$connection_owner = $this->get_connection_owner_id();
499
		if ( ! get_user_by( 'id', $connection_owner ) ) {
500
			return true;
501
		}
502
503
		return false;
504
	}
505
506
	/**
507
	 * Returns true if the user with the specified identifier is connected to
508
	 * WordPress.com.
509
	 *
510
	 * @param Integer|Boolean $user_id the user identifier.
511
	 * @return Boolean is the user connected?
512
	 */
513
	public function is_user_connected( $user_id = false ) {
514
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
515
		if ( ! $user_id ) {
516
			return false;
517
		}
518
519
		return (bool) $this->get_access_token( $user_id );
520
	}
521
522
	/**
523
	 * Returns the local user ID of the connection owner.
524
	 *
525
	 * @return string|int Returns the ID of the connection owner or False if no connection owner found.
526
	 */
527 View Code Duplication
	public function get_connection_owner_id() {
528
		$user_token       = $this->get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
529
		$connection_owner = false;
530
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
531
			$connection_owner = $user_token->external_user_id;
532
		}
533
534
		return $connection_owner;
535
	}
536
537
	/**
538
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
539
	 * Able to select by specific capability.
540
	 *
541
	 * @param string $capability The capability of the user.
542
	 * @return array Array of WP_User objects if found.
543
	 */
544
	public function get_connected_users( $capability = 'any' ) {
545
		$connected_users    = array();
546
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
547
548
		if ( ! empty( $connected_user_ids ) ) {
549
			foreach ( $connected_user_ids as $id ) {
550
				// Check for capability.
551
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
552
					continue;
553
				}
554
555
				$connected_users[] = get_userdata( $id );
556
			}
557
		}
558
559
		return $connected_users;
560
	}
561
562
	/**
563
	 * Get the wpcom user data of the current|specified connected user.
564
	 *
565
	 * @todo Refactor to properly load the XMLRPC client independently.
566
	 *
567
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

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

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
572
			$user_id = get_current_user_id();
573
		}
574
575
		$transient_key    = "jetpack_connected_user_data_$user_id";
576
		$cached_user_data = get_transient( $transient_key );
577
578
		if ( $cached_user_data ) {
579
			return $cached_user_data;
580
		}
581
582
		$xml = new \Jetpack_IXR_Client(
583
			array(
584
				'user_id' => $user_id,
585
			)
586
		);
587
		$xml->query( 'wpcom.getUser' );
588
		if ( ! $xml->isError() ) {
589
			$user_data = $xml->getResponse();
590
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
591
			return $user_data;
592
		}
593
594
		return false;
595
	}
596
597
	/**
598
	 * Returns a user object of the connection owner.
599
	 *
600
	 * @return object|false False if no connection owner found.
601
	 */
602 View Code Duplication
	public function get_connection_owner() {
603
		$user_token = $this->get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
604
605
		$connection_owner = false;
606
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
607
			$connection_owner = get_userdata( $user_token->external_user_id );
608
		}
609
610
		return $connection_owner;
611
	}
612
613
	/**
614
	 * Returns true if the provided user is the Jetpack connection owner.
615
	 * If user ID is not specified, the current user will be used.
616
	 *
617
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
618
	 * @return Boolean True the user the connection owner, false otherwise.
619
	 */
620 View Code Duplication
	public function is_connection_owner( $user_id = false ) {
621
		if ( ! $user_id ) {
622
			$user_id = get_current_user_id();
623
		}
624
625
		$user_token = $this->get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
626
627
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
628
	}
629
630
	/**
631
	 * Unlinks the current user from the linked WordPress.com user.
632
	 *
633
	 * @access public
634
	 * @static
635
	 *
636
	 * @todo Refactor to properly load the XMLRPC client independently.
637
	 *
638
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
639
	 * @return Boolean Whether the disconnection of the user was successful.
640
	 */
641
	public static function disconnect_user( $user_id = null ) {
642
		$tokens = \Jetpack_Options::get_option( 'user_tokens' );
643
		if ( ! $tokens ) {
644
			return false;
645
		}
646
647
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
648
649
		if ( \Jetpack_Options::get_option( 'master_user' ) === $user_id ) {
650
			return false;
651
		}
652
653
		if ( ! isset( $tokens[ $user_id ] ) ) {
654
			return false;
655
		}
656
657
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
658
		$xml->query( 'jetpack.unlink_user', $user_id );
659
660
		unset( $tokens[ $user_id ] );
661
662
		\Jetpack_Options::update_option( 'user_tokens', $tokens );
663
664
		/**
665
		 * Fires after the current user has been unlinked from WordPress.com.
666
		 *
667
		 * @since 4.1.0
668
		 *
669
		 * @param int $user_id The current user's ID.
670
		 */
671
		do_action( 'jetpack_unlinked_user', $user_id );
672
673
		return true;
674
	}
675
676
	/**
677
	 * Returns the requested Jetpack API URL.
678
	 *
679
	 * @param String $relative_url the relative API path.
680
	 * @return String API URL.
681
	 */
682
	public function api_url( $relative_url ) {
683
		$api_base = Constants::get_constant( 'JETPACK__API_BASE' );
684
		$version  = Constants::get_constant( 'JETPACK__API_VERSION' );
685
686
		$api_base = $api_base ? $api_base : 'https://jetpack.wordpress.com/jetpack.';
687
		$version  = $version ? '/' . $version . '/' : '/1/';
688
689
		/**
690
		 * Filters the API URL that Jetpack uses for server communication.
691
		 *
692
		 * @since 8.0.0
693
		 *
694
		 * @param String $url the generated URL.
695
		 * @param String $relative_url the relative URL that was passed as an argument.
696
		 * @param String $api_base the API base string that is being used.
697
		 * @param String $version the version string that is being used.
698
		 */
699
		return apply_filters(
700
			'jetpack_api_url',
701
			rtrim( $api_base . $relative_url, '/\\' ) . $version,
702
			$relative_url,
703
			$api_base,
704
			$version
705
		);
706
	}
707
708
	/**
709
	 * Attempts Jetpack registration which sets up the site for connection. Should
710
	 * remain public because the call to action comes from the current site, not from
711
	 * WordPress.com.
712
	 *
713
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
714
	 * @return Integer zero on success, or a bitmask on failure.
715
	 */
716
	public function register( $api_endpoint = 'register' ) {
717
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
718
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
719
720
		if (
721
			empty( $secrets['secret_1'] ) ||
722
			empty( $secrets['secret_2'] ) ||
723
			empty( $secrets['exp'] )
724
		) {
725
			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...
726
		}
727
728
		// Better to try (and fail) to set a higher timeout than this system
729
		// supports than to have register fail for more users than it should.
730
		$timeout = $this->set_min_time_limit( 60 ) / 2;
731
732
		$gmt_offset = get_option( 'gmt_offset' );
733
		if ( ! $gmt_offset ) {
734
			$gmt_offset = 0;
735
		}
736
737
		$stats_options = get_option( 'stats_options' );
738
		$stats_id      = isset( $stats_options['blog_id'] )
739
			? $stats_options['blog_id']
740
			: null;
741
742
		/**
743
		 * Filters the request body for additional property addition.
744
		 *
745
		 * @since 7.7.0
746
		 *
747
		 * @param Array $post_data request data.
748
		 * @param Array $token_data token data.
749
		 */
750
		$body = apply_filters(
751
			'jetpack_register_request_body',
752
			array(
753
				'siteurl'         => site_url(),
754
				'home'            => home_url(),
755
				'gmt_offset'      => $gmt_offset,
756
				'timezone_string' => (string) get_option( 'timezone_string' ),
757
				'site_name'       => (string) get_option( 'blogname' ),
758
				'secret_1'        => $secrets['secret_1'],
759
				'secret_2'        => $secrets['secret_2'],
760
				'site_lang'       => get_locale(),
761
				'timeout'         => $timeout,
762
				'stats_id'        => $stats_id,
763
				'state'           => get_current_user_id(),
764
				'site_created'    => $this->get_assumed_site_creation_date(),
765
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
766
			)
767
		);
768
769
		$args = array(
770
			'method'  => 'POST',
771
			'body'    => $body,
772
			'headers' => array(
773
				'Accept' => 'application/json',
774
			),
775
			'timeout' => $timeout,
776
		);
777
778
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
779
780
		// TODO: fix URLs for bad hosts.
781
		$response = Client::_wp_remote_request(
782
			$this->api_url( $api_endpoint ),
783
			$args,
784
			true
785
		);
786
787
		// Make sure the response is valid and does not contain any Jetpack errors.
788
		$registration_details = $this->validate_remote_register_response( $response );
789
790
		if ( is_wp_error( $registration_details ) ) {
791
			return $registration_details;
792
		} elseif ( ! $registration_details ) {
793
			return new \WP_Error(
794
				'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...
795
				'Unknown error registering your Jetpack site.',
796
				wp_remote_retrieve_response_code( $response )
797
			);
798
		}
799
800
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
801
			return new \WP_Error(
802
				'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...
803
				'Unable to validate registration of your Jetpack site.',
804
				wp_remote_retrieve_response_code( $response )
805
			);
806
		}
807
808
		if ( isset( $registration_details->jetpack_public ) ) {
809
			$jetpack_public = (int) $registration_details->jetpack_public;
810
		} else {
811
			$jetpack_public = false;
812
		}
813
814
		\Jetpack_Options::update_options(
815
			array(
816
				'id'         => (int) $registration_details->jetpack_id,
817
				'blog_token' => (string) $registration_details->jetpack_secret,
818
				'public'     => $jetpack_public,
819
			)
820
		);
821
822
		/**
823
		 * Fires when a site is registered on WordPress.com.
824
		 *
825
		 * @since 3.7.0
826
		 *
827
		 * @param int $json->jetpack_id Jetpack Blog ID.
828
		 * @param string $json->jetpack_secret Jetpack Blog Token.
829
		 * @param int|bool $jetpack_public Is the site public.
830
		 */
831
		do_action(
832
			'jetpack_site_registered',
833
			$registration_details->jetpack_id,
834
			$registration_details->jetpack_secret,
835
			$jetpack_public
836
		);
837
838
		if ( isset( $registration_details->token ) ) {
839
			/**
840
			 * Fires when a user token is sent along with the registration data.
841
			 *
842
			 * @since 7.6.0
843
			 *
844
			 * @param object $token the administrator token for the newly registered site.
845
			 */
846
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
847
		}
848
849
		return true;
850
	}
851
852
	/**
853
	 * Takes the response from the Jetpack register new site endpoint and
854
	 * verifies it worked properly.
855
	 *
856
	 * @since 2.6
857
	 *
858
	 * @param Mixed $response the response object, or the error object.
859
	 * @return string|WP_Error A JSON object on success or Jetpack_Error on failures
860
	 **/
861
	protected function validate_remote_register_response( $response ) {
862
		if ( is_wp_error( $response ) ) {
863
			return new \WP_Error(
864
				'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...
865
				$response->get_error_message()
866
			);
867
		}
868
869
		$code   = wp_remote_retrieve_response_code( $response );
870
		$entity = wp_remote_retrieve_body( $response );
871
872
		if ( $entity ) {
873
			$registration_response = json_decode( $entity );
874
		} else {
875
			$registration_response = false;
876
		}
877
878
		$code_type = intval( $code / 100 );
879
		if ( 5 === $code_type ) {
880
			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...
881
		} elseif ( 408 === $code ) {
882
			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...
883
		} elseif ( ! empty( $registration_response->error ) ) {
884
			if (
885
				'xml_rpc-32700' === $registration_response->error
886
				&& ! function_exists( 'xml_parser_create' )
887
			) {
888
				$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' );
889
			} else {
890
				$error_description = isset( $registration_response->error_description )
891
					? (string) $registration_response->error_description
892
					: '';
893
			}
894
895
			return new \WP_Error(
896
				(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...
897
				$error_description,
898
				$code
899
			);
900
		} elseif ( 200 !== $code ) {
901
			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...
902
		}
903
904
		// Jetpack ID error block.
905
		if ( empty( $registration_response->jetpack_id ) ) {
906
			return new \WP_Error(
907
				'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...
908
				/* translators: %s is an error message string */
909
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
910
				$entity
911
			);
912
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
913
			return new \WP_Error(
914
				'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...
915
				/* translators: %s is an error message string */
916
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
917
				$entity
918
			);
919 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
920
			return new \WP_Error(
921
				'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...
922
				/* translators: %s is an error message string */
923
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
924
				$entity
925
			);
926
		}
927
928
		return $registration_response;
929
	}
930
931
	/**
932
	 * Adds a used nonce to a list of known nonces.
933
	 *
934
	 * @param int    $timestamp the current request timestamp.
935
	 * @param string $nonce the nonce value.
936
	 * @return bool whether the nonce is unique or not.
937
	 */
938
	public function add_nonce( $timestamp, $nonce ) {
939
		global $wpdb;
940
		static $nonces_used_this_request = array();
941
942
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
943
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
944
		}
945
946
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
947
		$timestamp = (int) $timestamp;
948
		$nonce     = esc_sql( $nonce );
949
950
		// Raw query so we can avoid races: add_option will also update.
951
		$show_errors = $wpdb->show_errors( false );
952
953
		$old_nonce = $wpdb->get_row(
954
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
955
		);
956
957
		if ( is_null( $old_nonce ) ) {
958
			$return = $wpdb->query(
959
				$wpdb->prepare(
960
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
961
					"jetpack_nonce_{$timestamp}_{$nonce}",
962
					time(),
963
					'no'
964
				)
965
			);
966
		} else {
967
			$return = false;
968
		}
969
970
		$wpdb->show_errors( $show_errors );
971
972
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
973
974
		return $return;
975
	}
976
977
	/**
978
	 * Cleans nonces that were saved when calling ::add_nonce.
979
	 *
980
	 * @todo Properly prepare the query before executing it.
981
	 *
982
	 * @param bool $all whether to clean even non-expired nonces.
983
	 */
984
	public function clean_nonces( $all = false ) {
985
		global $wpdb;
986
987
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
988
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
989
990
		if ( true !== $all ) {
991
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
992
			$sql_args[] = time() - 3600;
993
		}
994
995
		$sql .= ' ORDER BY `option_id` LIMIT 100';
996
997
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
998
999
		for ( $i = 0; $i < 1000; $i++ ) {
1000
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1001
				break;
1002
			}
1003
		}
1004
	}
1005
1006
	/**
1007
	 * Builds the timeout limit for queries talking with the wpcom servers.
1008
	 *
1009
	 * Based on local php max_execution_time in php.ini
1010
	 *
1011
	 * @since 5.4
1012
	 * @return int
1013
	 **/
1014
	public function get_max_execution_time() {
1015
		$timeout = (int) ini_get( 'max_execution_time' );
1016
1017
		// Ensure exec time set in php.ini.
1018
		if ( ! $timeout ) {
1019
			$timeout = 30;
1020
		}
1021
		return $timeout;
1022
	}
1023
1024
	/**
1025
	 * Sets a minimum request timeout, and returns the current timeout
1026
	 *
1027
	 * @since 5.4
1028
	 * @param Integer $min_timeout the minimum timeout value.
1029
	 **/
1030 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1031
		$timeout = $this->get_max_execution_time();
1032
		if ( $timeout < $min_timeout ) {
1033
			$timeout = $min_timeout;
1034
			set_time_limit( $timeout );
1035
		}
1036
		return $timeout;
1037
	}
1038
1039
	/**
1040
	 * Get our assumed site creation date.
1041
	 * Calculated based on the earlier date of either:
1042
	 * - Earliest admin user registration date.
1043
	 * - Earliest date of post of any post type.
1044
	 *
1045
	 * @since 7.2.0
1046
	 *
1047
	 * @return string Assumed site creation date and time.
1048
	 */
1049
	public function get_assumed_site_creation_date() {
1050
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1051
		if ( ! empty( $cached_date ) ) {
1052
			return $cached_date;
1053
		}
1054
1055
		$earliest_registered_users  = get_users(
1056
			array(
1057
				'role'    => 'administrator',
1058
				'orderby' => 'user_registered',
1059
				'order'   => 'ASC',
1060
				'fields'  => array( 'user_registered' ),
1061
				'number'  => 1,
1062
			)
1063
		);
1064
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1065
1066
		$earliest_posts = get_posts(
1067
			array(
1068
				'posts_per_page' => 1,
1069
				'post_type'      => 'any',
1070
				'post_status'    => 'any',
1071
				'orderby'        => 'date',
1072
				'order'          => 'ASC',
1073
			)
1074
		);
1075
1076
		// If there are no posts at all, we'll count only on user registration date.
1077
		if ( $earliest_posts ) {
1078
			$earliest_post_date = $earliest_posts[0]->post_date;
1079
		} else {
1080
			$earliest_post_date = PHP_INT_MAX;
1081
		}
1082
1083
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1084
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1085
1086
		return $assumed_date;
1087
	}
1088
1089
	/**
1090
	 * Adds the activation source string as a parameter to passed arguments.
1091
	 *
1092
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1093
	 *
1094
	 * @param Array $args arguments that need to have the source added.
1095
	 * @return Array $amended arguments.
1096
	 */
1097 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1098
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1099
1100
		if ( $activation_source_name ) {
1101
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1102
			$args['_as'] = urlencode( $activation_source_name );
1103
		}
1104
1105
		if ( $activation_source_keyword ) {
1106
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1107
			$args['_ak'] = urlencode( $activation_source_keyword );
1108
		}
1109
1110
		return $args;
1111
	}
1112
1113
	/**
1114
	 * Returns the callable that would be used to generate secrets.
1115
	 *
1116
	 * @return Callable a function that returns a secure string to be used as a secret.
1117
	 */
1118
	protected function get_secret_callable() {
1119
		if ( ! isset( $this->secret_callable ) ) {
1120
			/**
1121
			 * Allows modification of the callable that is used to generate connection secrets.
1122
			 *
1123
			 * @param Callable a function or method that returns a secret string.
1124
			 */
1125
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', 'wp_generate_password' );
1126
		}
1127
1128
		return $this->secret_callable;
1129
	}
1130
1131
	/**
1132
	 * Generates two secret tokens and the end of life timestamp for them.
1133
	 *
1134
	 * @param String  $action  The action name.
1135
	 * @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...
1136
	 * @param Integer $exp     Expiration time in seconds.
1137
	 */
1138
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1139
		$callable = $this->get_secret_callable();
1140
1141
		$secrets = \Jetpack_Options::get_raw_option(
1142
			self::SECRETS_OPTION_NAME,
1143
			array()
1144
		);
1145
1146
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1147
1148
		if (
1149
			isset( $secrets[ $secret_name ] ) &&
1150
			$secrets[ $secret_name ]['exp'] > time()
1151
		) {
1152
			return $secrets[ $secret_name ];
1153
		}
1154
1155
		$secret_value = array(
1156
			'secret_1' => call_user_func( $callable ),
1157
			'secret_2' => call_user_func( $callable ),
1158
			'exp'      => time() + $exp,
1159
		);
1160
1161
		$secrets[ $secret_name ] = $secret_value;
1162
1163
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1164
		return $secrets[ $secret_name ];
1165
	}
1166
1167
	/**
1168
	 * Returns two secret tokens and the end of life timestamp for them.
1169
	 *
1170
	 * @param String  $action  The action name.
1171
	 * @param Integer $user_id The user identifier.
1172
	 * @return string|array an array of secrets or an error string.
1173
	 */
1174
	public function get_secrets( $action, $user_id ) {
1175
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1176
		$secrets     = \Jetpack_Options::get_raw_option(
1177
			self::SECRETS_OPTION_NAME,
1178
			array()
1179
		);
1180
1181
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1182
			return self::SECRETS_MISSING;
1183
		}
1184
1185
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1186
			$this->delete_secrets( $action, $user_id );
1187
			return self::SECRETS_EXPIRED;
1188
		}
1189
1190
		return $secrets[ $secret_name ];
1191
	}
1192
1193
	/**
1194
	 * Deletes secret tokens in case they, for example, have expired.
1195
	 *
1196
	 * @param String  $action  The action name.
1197
	 * @param Integer $user_id The user identifier.
1198
	 */
1199
	public function delete_secrets( $action, $user_id ) {
1200
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1201
		$secrets     = \Jetpack_Options::get_raw_option(
1202
			self::SECRETS_OPTION_NAME,
1203
			array()
1204
		);
1205
		if ( isset( $secrets[ $secret_name ] ) ) {
1206
			unset( $secrets[ $secret_name ] );
1207
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1208
		}
1209
	}
1210
1211
	/**
1212
	 * Responds to a WordPress.com call to register the current site.
1213
	 * Should be changed to protected.
1214
	 *
1215
	 * @param array $registration_data Array of [ secret_1, user_id ].
1216
	 */
1217
	public function handle_registration( array $registration_data ) {
1218
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1219
		if ( empty( $registration_user_id ) ) {
1220
			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...
1221
		}
1222
1223
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1224
	}
1225
1226
	/**
1227
	 * Verify a Previously Generated Secret.
1228
	 *
1229
	 * @param string $action   The type of secret to verify.
1230
	 * @param string $secret_1 The secret string to compare to what is stored.
1231
	 * @param int    $user_id  The user ID of the owner of the secret.
1232
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1233
	 */
1234
	public function verify_secrets( $action, $secret_1, $user_id ) {
1235
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1236
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1237
			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...
1238
		}
1239
1240
		$user = get_user_by( 'id', $user_id );
1241
1242
		/**
1243
		 * We've begun verifying the previously generated secret.
1244
		 *
1245
		 * @since 7.5.0
1246
		 *
1247
		 * @param string   $action The type of secret to verify.
1248
		 * @param \WP_User $user The user object.
1249
		 */
1250
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1251
1252
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1253
			/**
1254
			 * Verifying of the previously generated secret has failed.
1255
			 *
1256
			 * @since 7.5.0
1257
			 *
1258
			 * @param string    $action  The type of secret to verify.
1259
			 * @param \WP_User  $user The user object.
1260
			 * @param \WP_Error $error The error object.
1261
			 */
1262
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1263
1264
			return $error;
1265
		};
1266
1267
		$stored_secrets = $this->get_secrets( $action, $user_id );
1268
		$this->delete_secrets( $action, $user_id );
1269
1270
		$error = null;
1271
		if ( empty( $secret_1 ) ) {
1272
			$error = $return_error(
1273
				new \WP_Error(
1274
					'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...
1275
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1276
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1277
					400
1278
				)
1279
			);
1280
		} elseif ( ! is_string( $secret_1 ) ) {
1281
			$error = $return_error(
1282
				new \WP_Error(
1283
					'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...
1284
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1285
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1286
					400
1287
				)
1288
			);
1289
		} elseif ( empty( $user_id ) ) {
1290
			// $user_id is passed around during registration as "state".
1291
			$error = $return_error(
1292
				new \WP_Error(
1293
					'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...
1294
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1295
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1296
					400
1297
				)
1298
			);
1299
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1300
			$error = $return_error(
1301
				new \WP_Error(
1302
					'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...
1303
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1304
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1305
					400
1306
				)
1307
			);
1308
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1309
			$error = $return_error(
1310
				new \WP_Error(
1311
					'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...
1312
					__( 'Verification secrets not found', 'jetpack' ),
1313
					400
1314
				)
1315
			);
1316
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1317
			$error = $return_error(
1318
				new \WP_Error(
1319
					'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...
1320
					__( 'Verification took too long', 'jetpack' ),
1321
					400
1322
				)
1323
			);
1324
		} elseif ( ! $stored_secrets ) {
1325
			$error = $return_error(
1326
				new \WP_Error(
1327
					'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...
1328
					__( 'Verification secrets are empty', 'jetpack' ),
1329
					400
1330
				)
1331
			);
1332
		} elseif ( is_wp_error( $stored_secrets ) ) {
1333
			$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...
1334
			$error = $return_error( $stored_secrets );
1335
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1336
			$error = $return_error(
1337
				new \WP_Error(
1338
					'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...
1339
					__( 'Verification secrets are incomplete', 'jetpack' ),
1340
					400
1341
				)
1342
			);
1343
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1344
			$error = $return_error(
1345
				new \WP_Error(
1346
					'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...
1347
					__( 'Secret mismatch', 'jetpack' ),
1348
					400
1349
				)
1350
			);
1351
		}
1352
1353
		// Something went wrong during the checks, returning the error.
1354
		if ( ! empty( $error ) ) {
1355
			return $error;
1356
		}
1357
1358
		/**
1359
		 * We've succeeded at verifying the previously generated secret.
1360
		 *
1361
		 * @since 7.5.0
1362
		 *
1363
		 * @param string   $action The type of secret to verify.
1364
		 * @param \WP_User $user The user object.
1365
		 */
1366
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1367
1368
		return $stored_secrets['secret_2'];
1369
	}
1370
1371
	/**
1372
	 * Responds to a WordPress.com call to authorize the current user.
1373
	 * Should be changed to protected.
1374
	 */
1375
	public function handle_authorization() {
1376
1377
	}
1378
1379
	/**
1380
	 * Builds a URL to the Jetpack connection auth page.
1381
	 * This needs rethinking.
1382
	 *
1383
	 * @param bool        $raw If true, URL will not be escaped.
1384
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
1385
	 *                              If string, will be a custom redirect.
1386
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
1387
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0.
1388
	 *
1389
	 * @return string Connect URL
1390
	 */
1391
	public function build_connect_url( $raw, $redirect, $from, $register ) {
1392
		return array( $raw, $redirect, $from, $register );
1393
	}
1394
1395
	/**
1396
	 * Disconnects from the Jetpack servers.
1397
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1398
	 */
1399
	public function disconnect_site() {
1400
1401
	}
1402
1403
	/**
1404
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1405
	 *
1406
	 * @param string $text The string to hash.
1407
	 * @return string
1408
	 */
1409
	public function sha1_base64( $text ) {
1410
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1411
	}
1412
1413
	/**
1414
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1415
	 *
1416
	 * @param string $domain The domain to check.
1417
	 *
1418
	 * @return bool|WP_Error
1419
	 */
1420
	public function is_usable_domain( $domain ) {
1421
1422
		// If it's empty, just fail out.
1423
		if ( ! $domain ) {
1424
			return new \WP_Error(
1425
				'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...
1426
				/* translators: %1$s is a domain name. */
1427
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1428
			);
1429
		}
1430
1431
		/**
1432
		 * Skips the usuable domain check when connecting a site.
1433
		 *
1434
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1435
		 *
1436
		 * @since 4.1.0
1437
		 *
1438
		 * @param bool If the check should be skipped. Default false.
1439
		 */
1440
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1441
			return true;
1442
		}
1443
1444
		// None of the explicit localhosts.
1445
		$forbidden_domains = array(
1446
			'wordpress.com',
1447
			'localhost',
1448
			'localhost.localdomain',
1449
			'127.0.0.1',
1450
			'local.wordpress.test',         // VVV pattern.
1451
			'local.wordpress-trunk.test',   // VVV pattern.
1452
			'src.wordpress-develop.test',   // VVV pattern.
1453
			'build.wordpress-develop.test', // VVV pattern.
1454
		);
1455 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1456
			return new \WP_Error(
1457
				'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...
1458
				sprintf(
1459
					/* translators: %1$s is a domain name. */
1460
					__(
1461
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1462
						'jetpack'
1463
					),
1464
					$domain
1465
				)
1466
			);
1467
		}
1468
1469
		// No .test or .local domains.
1470 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1471
			return new \WP_Error(
1472
				'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...
1473
				sprintf(
1474
					/* translators: %1$s is a domain name. */
1475
					__(
1476
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1477
						'jetpack'
1478
					),
1479
					$domain
1480
				)
1481
			);
1482
		}
1483
1484
		// No WPCOM subdomains.
1485 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1486
			return new \WP_Error(
1487
				'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...
1488
				sprintf(
1489
					/* translators: %1$s is a domain name. */
1490
					__(
1491
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1492
						'jetpack'
1493
					),
1494
					$domain
1495
				)
1496
			);
1497
		}
1498
1499
		// If PHP was compiled without support for the Filter module (very edge case).
1500
		if ( ! function_exists( 'filter_var' ) ) {
1501
			// Just pass back true for now, and let wpcom sort it out.
1502
			return true;
1503
		}
1504
1505
		return true;
1506
	}
1507
1508
	/**
1509
	 * Gets the requested token.
1510
	 *
1511
	 * Tokens are one of two types:
1512
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
1513
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
1514
	 *    are not associated with a user account. They represent the site's connection with
1515
	 *    the Jetpack servers.
1516
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
1517
	 *
1518
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
1519
	 * token, and $private is a secret that should never be displayed anywhere or sent
1520
	 * over the network; it's used only for signing things.
1521
	 *
1522
	 * Blog Tokens can be "Normal" or "Special".
1523
	 * * Normal: The result of a normal connection flow. They look like
1524
	 *   "{$random_string_1}.{$random_string_2}"
1525
	 *   That is, $token_key and $private are both random strings.
1526
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
1527
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
1528
	 *   constant (rare).
1529
	 * * Special: A connection token for sites that have gone through an alternative
1530
	 *   connection flow. They look like:
1531
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
1532
	 *   That is, $private is a random string and $token_key has a special structure with
1533
	 *   lots of semicolons.
1534
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
1535
	 *   JETPACK_BLOG_TOKEN constant.
1536
	 *
1537
	 * In particular, note that Normal Blog Tokens never start with ";" and that
1538
	 * Special Blog Tokens always do.
1539
	 *
1540
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
1541
	 * order:
1542
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
1543
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
1544
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
1545
	 *
1546
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1547
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1548
	 * @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.
1549
	 *
1550
	 * @return object|false
1551
	 */
1552
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1553
		$possible_special_tokens = array();
1554
		$possible_normal_tokens  = array();
1555
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
1556
1557
		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...
1558
			if ( ! $user_tokens ) {
1559
				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...
1560
			}
1561
			if ( self::JETPACK_MASTER_USER === $user_id ) {
1562
				$user_id = \Jetpack_Options::get_option( 'master_user' );
1563
				if ( ! $user_id ) {
1564
					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...
1565
				}
1566
			}
1567
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
1568
				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...
1569
			}
1570
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
1571 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
1572
				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...
1573
			}
1574 View Code Duplication
			if ( $user_token_chunks[2] !== (string) $user_id ) {
1575
				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...
1576
			}
1577
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
1578
		} else {
1579
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
1580
			if ( $stored_blog_token ) {
1581
				$possible_normal_tokens[] = $stored_blog_token;
1582
			}
1583
1584
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
1585
1586
			if ( $defined_tokens_string ) {
1587
				$defined_tokens = explode( ',', $defined_tokens_string );
1588
				foreach ( $defined_tokens as $defined_token ) {
1589
					if ( ';' === $defined_token[0] ) {
1590
						$possible_special_tokens[] = $defined_token;
1591
					} else {
1592
						$possible_normal_tokens[] = $defined_token;
1593
					}
1594
				}
1595
			}
1596
		}
1597
1598
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1599
			$possible_tokens = $possible_normal_tokens;
1600
		} else {
1601
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
1602
		}
1603
1604
		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...
1605
			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...
1606
		}
1607
1608
		$valid_token = false;
1609
1610
		if ( false === $token_key ) {
1611
			// Use first token.
1612
			$valid_token = $possible_tokens[0];
1613
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1614
			// Use first normal token.
1615
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
1616
		} else {
1617
			// Use the token matching $token_key or false if none.
1618
			// Ensure we check the full key.
1619
			$token_check = rtrim( $token_key, '.' ) . '.';
1620
1621
			foreach ( $possible_tokens as $possible_token ) {
1622
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
1623
					$valid_token = $possible_token;
1624
					break;
1625
				}
1626
			}
1627
		}
1628
1629
		if ( ! $valid_token ) {
1630
			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...
1631
		}
1632
1633
		return (object) array(
1634
			'secret'           => $valid_token,
1635
			'external_user_id' => (int) $user_id,
1636
		);
1637
	}
1638
1639
	/**
1640
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
1641
	 * since it is passed by reference to various methods.
1642
	 * Capture it here so we can verify the signature later.
1643
	 *
1644
	 * @param Array $methods an array of available XMLRPC methods.
1645
	 * @return Array the same array, since this method doesn't add or remove anything.
1646
	 */
1647
	public function xmlrpc_methods( $methods ) {
1648
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
1649
		return $methods;
1650
	}
1651
1652
	/**
1653
	 * Resets the raw post data parameter for testing purposes.
1654
	 */
1655
	public function reset_raw_post_data() {
1656
		$this->raw_post_data = null;
1657
	}
1658
1659
	/**
1660
	 * Registering an additional method.
1661
	 *
1662
	 * @param Array $methods an array of available XMLRPC methods.
1663
	 * @return Array the amended array in case the method is added.
1664
	 */
1665
	public function public_xmlrpc_methods( $methods ) {
1666
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
1667
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
1668
		}
1669
		return $methods;
1670
	}
1671
1672
	/**
1673
	 * Handles a getOptions XMLRPC method call.
1674
	 *
1675
	 * @param Array $args method call arguments.
1676
	 * @return an amended XMLRPC server options array.
1677
	 */
1678
	public function jetpack_get_options( $args ) {
1679
		global $wp_xmlrpc_server;
1680
1681
		$wp_xmlrpc_server->escape( $args );
1682
1683
		$username = $args[1];
1684
		$password = $args[2];
1685
1686
		$user = $wp_xmlrpc_server->login( $username, $password );
1687
		if ( ! $user ) {
1688
			return $wp_xmlrpc_server->error;
1689
		}
1690
1691
		$options   = array();
1692
		$user_data = $this->get_connected_user_data();
1693
		if ( is_array( $user_data ) ) {
1694
			$options['jetpack_user_id']         = array(
1695
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
1696
				'readonly' => true,
1697
				'value'    => $user_data['ID'],
1698
			);
1699
			$options['jetpack_user_login']      = array(
1700
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
1701
				'readonly' => true,
1702
				'value'    => $user_data['login'],
1703
			);
1704
			$options['jetpack_user_email']      = array(
1705
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
1706
				'readonly' => true,
1707
				'value'    => $user_data['email'],
1708
			);
1709
			$options['jetpack_user_site_count'] = array(
1710
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
1711
				'readonly' => true,
1712
				'value'    => $user_data['site_count'],
1713
			);
1714
		}
1715
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
1716
		$args                           = stripslashes_deep( $args );
1717
		return $wp_xmlrpc_server->wp_getOptions( $args );
1718
	}
1719
1720
	/**
1721
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
1722
	 *
1723
	 * @param Array $options standard Core options.
1724
	 * @return Array amended options.
1725
	 */
1726
	public function xmlrpc_options( $options ) {
1727
		$jetpack_client_id = false;
1728
		if ( $this->is_active() ) {
1729
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
1730
		}
1731
		$options['jetpack_version'] = array(
1732
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
1733
			'readonly' => true,
1734
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
1735
		);
1736
1737
		$options['jetpack_client_id'] = array(
1738
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
1739
			'readonly' => true,
1740
			'value'    => $jetpack_client_id,
1741
		);
1742
		return $options;
1743
	}
1744
1745
	/**
1746
	 * Resets the saved authentication state in between testing requests.
1747
	 */
1748
	public function reset_saved_auth_state() {
1749
		$this->xmlrpc_verification = null;
1750
	}
1751
1752
	/**
1753
	 * Sign a user role with the master access token.
1754
	 * If not specified, will default to the current user.
1755
	 *
1756
	 * @access public
1757
	 *
1758
	 * @param string $role    User role.
1759
	 * @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...
1760
	 * @return string Signed user role.
1761
	 */
1762
	public function sign_role( $role, $user_id = null ) {
1763
		if ( empty( $user_id ) ) {
1764
			$user_id = (int) get_current_user_id();
1765
		}
1766
1767
		if ( ! $user_id ) {
1768
			return false;
1769
		}
1770
1771
		$token = $this->get_access_token();
1772
		if ( ! $token || is_wp_error( $token ) ) {
1773
			return false;
1774
		}
1775
1776
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
1777
	}
1778
}
1779