Completed
Push — add/instant-search-blog-id ( 68072d...a57a7d )
by
unknown
08:45 queued 01:37
created

Manager::verify_signature()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * The Jetpack Connection manager class file.
4
 *
5
 * @package jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Tracking;
12
13
/**
14
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
15
 * and Jetpack.
16
 */
17
class Manager implements Manager_Interface {
18
19
	const SECRETS_MISSING        = 'secrets_missing';
20
	const SECRETS_EXPIRED        = 'secrets_expired';
21
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
22
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
23
	const JETPACK_MASTER_USER    = true;
24
25
	/**
26
	 * The procedure that should be run to generate secrets.
27
	 *
28
	 * @var Callable
29
	 */
30
	protected $secret_callable;
31
32
	/**
33
	 * 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
54
		$is_jetpack_xmlrpc_request = $this->setup_xmlrpc_handlers(
55
			$_GET,
56
			$this->is_active(),
57
			$this->verify_xml_rpc_signature()
0 ignored issues
show
Bug introduced by
It seems like $this->verify_xml_rpc_signature() targeting Automattic\Jetpack\Conne...ify_xml_rpc_signature() can also be of type array; however, Automattic\Jetpack\Conne...setup_xmlrpc_handlers() does only seem to accept boolean, maybe add an additional type check?

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

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

An additional type check may prevent trouble.

Loading history...
58
		);
59
60
		// All the XMLRPC functionality has been moved into setup_xmlrpc_handlers.
61 View Code Duplication
		if (
62
			! $is_jetpack_xmlrpc_request
63
			&& is_admin()
64
			&& isset( $_POST['action'] ) // phpcs:ignore WordPress.Security.NonceVerification
65
			&& (
66
				'jetpack_upload_file' === $_POST['action']  // phpcs:ignore WordPress.Security.NonceVerification
67
				|| 'jetpack_update_file' === $_POST['action']  // phpcs:ignore WordPress.Security.NonceVerification
68
			)
69
		) {
70
			$this->require_jetpack_authentication();
71
			return;
72
		}
73
74
		if ( $this->is_active() ) {
75
			add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
76
		} else {
77
			add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
78
		}
79
	}
80
81
	/**
82
	 * Sets up the XMLRPC request handlers.
83
	 *
84
	 * @param Array                  $request_params incoming request parameters.
85
	 * @param Boolean                $is_active whether the connection is currently active.
86
	 * @param Boolean                $is_signed whether the signature check has been successful.
87
	 * @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...
88
	 */
89
	public function setup_xmlrpc_handlers(
90
		$request_params,
91
		$is_active,
92
		$is_signed,
93
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
94
	) {
95
		if (
96
			! isset( $request_params['for'] )
97
			|| 'jetpack' !== $request_params['for']
98
		) {
99
			return false;
100
		}
101
102
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
103
		if (
104
			isset( $request_params['jetpack'] )
105
			&& 'comms' === $request_params['jetpack']
106
		) {
107
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
108
				// Use the real constant here for WordPress' sake.
109
				define( 'XMLRPC_REQUEST', true );
110
			}
111
112
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
113
114
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
115
		}
116
117
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
118
			return false;
119
		}
120
		// Display errors can cause the XML to be not well formed.
121
		@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...
122
123
		if ( $xmlrpc_server ) {
124
			$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...
125
		} else {
126
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
127
		}
128
129
		$this->require_jetpack_authentication();
130
131
		if ( $is_active ) {
132
			// Hack to preserve $HTTP_RAW_POST_DATA.
133
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
134
135
			if ( $is_signed ) {
136
				// The actual API methods.
137
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
138
			} else {
139
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
140
				// active Jetpack connection, so that additional users can link their account.
141
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
142
			}
143
		} else {
144
			// The bootstrap API methods.
145
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
146
147
			if ( $is_signed ) {
148
				// The jetpack Provision method is available for blog-token-signed requests.
149
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
150
			} else {
151
				new XMLRPC_Connector( $this );
152
			}
153
		}
154
155
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
156
157
		add_action( 'jetpack_clean_nonces', array( $this, 'clean_nonces' ) );
158
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
159
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
160
		}
161
162
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
163
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
164
165
		return true;
166
	}
167
168
	/**
169
	 * Initializes the REST API connector on the init hook.
170
	 */
171
	public function initialize_rest_api_registration_connector() {
172
		new REST_Connector( $this );
173
	}
174
175
	/**
176
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
177
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
178
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
179
	 * which is accessible via a different URI. Most of the below is copied directly
180
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
181
	 *
182
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
183
	 */
184
	public function alternate_xmlrpc() {
185
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
186
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
187
		global $HTTP_RAW_POST_DATA;
188
189
		// Some browser-embedded clients send cookies. We don't want them.
190
		$_COOKIE = array();
191
192
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
193
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
194
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
195
		}
196
197
		// phpcs:enable
198
199
		include_once ABSPATH . 'wp-admin/includes/admin.php';
200
		include_once ABSPATH . WPINC . '/class-IXR.php';
201
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
202
203
		/**
204
		 * Filters the class used for handling XML-RPC requests.
205
		 *
206
		 * @since 3.1.0
207
		 *
208
		 * @param string $class The name of the XML-RPC server class.
209
		 */
210
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
211
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
212
213
		// Fire off the request.
214
		nocache_headers();
215
		$wp_xmlrpc_server->serve_request();
216
217
		exit;
218
	}
219
220
	/**
221
	 * Removes all XML-RPC methods that are not `jetpack.*`.
222
	 * Only used in our alternate XML-RPC endpoint, where we want to
223
	 * ensure that Core and other plugins' methods are not exposed.
224
	 *
225
	 * @param array $methods a list of registered WordPress XMLRPC methods.
226
	 * @return array filtered $methods
227
	 */
228
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
229
		$jetpack_methods = array();
230
231
		foreach ( $methods as $method => $callback ) {
232
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
233
				$jetpack_methods[ $method ] = $callback;
234
			}
235
		}
236
237
		return $jetpack_methods;
238
	}
239
240
	/**
241
	 * Removes all other authentication methods not to allow other
242
	 * methods to validate unauthenticated requests.
243
	 */
244
	public function require_jetpack_authentication() {
245
		// Don't let anyone authenticate.
246
		$_COOKIE = array();
247
		remove_all_filters( 'authenticate' );
248
		remove_all_actions( 'wp_login_failed' );
249
250
		if ( $this->is_active() ) {
251
			// Allow Jetpack authentication.
252
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
253
		}
254
	}
255
256
	/**
257
	 * Authenticates XML-RPC and other requests from the Jetpack Server
258
	 *
259
	 * @param WP_User|Mixed $user user object if authenticated.
260
	 * @param String        $username username.
261
	 * @param String        $password password string.
262
	 * @return WP_User|Mixed authenticated user or error.
263
	 */
264
	public function authenticate_jetpack( $user, $username, $password ) {
265
		if ( is_a( $user, '\\WP_User' ) ) {
266
			return $user;
267
		}
268
269
		$token_details = $this->verify_xml_rpc_signature();
270
271
		if ( ! $token_details ) {
272
			return $user;
273
		}
274
275
		if ( 'user' !== $token_details['type'] ) {
276
			return $user;
277
		}
278
279
		if ( ! $token_details['user_id'] ) {
280
			return $user;
281
		}
282
283
		nocache_headers();
284
285
		return new \WP_User( $token_details['user_id'] );
286
	}
287
288
	/**
289
	 * Verifies the signature of the current request.
290
	 *
291
	 * @return false|array
292
	 */
293
	public function verify_xml_rpc_signature() {
294
		if ( is_null( $this->xmlrpc_verification ) ) {
295
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
296
297
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
298
				/**
299
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
300
				 *
301
				 * Error codes:
302
				 * - malformed_token
303
				 * - malformed_user_id
304
				 * - unknown_token
305
				 * - could_not_sign
306
				 * - invalid_nonce
307
				 * - signature_mismatch
308
				 *
309
				 * @since 7.5.0
310
				 *
311
				 * @param WP_Error $signature_verification_error The verification error
312
				 */
313
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
314
			}
315
		}
316
317
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
318
	}
319
320
	/**
321
	 * Verifies the signature of the current request.
322
	 *
323
	 * This function has side effects and should not be used. Instead,
324
	 * use the memoized version `->verify_xml_rpc_signature()`.
325
	 *
326
	 * @internal
327
	 */
328
	private function internal_verify_xml_rpc_signature() {
329
		// It's not for us.
330
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
331
			return false;
332
		}
333
334
		$signature_details = array(
335
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
336
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
337
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
338
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
339
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
340
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
341
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
342
		);
343
344
		@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...
345
		if (
346
			empty( $token_key )
347
		||
348
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
349
		) {
350
			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...
351
		}
352
353
		if ( '0' === $user_id ) {
354
			$token_type = 'blog';
355
			$user_id    = 0;
356
		} else {
357
			$token_type = 'user';
358
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
359
				return new \WP_Error(
360
					'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...
361
					'Malformed user_id in request',
362
					compact( 'signature_details' )
363
				);
364
			}
365
			$user_id = (int) $user_id;
366
367
			$user = new \WP_User( $user_id );
368
			if ( ! $user || ! $user->exists() ) {
369
				return new \WP_Error(
370
					'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...
371
					sprintf( 'User %d does not exist', $user_id ),
372
					compact( 'signature_details' )
373
				);
374
			}
375
		}
376
377
		$token = $this->get_access_token( $user_id, $token_key, false );
378
		if ( is_wp_error( $token ) ) {
379
			$token->add_data( compact( 'signature_details' ) );
380
			return $token;
381
		} elseif ( ! $token ) {
382
			return new \WP_Error(
383
				'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...
384
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
385
				compact( 'signature_details' )
386
			);
387
		}
388
389
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
390
		// phpcs:disable WordPress.Security.NonceVerification.Missing
391
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
392
			$post_data   = $_POST;
393
			$file_hashes = array();
394
			foreach ( $post_data as $post_data_key => $post_data_value ) {
395
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
396
					continue;
397
				}
398
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
399
				$file_hashes[ $post_data_key ] = $post_data_value;
400
			}
401
402
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
403
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
404
				$post_data[ $post_data_key ] = $post_data_value;
405
			}
406
407
			ksort( $post_data );
408
409
			$body = http_build_query( stripslashes_deep( $post_data ) );
410
		} elseif ( is_null( $this->raw_post_data ) ) {
411
			$body = file_get_contents( 'php://input' );
412
		} else {
413
			$body = null;
414
		}
415
		// phpcs:enable
416
417
		$signature = $jetpack_signature->sign_current_request(
418
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
419
		);
420
421
		$signature_details['url'] = $jetpack_signature->current_request_url;
422
423
		if ( ! $signature ) {
424
			return new \WP_Error(
425
				'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...
426
				'Unknown signature error',
427
				compact( 'signature_details' )
428
			);
429
		} elseif ( is_wp_error( $signature ) ) {
430
			return $signature;
431
		}
432
433
		$timestamp = (int) $_GET['timestamp'];
434
		$nonce     = stripslashes( (string) $_GET['nonce'] );
435
436
		// Use up the nonce regardless of whether the signature matches.
437
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
438
			return new \WP_Error(
439
				'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...
440
				'Could not add nonce',
441
				compact( 'signature_details' )
442
			);
443
		}
444
445
		// Be careful about what you do with this debugging data.
446
		// If a malicious requester has access to the expected signature,
447
		// bad things might be possible.
448
		$signature_details['expected'] = $signature;
449
450
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
451
			return new \WP_Error(
452
				'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...
453
				'Signature mismatch',
454
				compact( 'signature_details' )
455
			);
456
		}
457
458
		/**
459
		 * Action for additional token checking.
460
		 *
461
		 * @since 7.7.0
462
		 *
463
		 * @param Array $post_data request data.
464
		 * @param Array $token_data token data.
465
		 */
466
		return apply_filters(
467
			'jetpack_signature_check_token',
468
			array(
469
				'type'      => $token_type,
470
				'token_key' => $token_key,
471
				'user_id'   => $token->external_user_id,
472
			),
473
			$token,
474
			$this->raw_post_data
475
		);
476
	}
477
478
	/**
479
	 * Returns true if the current site is connected to WordPress.com.
480
	 *
481
	 * @return Boolean is the site connected?
482
	 */
483
	public function is_active() {
484
		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...
485
	}
486
487
	/**
488
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
489
	 *
490
	 * @access public
491
	 *
492
	 * @return bool
493
	 */
494
	public function is_registered() {
495
		$blog_id   = \Jetpack_Options::get_option( 'id' );
496
		$has_token = $this->is_active();
497
		return $blog_id && $has_token;
498
	}
499
500
	/**
501
	 * Returns true if the user with the specified identifier is connected to
502
	 * WordPress.com.
503
	 *
504
	 * @param Integer|Boolean $user_id the user identifier.
505
	 * @return Boolean is the user connected?
506
	 */
507
	public function is_user_connected( $user_id = false ) {
508
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
509
		if ( ! $user_id ) {
510
			return false;
511
		}
512
513
		return (bool) $this->get_access_token( $user_id );
514
	}
515
516
	/**
517
	 * Get the wpcom user data of the current|specified connected user.
518
	 *
519
	 * @todo Refactor to properly load the XMLRPC client independently.
520
	 *
521
	 * @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...
522
	 * @return Object the user object.
523
	 */
524 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
525
		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...
526
			$user_id = get_current_user_id();
527
		}
528
529
		$transient_key    = "jetpack_connected_user_data_$user_id";
530
		$cached_user_data = get_transient( $transient_key );
531
532
		if ( $cached_user_data ) {
533
			return $cached_user_data;
534
		}
535
536
		$xml = new \Jetpack_IXR_Client(
537
			array(
538
				'user_id' => $user_id,
539
			)
540
		);
541
		$xml->query( 'wpcom.getUser' );
542
		if ( ! $xml->isError() ) {
543
			$user_data = $xml->getResponse();
544
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
545
			return $user_data;
546
		}
547
548
		return false;
549
	}
550
551
	/**
552
	 * Returns true if the provided user is the Jetpack connection owner.
553
	 * If user ID is not specified, the current user will be used.
554
	 *
555
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
556
	 * @return Boolean True the user the connection owner, false otherwise.
557
	 */
558
	public function is_connection_owner( $user_id = false ) {
559
		if ( ! $user_id ) {
560
			$user_id = get_current_user_id();
561
		}
562
563
		$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...
564
565
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
566
	}
567
568
	/**
569
	 * Unlinks the current user from the linked WordPress.com user.
570
	 *
571
	 * @access public
572
	 * @static
573
	 *
574
	 * @todo Refactor to properly load the XMLRPC client independently.
575
	 *
576
	 * @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...
577
	 * @return Boolean Whether the disconnection of the user was successful.
578
	 */
579
	public static function disconnect_user( $user_id = null ) {
580
		$tokens = \Jetpack_Options::get_option( 'user_tokens' );
581
		if ( ! $tokens ) {
582
			return false;
583
		}
584
585
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
586
587
		if ( \Jetpack_Options::get_option( 'master_user' ) === $user_id ) {
588
			return false;
589
		}
590
591
		if ( ! isset( $tokens[ $user_id ] ) ) {
592
			return false;
593
		}
594
595
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
596
		$xml->query( 'jetpack.unlink_user', $user_id );
597
598
		unset( $tokens[ $user_id ] );
599
600
		\Jetpack_Options::update_option( 'user_tokens', $tokens );
601
602
		/**
603
		 * Fires after the current user has been unlinked from WordPress.com.
604
		 *
605
		 * @since 4.1.0
606
		 *
607
		 * @param int $user_id The current user's ID.
608
		 */
609
		do_action( 'jetpack_unlinked_user', $user_id );
610
611
		return true;
612
	}
613
614
	/**
615
	 * Returns the requested Jetpack API URL.
616
	 *
617
	 * @param String $relative_url the relative API path.
618
	 * @return String API URL.
619
	 */
620
	public function api_url( $relative_url ) {
621
		$api_base = Constants::get_constant( 'JETPACK__API_BASE' );
622
		$version  = Constants::get_constant( 'JETPACK__API_VERSION' );
623
624
		$api_base = $api_base ? $api_base : 'https://jetpack.wordpress.com/jetpack.';
625
		$version  = $version ? '/' . $version . '/' : '/1/';
626
627
		return rtrim( $api_base . $relative_url, '/\\' ) . $version;
628
	}
629
630
	/**
631
	 * Attempts Jetpack registration which sets up the site for connection. Should
632
	 * remain public because the call to action comes from the current site, not from
633
	 * WordPress.com.
634
	 *
635
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
636
	 * @return Integer zero on success, or a bitmask on failure.
637
	 */
638
	public function register( $api_endpoint = 'register' ) {
639
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
640
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
641
642
		if (
643
			empty( $secrets['secret_1'] ) ||
644
			empty( $secrets['secret_2'] ) ||
645
			empty( $secrets['exp'] )
646
		) {
647
			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...
648
		}
649
650
		// Better to try (and fail) to set a higher timeout than this system
651
		// supports than to have register fail for more users than it should.
652
		$timeout = $this->set_min_time_limit( 60 ) / 2;
653
654
		$gmt_offset = get_option( 'gmt_offset' );
655
		if ( ! $gmt_offset ) {
656
			$gmt_offset = 0;
657
		}
658
659
		$stats_options = get_option( 'stats_options' );
660
		$stats_id      = isset( $stats_options['blog_id'] )
661
			? $stats_options['blog_id']
662
			: null;
663
664
		/**
665
		 * Filters the request body for additional property addition.
666
		 *
667
		 * @since 7.7.0
668
		 *
669
		 * @param Array $post_data request data.
670
		 * @param Array $token_data token data.
671
		 */
672
		$body = apply_filters(
673
			'jetpack_register_request_body',
674
			array(
675
				'siteurl'         => site_url(),
676
				'home'            => home_url(),
677
				'gmt_offset'      => $gmt_offset,
678
				'timezone_string' => (string) get_option( 'timezone_string' ),
679
				'site_name'       => (string) get_option( 'blogname' ),
680
				'secret_1'        => $secrets['secret_1'],
681
				'secret_2'        => $secrets['secret_2'],
682
				'site_lang'       => get_locale(),
683
				'timeout'         => $timeout,
684
				'stats_id'        => $stats_id,
685
				'state'           => get_current_user_id(),
686
				'site_created'    => $this->get_assumed_site_creation_date(),
687
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
688
			)
689
		);
690
691
		$args = array(
692
			'method'  => 'POST',
693
			'body'    => $body,
694
			'headers' => array(
695
				'Accept' => 'application/json',
696
			),
697
			'timeout' => $timeout,
698
		);
699
700
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
701
702
		// TODO: fix URLs for bad hosts.
703
		$response = Client::_wp_remote_request(
704
			$this->api_url( $api_endpoint ),
705
			$args,
706
			true
707
		);
708
709
		// Make sure the response is valid and does not contain any Jetpack errors.
710
		$registration_details = $this->validate_remote_register_response( $response );
711
712
		if ( is_wp_error( $registration_details ) ) {
713
			return $registration_details;
714
		} elseif ( ! $registration_details ) {
715
			return new \WP_Error(
716
				'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...
717
				'Unknown error registering your Jetpack site.',
718
				wp_remote_retrieve_response_code( $response )
719
			);
720
		}
721
722
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
723
			return new \WP_Error(
724
				'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...
725
				'Unable to validate registration of your Jetpack site.',
726
				wp_remote_retrieve_response_code( $response )
727
			);
728
		}
729
730
		if ( isset( $registration_details->jetpack_public ) ) {
731
			$jetpack_public = (int) $registration_details->jetpack_public;
732
		} else {
733
			$jetpack_public = false;
734
		}
735
736
		\Jetpack_Options::update_options(
737
			array(
738
				'id'         => (int) $registration_details->jetpack_id,
739
				'blog_token' => (string) $registration_details->jetpack_secret,
740
				'public'     => $jetpack_public,
741
			)
742
		);
743
744
		/**
745
		 * Fires when a site is registered on WordPress.com.
746
		 *
747
		 * @since 3.7.0
748
		 *
749
		 * @param int $json->jetpack_id Jetpack Blog ID.
750
		 * @param string $json->jetpack_secret Jetpack Blog Token.
751
		 * @param int|bool $jetpack_public Is the site public.
752
		 */
753
		do_action(
754
			'jetpack_site_registered',
755
			$registration_details->jetpack_id,
756
			$registration_details->jetpack_secret,
757
			$jetpack_public
758
		);
759
760
		if ( isset( $registration_details->token ) ) {
761
			/**
762
			 * Fires when a user token is sent along with the registration data.
763
			 *
764
			 * @since 7.6.0
765
			 *
766
			 * @param object $token the administrator token for the newly registered site.
767
			 */
768
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
769
		}
770
771
		return true;
772
	}
773
774
	/**
775
	 * Takes the response from the Jetpack register new site endpoint and
776
	 * verifies it worked properly.
777
	 *
778
	 * @since 2.6
779
	 *
780
	 * @param Mixed $response the response object, or the error object.
781
	 * @return string|WP_Error A JSON object on success or Jetpack_Error on failures
782
	 **/
783
	protected function validate_remote_register_response( $response ) {
784
		if ( is_wp_error( $response ) ) {
785
			return new \WP_Error(
786
				'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...
787
				$response->get_error_message()
788
			);
789
		}
790
791
		$code   = wp_remote_retrieve_response_code( $response );
792
		$entity = wp_remote_retrieve_body( $response );
793
794
		if ( $entity ) {
795
			$registration_response = json_decode( $entity );
796
		} else {
797
			$registration_response = false;
798
		}
799
800
		$code_type = intval( $code / 100 );
801
		if ( 5 === $code_type ) {
802
			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...
803
		} elseif ( 408 === $code ) {
804
			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...
805
		} elseif ( ! empty( $registration_response->error ) ) {
806
			if (
807
				'xml_rpc-32700' === $registration_response->error
808
				&& ! function_exists( 'xml_parser_create' )
809
			) {
810
				$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' );
811
			} else {
812
				$error_description = isset( $registration_response->error_description )
813
					? (string) $registration_response->error_description
814
					: '';
815
			}
816
817
			return new \WP_Error(
818
				(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...
819
				$error_description,
820
				$code
821
			);
822
		} elseif ( 200 !== $code ) {
823
			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...
824
		}
825
826
		// Jetpack ID error block.
827
		if ( empty( $registration_response->jetpack_id ) ) {
828
			return new \WP_Error(
829
				'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...
830
				/* translators: %s is an error message string */
831
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
832
				$entity
833
			);
834
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
835
			return new \WP_Error(
836
				'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...
837
				/* translators: %s is an error message string */
838
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
839
				$entity
840
			);
841
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
842
			return new \WP_Error(
843
				'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...
844
				/* translators: %s is an error message string */
845
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
846
				$entity
847
			);
848
		}
849
850
		return $registration_response;
851
	}
852
853
	/**
854
	 * Adds a used nonce to a list of known nonces.
855
	 *
856
	 * @param int    $timestamp the current request timestamp.
857
	 * @param string $nonce the nonce value.
858
	 * @return bool whether the nonce is unique or not.
859
	 */
860
	public function add_nonce( $timestamp, $nonce ) {
861
		global $wpdb;
862
		static $nonces_used_this_request = array();
863
864
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
865
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
866
		}
867
868
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
869
		$timestamp = (int) $timestamp;
870
		$nonce     = esc_sql( $nonce );
871
872
		// Raw query so we can avoid races: add_option will also update.
873
		$show_errors = $wpdb->show_errors( false );
874
875
		$old_nonce = $wpdb->get_row(
876
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
877
		);
878
879
		if ( is_null( $old_nonce ) ) {
880
			$return = $wpdb->query(
881
				$wpdb->prepare(
882
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
883
					"jetpack_nonce_{$timestamp}_{$nonce}",
884
					time(),
885
					'no'
886
				)
887
			);
888
		} else {
889
			$return = false;
890
		}
891
892
		$wpdb->show_errors( $show_errors );
893
894
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
895
896
		return $return;
897
	}
898
899
	/**
900
	 * Cleans nonces that were saved when calling ::add_nonce.
901
	 *
902
	 * @todo Properly prepare the query before executing it.
903
	 *
904
	 * @param bool $all whether to clean even non-expired nonces.
905
	 */
906
	public function clean_nonces( $all = false ) {
907
		global $wpdb;
908
909
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
910
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
911
912
		if ( true !== $all ) {
913
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
914
			$sql_args[] = time() - 3600;
915
		}
916
917
		$sql .= ' ORDER BY `option_id` LIMIT 100';
918
919
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
920
921
		for ( $i = 0; $i < 1000; $i++ ) {
922
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
923
				break;
924
			}
925
		}
926
	}
927
928
	/**
929
	 * Builds the timeout limit for queries talking with the wpcom servers.
930
	 *
931
	 * Based on local php max_execution_time in php.ini
932
	 *
933
	 * @since 5.4
934
	 * @return int
935
	 **/
936
	public function get_max_execution_time() {
937
		$timeout = (int) ini_get( 'max_execution_time' );
938
939
		// Ensure exec time set in php.ini.
940
		if ( ! $timeout ) {
941
			$timeout = 30;
942
		}
943
		return $timeout;
944
	}
945
946
	/**
947
	 * Sets a minimum request timeout, and returns the current timeout
948
	 *
949
	 * @since 5.4
950
	 * @param Integer $min_timeout the minimum timeout value.
951
	 **/
952 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
953
		$timeout = $this->get_max_execution_time();
954
		if ( $timeout < $min_timeout ) {
955
			$timeout = $min_timeout;
956
			set_time_limit( $timeout );
957
		}
958
		return $timeout;
959
	}
960
961
	/**
962
	 * Get our assumed site creation date.
963
	 * Calculated based on the earlier date of either:
964
	 * - Earliest admin user registration date.
965
	 * - Earliest date of post of any post type.
966
	 *
967
	 * @since 7.2.0
968
	 *
969
	 * @return string Assumed site creation date and time.
970
	 */
971 View Code Duplication
	public function get_assumed_site_creation_date() {
972
		$earliest_registered_users  = get_users(
973
			array(
974
				'role'    => 'administrator',
975
				'orderby' => 'user_registered',
976
				'order'   => 'ASC',
977
				'fields'  => array( 'user_registered' ),
978
				'number'  => 1,
979
			)
980
		);
981
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
982
983
		$earliest_posts = get_posts(
984
			array(
985
				'posts_per_page' => 1,
986
				'post_type'      => 'any',
987
				'post_status'    => 'any',
988
				'orderby'        => 'date',
989
				'order'          => 'ASC',
990
			)
991
		);
992
993
		// If there are no posts at all, we'll count only on user registration date.
994
		if ( $earliest_posts ) {
995
			$earliest_post_date = $earliest_posts[0]->post_date;
996
		} else {
997
			$earliest_post_date = PHP_INT_MAX;
998
		}
999
1000
		return min( $earliest_registration_date, $earliest_post_date );
1001
	}
1002
1003
	/**
1004
	 * Adds the activation source string as a parameter to passed arguments.
1005
	 *
1006
	 * @param Array $args arguments that need to have the source added.
1007
	 * @return Array $amended arguments.
1008
	 */
1009 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1010
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1011
1012
		if ( $activation_source_name ) {
1013
			$args['_as'] = urlencode( $activation_source_name );
1014
		}
1015
1016
		if ( $activation_source_keyword ) {
1017
			$args['_ak'] = urlencode( $activation_source_keyword );
1018
		}
1019
1020
		return $args;
1021
	}
1022
1023
	/**
1024
	 * Returns the callable that would be used to generate secrets.
1025
	 *
1026
	 * @return Callable a function that returns a secure string to be used as a secret.
1027
	 */
1028
	protected function get_secret_callable() {
1029
		if ( ! isset( $this->secret_callable ) ) {
1030
			/**
1031
			 * Allows modification of the callable that is used to generate connection secrets.
1032
			 *
1033
			 * @param Callable a function or method that returns a secret string.
1034
			 */
1035
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', 'wp_generate_password' );
1036
		}
1037
1038
		return $this->secret_callable;
1039
	}
1040
1041
	/**
1042
	 * Generates two secret tokens and the end of life timestamp for them.
1043
	 *
1044
	 * @param String  $action  The action name.
1045
	 * @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...
1046
	 * @param Integer $exp     Expiration time in seconds.
1047
	 */
1048
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1049
		$callable = $this->get_secret_callable();
1050
1051
		$secrets = \Jetpack_Options::get_raw_option(
1052
			self::SECRETS_OPTION_NAME,
1053
			array()
1054
		);
1055
1056
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1057
1058
		if (
1059
			isset( $secrets[ $secret_name ] ) &&
1060
			$secrets[ $secret_name ]['exp'] > time()
1061
		) {
1062
			return $secrets[ $secret_name ];
1063
		}
1064
1065
		$secret_value = array(
1066
			'secret_1' => call_user_func( $callable ),
1067
			'secret_2' => call_user_func( $callable ),
1068
			'exp'      => time() + $exp,
1069
		);
1070
1071
		$secrets[ $secret_name ] = $secret_value;
1072
1073
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1074
		return $secrets[ $secret_name ];
1075
	}
1076
1077
	/**
1078
	 * Returns two secret tokens and the end of life timestamp for them.
1079
	 *
1080
	 * @param String  $action  The action name.
1081
	 * @param Integer $user_id The user identifier.
1082
	 * @return string|array an array of secrets or an error string.
1083
	 */
1084
	public function get_secrets( $action, $user_id ) {
1085
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1086
		$secrets     = \Jetpack_Options::get_raw_option(
1087
			self::SECRETS_OPTION_NAME,
1088
			array()
1089
		);
1090
1091
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1092
			return self::SECRETS_MISSING;
1093
		}
1094
1095
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1096
			$this->delete_secrets( $action, $user_id );
1097
			return self::SECRETS_EXPIRED;
1098
		}
1099
1100
		return $secrets[ $secret_name ];
1101
	}
1102
1103
	/**
1104
	 * Deletes secret tokens in case they, for example, have expired.
1105
	 *
1106
	 * @param String  $action  The action name.
1107
	 * @param Integer $user_id The user identifier.
1108
	 */
1109
	public function delete_secrets( $action, $user_id ) {
1110
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1111
		$secrets     = \Jetpack_Options::get_raw_option(
1112
			self::SECRETS_OPTION_NAME,
1113
			array()
1114
		);
1115
		if ( isset( $secrets[ $secret_name ] ) ) {
1116
			unset( $secrets[ $secret_name ] );
1117
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1118
		}
1119
	}
1120
1121
	/**
1122
	 * Responds to a WordPress.com call to register the current site.
1123
	 * Should be changed to protected.
1124
	 *
1125
	 * @param array $registration_data Array of [ secret_1, user_id ].
1126
	 */
1127
	public function handle_registration( array $registration_data ) {
1128
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1129
		if ( empty( $registration_user_id ) ) {
1130
			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...
1131
		}
1132
1133
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1134
	}
1135
1136
	/**
1137
	 * Verify a Previously Generated Secret.
1138
	 *
1139
	 * @param string $action   The type of secret to verify.
1140
	 * @param string $secret_1 The secret string to compare to what is stored.
1141
	 * @param int    $user_id  The user ID of the owner of the secret.
1142
	 */
1143
	protected function verify_secrets( $action, $secret_1, $user_id ) {
1144
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1145
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1146
			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...
1147
		}
1148
1149
		$user = get_user_by( 'id', $user_id );
1150
1151
		/**
1152
		 * We've begun verifying the previously generated secret.
1153
		 *
1154
		 * @since 7.5.0
1155
		 *
1156
		 * @param string   $action The type of secret to verify.
1157
		 * @param \WP_User $user The user object.
1158
		 */
1159
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1160
1161
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1162
			/**
1163
			 * Verifying of the previously generated secret has failed.
1164
			 *
1165
			 * @since 7.5.0
1166
			 *
1167
			 * @param string    $action  The type of secret to verify.
1168
			 * @param \WP_User  $user The user object.
1169
			 * @param \WP_Error $error The error object.
1170
			 */
1171
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1172
1173
			return $error;
1174
		};
1175
1176
		$stored_secrets = $this->get_secrets( $action, $user_id );
1177
		$this->delete_secrets( $action, $user_id );
1178
1179
		if ( empty( $secret_1 ) ) {
1180
			return $return_error(
1181
				new \WP_Error(
1182
					'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...
1183
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1184
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1185
					400
1186
				)
1187
			);
1188
		} elseif ( ! is_string( $secret_1 ) ) {
1189
			return $return_error(
1190
				new \WP_Error(
1191
					'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...
1192
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1193
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1194
					400
1195
				)
1196
			);
1197
		} elseif ( empty( $user_id ) ) {
1198
			// $user_id is passed around during registration as "state".
1199
			return $return_error(
1200
				new \WP_Error(
1201
					'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...
1202
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1203
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1204
					400
1205
				)
1206
			);
1207
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1208
			return $return_error(
1209
				new \WP_Error(
1210
					'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...
1211
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1212
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1213
					400
1214
				)
1215
			);
1216
		}
1217
1218
		if ( ! $stored_secrets ) {
1219
			return $return_error(
1220
				new \WP_Error(
1221
					'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...
1222
					__( 'Verification secrets not found', 'jetpack' ),
1223
					400
1224
				)
1225
			);
1226
		} elseif ( is_wp_error( $stored_secrets ) ) {
1227
			$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...
1228
			return $return_error( $stored_secrets );
1229
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1230
			return $return_error(
1231
				new \WP_Error(
1232
					'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...
1233
					__( 'Verification secrets are incomplete', 'jetpack' ),
1234
					400
1235
				)
1236
			);
1237
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1238
			return $return_error(
1239
				new \WP_Error(
1240
					'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...
1241
					__( 'Secret mismatch', 'jetpack' ),
1242
					400
1243
				)
1244
			);
1245
		}
1246
1247
		/**
1248
		 * We've succeeded at verifying the previously generated secret.
1249
		 *
1250
		 * @since 7.5.0
1251
		 *
1252
		 * @param string   $action The type of secret to verify.
1253
		 * @param \WP_User $user The user object.
1254
		 */
1255
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1256
1257
		return $stored_secrets['secret_2'];
1258
	}
1259
1260
	/**
1261
	 * Responds to a WordPress.com call to authorize the current user.
1262
	 * Should be changed to protected.
1263
	 */
1264
	public function handle_authorization() {
1265
1266
	}
1267
1268
	/**
1269
	 * Builds a URL to the Jetpack connection auth page.
1270
	 * This needs rethinking.
1271
	 *
1272
	 * @param bool        $raw If true, URL will not be escaped.
1273
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
1274
	 *                              If string, will be a custom redirect.
1275
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
1276
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0.
1277
	 *
1278
	 * @return string Connect URL
1279
	 */
1280
	public function build_connect_url( $raw, $redirect, $from, $register ) {
1281
		return array( $raw, $redirect, $from, $register );
1282
	}
1283
1284
	/**
1285
	 * Disconnects from the Jetpack servers.
1286
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1287
	 */
1288
	public function disconnect_site() {
1289
1290
	}
1291
1292
	/**
1293
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1294
	 *
1295
	 * @param string $text The string to hash.
1296
	 * @return string
1297
	 */
1298
	public function sha1_base64( $text ) {
1299
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1300
	}
1301
1302
	/**
1303
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1304
	 *
1305
	 * @param string $domain The domain to check.
1306
	 *
1307
	 * @return bool|WP_Error
1308
	 */
1309
	public function is_usable_domain( $domain ) {
1310
1311
		// If it's empty, just fail out.
1312
		if ( ! $domain ) {
1313
			return new \WP_Error(
1314
				'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...
1315
				/* translators: %1$s is a domain name. */
1316
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1317
			);
1318
		}
1319
1320
		/**
1321
		 * Skips the usuable domain check when connecting a site.
1322
		 *
1323
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1324
		 *
1325
		 * @since 4.1.0
1326
		 *
1327
		 * @param bool If the check should be skipped. Default false.
1328
		 */
1329
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1330
			return true;
1331
		}
1332
1333
		// None of the explicit localhosts.
1334
		$forbidden_domains = array(
1335
			'wordpress.com',
1336
			'localhost',
1337
			'localhost.localdomain',
1338
			'127.0.0.1',
1339
			'local.wordpress.test',         // VVV pattern.
1340
			'local.wordpress-trunk.test',   // VVV pattern.
1341
			'src.wordpress-develop.test',   // VVV pattern.
1342
			'build.wordpress-develop.test', // VVV pattern.
1343
		);
1344 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1345
			return new \WP_Error(
1346
				'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...
1347
				sprintf(
1348
					/* translators: %1$s is a domain name. */
1349
					__(
1350
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1351
						'jetpack'
1352
					),
1353
					$domain
1354
				)
1355
			);
1356
		}
1357
1358
		// No .test or .local domains.
1359 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1360
			return new \WP_Error(
1361
				'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...
1362
				sprintf(
1363
					/* translators: %1$s is a domain name. */
1364
					__(
1365
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1366
						'jetpack'
1367
					),
1368
					$domain
1369
				)
1370
			);
1371
		}
1372
1373
		// No WPCOM subdomains.
1374 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1375
			return new \WP_Error(
1376
				'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...
1377
				sprintf(
1378
					/* translators: %1$s is a domain name. */
1379
					__(
1380
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1381
						'jetpack'
1382
					),
1383
					$domain
1384
				)
1385
			);
1386
		}
1387
1388
		// If PHP was compiled without support for the Filter module (very edge case).
1389
		if ( ! function_exists( 'filter_var' ) ) {
1390
			// Just pass back true for now, and let wpcom sort it out.
1391
			return true;
1392
		}
1393
1394
		return true;
1395
	}
1396
1397
	/**
1398
	 * Gets the requested token.
1399
	 *
1400
	 * Tokens are one of two types:
1401
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
1402
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
1403
	 *    are not associated with a user account. They represent the site's connection with
1404
	 *    the Jetpack servers.
1405
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
1406
	 *
1407
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
1408
	 * token, and $private is a secret that should never be displayed anywhere or sent
1409
	 * over the network; it's used only for signing things.
1410
	 *
1411
	 * Blog Tokens can be "Normal" or "Special".
1412
	 * * Normal: The result of a normal connection flow. They look like
1413
	 *   "{$random_string_1}.{$random_string_2}"
1414
	 *   That is, $token_key and $private are both random strings.
1415
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
1416
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
1417
	 *   constant (rare).
1418
	 * * Special: A connection token for sites that have gone through an alternative
1419
	 *   connection flow. They look like:
1420
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
1421
	 *   That is, $private is a random string and $token_key has a special structure with
1422
	 *   lots of semicolons.
1423
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
1424
	 *   JETPACK_BLOG_TOKEN constant.
1425
	 *
1426
	 * In particular, note that Normal Blog Tokens never start with ";" and that
1427
	 * Special Blog Tokens always do.
1428
	 *
1429
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
1430
	 * order:
1431
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
1432
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
1433
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
1434
	 *
1435
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1436
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1437
	 * @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.
1438
	 *
1439
	 * @return object|false
1440
	 */
1441
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1442
		$possible_special_tokens = array();
1443
		$possible_normal_tokens  = array();
1444
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
1445
1446
		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...
1447
			if ( ! $user_tokens ) {
1448
				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...
1449
			}
1450
			if ( self::JETPACK_MASTER_USER === $user_id ) {
1451
				$user_id = \Jetpack_Options::get_option( 'master_user' );
1452
				if ( ! $user_id ) {
1453
					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...
1454
				}
1455
			}
1456
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
1457
				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...
1458
			}
1459
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
1460
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
1461
				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...
1462
			}
1463
			if ( $user_token_chunks[2] !== (string) $user_id ) {
1464
				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...
1465
			}
1466
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
1467
		} else {
1468
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
1469
			if ( $stored_blog_token ) {
1470
				$possible_normal_tokens[] = $stored_blog_token;
1471
			}
1472
1473
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
1474
1475
			if ( $defined_tokens_string ) {
1476
				$defined_tokens = explode( ',', $defined_tokens_string );
1477
				foreach ( $defined_tokens as $defined_token ) {
1478
					if ( ';' === $defined_token[0] ) {
1479
						$possible_special_tokens[] = $defined_token;
1480
					} else {
1481
						$possible_normal_tokens[] = $defined_token;
1482
					}
1483
				}
1484
			}
1485
		}
1486
1487
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1488
			$possible_tokens = $possible_normal_tokens;
1489
		} else {
1490
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
1491
		}
1492
1493
		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...
1494
			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...
1495
		}
1496
1497
		$valid_token = false;
1498
1499
		if ( false === $token_key ) {
1500
			// Use first token.
1501
			$valid_token = $possible_tokens[0];
1502
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1503
			// Use first normal token.
1504
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
1505
		} else {
1506
			// Use the token matching $token_key or false if none.
1507
			// Ensure we check the full key.
1508
			$token_check = rtrim( $token_key, '.' ) . '.';
1509
1510
			foreach ( $possible_tokens as $possible_token ) {
1511
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
1512
					$valid_token = $possible_token;
1513
					break;
1514
				}
1515
			}
1516
		}
1517
1518
		if ( ! $valid_token ) {
1519
			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...
1520
		}
1521
1522
		return (object) array(
1523
			'secret'           => $valid_token,
1524
			'external_user_id' => (int) $user_id,
1525
		);
1526
	}
1527
1528
	/**
1529
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
1530
	 * since it is passed by reference to various methods.
1531
	 * Capture it here so we can verify the signature later.
1532
	 *
1533
	 * @param Array $methods an array of available XMLRPC methods.
1534
	 * @return Array the same array, since this method doesn't add or remove anything.
1535
	 */
1536
	public function xmlrpc_methods( $methods ) {
1537
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
1538
		return $methods;
1539
	}
1540
1541
	/**
1542
	 * Resets the raw post data parameter for testing purposes.
1543
	 */
1544
	public function reset_raw_post_data() {
1545
		$this->raw_post_data = null;
1546
	}
1547
1548
	/**
1549
	 * Registering an additional method.
1550
	 *
1551
	 * @param Array $methods an array of available XMLRPC methods.
1552
	 * @return Array the amended array in case the method is added.
1553
	 */
1554
	public function public_xmlrpc_methods( $methods ) {
1555
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
1556
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
1557
		}
1558
		return $methods;
1559
	}
1560
1561
	/**
1562
	 * Handles a getOptions XMLRPC method call.
1563
	 *
1564
	 * @param Array $args method call arguments.
1565
	 * @return an amended XMLRPC server options array.
1566
	 */
1567
	public function jetpack_getOptions( $args ) {
1568
		global $wp_xmlrpc_server;
1569
1570
		$wp_xmlrpc_server->escape( $args );
1571
1572
		$username = $args[1];
1573
		$password = $args[2];
1574
1575
		$user = $wp_xmlrpc_server->login( $username, $password );
1576
		if ( ! $user ) {
1577
			return $wp_xmlrpc_server->error;
1578
		}
1579
1580
		$options   = array();
1581
		$user_data = $this->get_connected_user_data();
1582
		if ( is_array( $user_data ) ) {
1583
			$options['jetpack_user_id']         = array(
1584
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
1585
				'readonly' => true,
1586
				'value'    => $user_data['ID'],
1587
			);
1588
			$options['jetpack_user_login']      = array(
1589
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
1590
				'readonly' => true,
1591
				'value'    => $user_data['login'],
1592
			);
1593
			$options['jetpack_user_email']      = array(
1594
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
1595
				'readonly' => true,
1596
				'value'    => $user_data['email'],
1597
			);
1598
			$options['jetpack_user_site_count'] = array(
1599
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
1600
				'readonly' => true,
1601
				'value'    => $user_data['site_count'],
1602
			);
1603
		}
1604
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
1605
		$args                           = stripslashes_deep( $args );
1606
		return $wp_xmlrpc_server->wp_getOptions( $args );
1607
	}
1608
1609
	/**
1610
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
1611
	 *
1612
	 * @param Array $options standard Core options.
1613
	 * @return Array amended options.
1614
	 */
1615
	public function xmlrpc_options( $options ) {
1616
		$jetpack_client_id = false;
1617
		if ( $this->is_active() ) {
1618
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
1619
		}
1620
		$options['jetpack_version'] = array(
1621
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
1622
			'readonly' => true,
1623
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
1624
		);
1625
1626
		$options['jetpack_client_id'] = array(
1627
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
1628
			'readonly' => true,
1629
			'value'    => $jetpack_client_id,
1630
		);
1631
		return $options;
1632
	}
1633
1634
	/**
1635
	 * Resets the saved authentication state in between testing requests.
1636
	 */
1637
	public function reset_saved_auth_state() {
1638
		$this->xmlrpc_verification = null;
1639
	}
1640
}
1641