Completed
Push — add/delete-connection-owner-no... ( dc993b...d265dd )
by
unknown
07:09
created

Manager::get_connection_owner_id()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
nc 2
nop 0
dl 9
loc 9
rs 9.9666
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
		$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
66
	/**
67
	 * Sets up the XMLRPC request handlers.
68
	 *
69
	 * @param Array                  $request_params incoming request parameters.
70
	 * @param Boolean                $is_active whether the connection is currently active.
71
	 * @param Boolean                $is_signed whether the signature check has been successful.
72
	 * @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...
73
	 */
74
	public function setup_xmlrpc_handlers(
75
		$request_params,
76
		$is_active,
77
		$is_signed,
78
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
79
	) {
80
		if (
81
			! isset( $request_params['for'] )
82
			|| 'jetpack' !== $request_params['for']
83
		) {
84
			return false;
85
		}
86
87
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
88
		if (
89
			isset( $request_params['jetpack'] )
90
			&& 'comms' === $request_params['jetpack']
91
		) {
92
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
93
				// Use the real constant here for WordPress' sake.
94
				define( 'XMLRPC_REQUEST', true );
95
			}
96
97
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
98
99
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
100
		}
101
102
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
103
			return false;
104
		}
105
		// Display errors can cause the XML to be not well formed.
106
		@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...
107
108
		if ( $xmlrpc_server ) {
109
			$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...
110
		} else {
111
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
112
		}
113
114
		$this->require_jetpack_authentication();
115
116
		if ( $is_active ) {
117
			// Hack to preserve $HTTP_RAW_POST_DATA.
118
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
119
120
			if ( $is_signed ) {
121
				// The actual API methods.
122
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
123
			} else {
124
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
125
				// active Jetpack connection, so that additional users can link their account.
126
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
127
			}
128
		} else {
129
			// The bootstrap API methods.
130
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
131
132
			if ( $is_signed ) {
133
				// The jetpack Provision method is available for blog-token-signed requests.
134
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
135
			} else {
136
				new XMLRPC_Connector( $this );
137
			}
138
		}
139
140
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
141
142
		add_action( 'jetpack_clean_nonces', array( $this, 'clean_nonces' ) );
143
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
144
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
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
150
		return true;
151
	}
152
153
	/**
154
	 * Initializes the REST API connector on the init hook.
155
	 */
156
	public function initialize_rest_api_registration_connector() {
157
		new REST_Connector( $this );
158
	}
159
160
	/**
161
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
162
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
163
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
164
	 * which is accessible via a different URI. Most of the below is copied directly
165
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
166
	 *
167
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
168
	 */
169
	public function alternate_xmlrpc() {
170
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
171
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
172
		global $HTTP_RAW_POST_DATA;
173
174
		// Some browser-embedded clients send cookies. We don't want them.
175
		$_COOKIE = array();
176
177
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
178
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
179
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
180
		}
181
182
		// phpcs:enable
183
184
		include_once ABSPATH . 'wp-admin/includes/admin.php';
185
		include_once ABSPATH . WPINC . '/class-IXR.php';
186
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
187
188
		/**
189
		 * Filters the class used for handling XML-RPC requests.
190
		 *
191
		 * @since 3.1.0
192
		 *
193
		 * @param string $class The name of the XML-RPC server class.
194
		 */
195
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
196
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
197
198
		// Fire off the request.
199
		nocache_headers();
200
		$wp_xmlrpc_server->serve_request();
201
202
		exit;
203
	}
204
205
	/**
206
	 * Removes all XML-RPC methods that are not `jetpack.*`.
207
	 * Only used in our alternate XML-RPC endpoint, where we want to
208
	 * ensure that Core and other plugins' methods are not exposed.
209
	 *
210
	 * @param array $methods a list of registered WordPress XMLRPC methods.
211
	 * @return array filtered $methods
212
	 */
213
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
214
		$jetpack_methods = array();
215
216
		foreach ( $methods as $method => $callback ) {
217
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
218
				$jetpack_methods[ $method ] = $callback;
219
			}
220
		}
221
222
		return $jetpack_methods;
223
	}
224
225
	/**
226
	 * Removes all other authentication methods not to allow other
227
	 * methods to validate unauthenticated requests.
228
	 */
229
	public function require_jetpack_authentication() {
230
		// Don't let anyone authenticate.
231
		$_COOKIE = array();
232
		remove_all_filters( 'authenticate' );
233
		remove_all_actions( 'wp_login_failed' );
234
235
		if ( $this->is_active() ) {
236
			// Allow Jetpack authentication.
237
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
238
		}
239
	}
240
241
	/**
242
	 * Authenticates XML-RPC and other requests from the Jetpack Server
243
	 *
244
	 * @param WP_User|Mixed $user user object if authenticated.
245
	 * @param String        $username username.
246
	 * @param String        $password password string.
247
	 * @return WP_User|Mixed authenticated user or error.
248
	 */
249
	public function authenticate_jetpack( $user, $username, $password ) {
250
		if ( is_a( $user, '\\WP_User' ) ) {
251
			return $user;
252
		}
253
254
		$token_details = $this->verify_xml_rpc_signature();
255
256
		if ( ! $token_details ) {
257
			return $user;
258
		}
259
260
		if ( 'user' !== $token_details['type'] ) {
261
			return $user;
262
		}
263
264
		if ( ! $token_details['user_id'] ) {
265
			return $user;
266
		}
267
268
		nocache_headers();
269
270
		return new \WP_User( $token_details['user_id'] );
271
	}
272
273
	/**
274
	 * Verifies the signature of the current request.
275
	 *
276
	 * @return false|array
277
	 */
278
	public function verify_xml_rpc_signature() {
279
		if ( is_null( $this->xmlrpc_verification ) ) {
280
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
281
282
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
283
				/**
284
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
285
				 *
286
				 * Error codes:
287
				 * - malformed_token
288
				 * - malformed_user_id
289
				 * - unknown_token
290
				 * - could_not_sign
291
				 * - invalid_nonce
292
				 * - signature_mismatch
293
				 *
294
				 * @since 7.5.0
295
				 *
296
				 * @param WP_Error $signature_verification_error The verification error
297
				 */
298
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
299
			}
300
		}
301
302
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
303
	}
304
305
	/**
306
	 * Verifies the signature of the current request.
307
	 *
308
	 * This function has side effects and should not be used. Instead,
309
	 * use the memoized version `->verify_xml_rpc_signature()`.
310
	 *
311
	 * @internal
312
	 */
313
	private function internal_verify_xml_rpc_signature() {
314
		// It's not for us.
315
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
316
			return false;
317
		}
318
319
		$signature_details = array(
320
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
321
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
322
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
323
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
324
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
325
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
326
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
327
		);
328
329
		@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...
330
		if (
331
			empty( $token_key )
332
		||
333
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
334
		) {
335
			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...
336
		}
337
338
		if ( '0' === $user_id ) {
339
			$token_type = 'blog';
340
			$user_id    = 0;
341
		} else {
342
			$token_type = 'user';
343
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
344
				return new \WP_Error(
345
					'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...
346
					'Malformed user_id in request',
347
					compact( 'signature_details' )
348
				);
349
			}
350
			$user_id = (int) $user_id;
351
352
			$user = new \WP_User( $user_id );
353
			if ( ! $user || ! $user->exists() ) {
354
				return new \WP_Error(
355
					'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...
356
					sprintf( 'User %d does not exist', $user_id ),
357
					compact( 'signature_details' )
358
				);
359
			}
360
		}
361
362
		$token = $this->get_access_token( $user_id, $token_key, false );
363
		if ( is_wp_error( $token ) ) {
364
			$token->add_data( compact( 'signature_details' ) );
365
			return $token;
366
		} elseif ( ! $token ) {
367
			return new \WP_Error(
368
				'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...
369
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
370
				compact( 'signature_details' )
371
			);
372
		}
373
374
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
375
		// phpcs:disable WordPress.Security.NonceVerification.Missing
376
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
377
			$post_data   = $_POST;
378
			$file_hashes = array();
379
			foreach ( $post_data as $post_data_key => $post_data_value ) {
380
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
381
					continue;
382
				}
383
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
384
				$file_hashes[ $post_data_key ] = $post_data_value;
385
			}
386
387
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
388
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
389
				$post_data[ $post_data_key ] = $post_data_value;
390
			}
391
392
			ksort( $post_data );
393
394
			$body = http_build_query( stripslashes_deep( $post_data ) );
395
		} elseif ( is_null( $this->raw_post_data ) ) {
396
			$body = file_get_contents( 'php://input' );
397
		} else {
398
			$body = null;
399
		}
400
		// phpcs:enable
401
402
		$signature = $jetpack_signature->sign_current_request(
403
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
404
		);
405
406
		$signature_details['url'] = $jetpack_signature->current_request_url;
407
408
		if ( ! $signature ) {
409
			return new \WP_Error(
410
				'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...
411
				'Unknown signature error',
412
				compact( 'signature_details' )
413
			);
414
		} elseif ( is_wp_error( $signature ) ) {
415
			return $signature;
416
		}
417
418
		$timestamp = (int) $_GET['timestamp'];
419
		$nonce     = stripslashes( (string) $_GET['nonce'] );
420
421
		// Use up the nonce regardless of whether the signature matches.
422
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
423
			return new \WP_Error(
424
				'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...
425
				'Could not add nonce',
426
				compact( 'signature_details' )
427
			);
428
		}
429
430
		// Be careful about what you do with this debugging data.
431
		// If a malicious requester has access to the expected signature,
432
		// bad things might be possible.
433
		$signature_details['expected'] = $signature;
434
435
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
436
			return new \WP_Error(
437
				'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...
438
				'Signature mismatch',
439
				compact( 'signature_details' )
440
			);
441
		}
442
443
		/**
444
		 * Action for additional token checking.
445
		 *
446
		 * @since 7.7.0
447
		 *
448
		 * @param Array $post_data request data.
449
		 * @param Array $token_data token data.
450
		 */
451
		return apply_filters(
452
			'jetpack_signature_check_token',
453
			array(
454
				'type'      => $token_type,
455
				'token_key' => $token_key,
456
				'user_id'   => $token->external_user_id,
457
			),
458
			$token,
459
			$this->raw_post_data
460
		);
461
	}
462
463
	/**
464
	 * Returns true if the current site is connected to WordPress.com.
465
	 *
466
	 * @return Boolean is the site connected?
467
	 */
468
	public function is_active() {
469
		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...
470
	}
471
472
	/**
473
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
474
	 *
475
	 * @access public
476
	 *
477
	 * @return bool
478
	 */
479
	public function is_registered() {
480
		$blog_id   = \Jetpack_Options::get_option( 'id' );
481
		$has_token = $this->is_active();
482
		return $blog_id && $has_token;
483
	}
484
485
	/**
486
	 * Checks to see if the connection owner of the site is missing.
487
	 *
488
	 * @return bool
489
	 */
490
	public function is_missing_connection_owner() {
491
		$connection_owner = $this->get_connection_owner_id();
492
		if ( ! get_user_by( 'id', $connection_owner ) ) {
493
			return true;
494
		}
495
496
		return false;
497
	}
498
499
	/**
500
	 * Returns true if the user with the specified identifier is connected to
501
	 * WordPress.com.
502
	 *
503
	 * @param Integer|Boolean $user_id the user identifier.
504
	 * @return Boolean is the user connected?
505
	 */
506
	public function is_user_connected( $user_id = false ) {
507
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
508
		if ( ! $user_id ) {
509
			return false;
510
		}
511
512
		return (bool) $this->get_access_token( $user_id );
513
	}
514
515
	/**
516
	 * Returns the local user ID of the connection owner.
517
	 *
518
	 * @return string|int Returns the ID of the connection owner or False if no connection owner found.
519
	 */
520 View Code Duplication
	public function get_connection_owner_id() {
521
		$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...
522
		$connection_owner = false;
523
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
524
			$connection_owner = $user_token->external_user_id;
525
		}
526
527
		return $connection_owner;
528
	}
529
530
	/**
531
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
532
	 * Able to select by specific capability.
533
	 *
534
	 * @param string The capability of the user
535
	 * @return array Array of WP_User objects if found.
536
	 */
537
	public function get_connected_users( $capability = 'any' ) {
538
		$connected_users    = array();
539
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
540
541
		if ( ! empty( $connected_user_ids ) ) {
542
			foreach ( $connected_user_ids as $id ) {
543
				// Check for capability
544
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
545
					continue;
546
				}
547
548
				$connected_users[] = get_userdata( $id );
549
			}
550
		}
551
552
		return $connected_users;
553
	}
554
555
	/**
556
	 * Get the wpcom user data of the current|specified connected user.
557
	 *
558
	 * @todo Refactor to properly load the XMLRPC client independently.
559
	 *
560
	 * @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...
561
	 * @return Object the user object.
562
	 */
563 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
564
		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...
565
			$user_id = get_current_user_id();
566
		}
567
568
		$transient_key    = "jetpack_connected_user_data_$user_id";
569
		$cached_user_data = get_transient( $transient_key );
570
571
		if ( $cached_user_data ) {
572
			return $cached_user_data;
573
		}
574
575
		$xml = new \Jetpack_IXR_Client(
576
			array(
577
				'user_id' => $user_id,
578
			)
579
		);
580
		$xml->query( 'wpcom.getUser' );
581
		if ( ! $xml->isError() ) {
582
			$user_data = $xml->getResponse();
583
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
584
			return $user_data;
585
		}
586
587
		return false;
588
	}
589
590
	/**
591
	 * Returns a user object of the connection owner.
592
	 *
593
	 * @return object|false False if no connection owner found.
594
	 */
595 View Code Duplication
	public function get_connection_owner() {
596
		$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...
597
598
		$connection_owner = false;
599
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
600
			$connection_owner = get_userdata( $user_token->external_user_id );
601
		}
602
603
		return $connection_owner;
604
	}
605
606
	/**
607
	 * Returns true if the provided user is the Jetpack connection owner.
608
	 * If user ID is not specified, the current user will be used.
609
	 *
610
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
611
	 * @return Boolean True the user the connection owner, false otherwise.
612
	 */
613 View Code Duplication
	public function is_connection_owner( $user_id = false ) {
614
		if ( ! $user_id ) {
615
			$user_id = get_current_user_id();
616
		}
617
618
		$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...
619
620
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
621
	}
622
623
	/**
624
	 * Unlinks the current user from the linked WordPress.com user.
625
	 *
626
	 * @access public
627
	 * @static
628
	 *
629
	 * @todo Refactor to properly load the XMLRPC client independently.
630
	 *
631
	 * @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...
632
	 * @return Boolean Whether the disconnection of the user was successful.
633
	 */
634
	public static function disconnect_user( $user_id = null ) {
635
		$tokens = \Jetpack_Options::get_option( 'user_tokens' );
636
		if ( ! $tokens ) {
637
			return false;
638
		}
639
640
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
641
642
		if ( \Jetpack_Options::get_option( 'master_user' ) === $user_id ) {
643
			return false;
644
		}
645
646
		if ( ! isset( $tokens[ $user_id ] ) ) {
647
			return false;
648
		}
649
650
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
651
		$xml->query( 'jetpack.unlink_user', $user_id );
652
653
		unset( $tokens[ $user_id ] );
654
655
		\Jetpack_Options::update_option( 'user_tokens', $tokens );
656
657
		/**
658
		 * Fires after the current user has been unlinked from WordPress.com.
659
		 *
660
		 * @since 4.1.0
661
		 *
662
		 * @param int $user_id The current user's ID.
663
		 */
664
		do_action( 'jetpack_unlinked_user', $user_id );
665
666
		return true;
667
	}
668
669
	/**
670
	 * Returns the requested Jetpack API URL.
671
	 *
672
	 * @param String $relative_url the relative API path.
673
	 * @return String API URL.
674
	 */
675
	public function api_url( $relative_url ) {
676
		$api_base = Constants::get_constant( 'JETPACK__API_BASE' );
677
		$version  = Constants::get_constant( 'JETPACK__API_VERSION' );
678
679
		$api_base = $api_base ? $api_base : 'https://jetpack.wordpress.com/jetpack.';
680
		$version  = $version ? '/' . $version . '/' : '/1/';
681
682
		return rtrim( $api_base . $relative_url, '/\\' ) . $version;
683
	}
684
685
	/**
686
	 * Attempts Jetpack registration which sets up the site for connection. Should
687
	 * remain public because the call to action comes from the current site, not from
688
	 * WordPress.com.
689
	 *
690
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
691
	 * @return Integer zero on success, or a bitmask on failure.
692
	 */
693
	public function register( $api_endpoint = 'register' ) {
694
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
695
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
696
697
		if (
698
			empty( $secrets['secret_1'] ) ||
699
			empty( $secrets['secret_2'] ) ||
700
			empty( $secrets['exp'] )
701
		) {
702
			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...
703
		}
704
705
		// Better to try (and fail) to set a higher timeout than this system
706
		// supports than to have register fail for more users than it should.
707
		$timeout = $this->set_min_time_limit( 60 ) / 2;
708
709
		$gmt_offset = get_option( 'gmt_offset' );
710
		if ( ! $gmt_offset ) {
711
			$gmt_offset = 0;
712
		}
713
714
		$stats_options = get_option( 'stats_options' );
715
		$stats_id      = isset( $stats_options['blog_id'] )
716
			? $stats_options['blog_id']
717
			: null;
718
719
		/**
720
		 * Filters the request body for additional property addition.
721
		 *
722
		 * @since 7.7.0
723
		 *
724
		 * @param Array $post_data request data.
725
		 * @param Array $token_data token data.
726
		 */
727
		$body = apply_filters(
728
			'jetpack_register_request_body',
729
			array(
730
				'siteurl'         => site_url(),
731
				'home'            => home_url(),
732
				'gmt_offset'      => $gmt_offset,
733
				'timezone_string' => (string) get_option( 'timezone_string' ),
734
				'site_name'       => (string) get_option( 'blogname' ),
735
				'secret_1'        => $secrets['secret_1'],
736
				'secret_2'        => $secrets['secret_2'],
737
				'site_lang'       => get_locale(),
738
				'timeout'         => $timeout,
739
				'stats_id'        => $stats_id,
740
				'state'           => get_current_user_id(),
741
				'site_created'    => $this->get_assumed_site_creation_date(),
742
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
743
			)
744
		);
745
746
		$args = array(
747
			'method'  => 'POST',
748
			'body'    => $body,
749
			'headers' => array(
750
				'Accept' => 'application/json',
751
			),
752
			'timeout' => $timeout,
753
		);
754
755
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
756
757
		// TODO: fix URLs for bad hosts.
758
		$response = Client::_wp_remote_request(
759
			$this->api_url( $api_endpoint ),
760
			$args,
761
			true
762
		);
763
764
		// Make sure the response is valid and does not contain any Jetpack errors.
765
		$registration_details = $this->validate_remote_register_response( $response );
766
767
		if ( is_wp_error( $registration_details ) ) {
768
			return $registration_details;
769
		} elseif ( ! $registration_details ) {
770
			return new \WP_Error(
771
				'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...
772
				'Unknown error registering your Jetpack site.',
773
				wp_remote_retrieve_response_code( $response )
774
			);
775
		}
776
777
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
778
			return new \WP_Error(
779
				'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...
780
				'Unable to validate registration of your Jetpack site.',
781
				wp_remote_retrieve_response_code( $response )
782
			);
783
		}
784
785
		if ( isset( $registration_details->jetpack_public ) ) {
786
			$jetpack_public = (int) $registration_details->jetpack_public;
787
		} else {
788
			$jetpack_public = false;
789
		}
790
791
		\Jetpack_Options::update_options(
792
			array(
793
				'id'         => (int) $registration_details->jetpack_id,
794
				'blog_token' => (string) $registration_details->jetpack_secret,
795
				'public'     => $jetpack_public,
796
			)
797
		);
798
799
		/**
800
		 * Fires when a site is registered on WordPress.com.
801
		 *
802
		 * @since 3.7.0
803
		 *
804
		 * @param int $json->jetpack_id Jetpack Blog ID.
805
		 * @param string $json->jetpack_secret Jetpack Blog Token.
806
		 * @param int|bool $jetpack_public Is the site public.
807
		 */
808
		do_action(
809
			'jetpack_site_registered',
810
			$registration_details->jetpack_id,
811
			$registration_details->jetpack_secret,
812
			$jetpack_public
813
		);
814
815
		if ( isset( $registration_details->token ) ) {
816
			/**
817
			 * Fires when a user token is sent along with the registration data.
818
			 *
819
			 * @since 7.6.0
820
			 *
821
			 * @param object $token the administrator token for the newly registered site.
822
			 */
823
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
824
		}
825
826
		return true;
827
	}
828
829
	/**
830
	 * Takes the response from the Jetpack register new site endpoint and
831
	 * verifies it worked properly.
832
	 *
833
	 * @since 2.6
834
	 *
835
	 * @param Mixed $response the response object, or the error object.
836
	 * @return string|WP_Error A JSON object on success or Jetpack_Error on failures
837
	 **/
838
	protected function validate_remote_register_response( $response ) {
839
		if ( is_wp_error( $response ) ) {
840
			return new \WP_Error(
841
				'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...
842
				$response->get_error_message()
843
			);
844
		}
845
846
		$code   = wp_remote_retrieve_response_code( $response );
847
		$entity = wp_remote_retrieve_body( $response );
848
849
		if ( $entity ) {
850
			$registration_response = json_decode( $entity );
851
		} else {
852
			$registration_response = false;
853
		}
854
855
		$code_type = intval( $code / 100 );
856
		if ( 5 === $code_type ) {
857
			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...
858
		} elseif ( 408 === $code ) {
859
			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...
860
		} elseif ( ! empty( $registration_response->error ) ) {
861
			if (
862
				'xml_rpc-32700' === $registration_response->error
863
				&& ! function_exists( 'xml_parser_create' )
864
			) {
865
				$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' );
866
			} else {
867
				$error_description = isset( $registration_response->error_description )
868
					? (string) $registration_response->error_description
869
					: '';
870
			}
871
872
			return new \WP_Error(
873
				(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...
874
				$error_description,
875
				$code
876
			);
877
		} elseif ( 200 !== $code ) {
878
			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...
879
		}
880
881
		// Jetpack ID error block.
882
		if ( empty( $registration_response->jetpack_id ) ) {
883
			return new \WP_Error(
884
				'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...
885
				/* translators: %s is an error message string */
886
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
887
				$entity
888
			);
889
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
890
			return new \WP_Error(
891
				'jetpack_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

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

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

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

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

Loading history...
899
				/* translators: %s is an error message string */
900
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
901
				$entity
902
			);
903
		}
904
905
		return $registration_response;
906
	}
907
908
	/**
909
	 * Adds a used nonce to a list of known nonces.
910
	 *
911
	 * @param int    $timestamp the current request timestamp.
912
	 * @param string $nonce the nonce value.
913
	 * @return bool whether the nonce is unique or not.
914
	 */
915
	public function add_nonce( $timestamp, $nonce ) {
916
		global $wpdb;
917
		static $nonces_used_this_request = array();
918
919
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
920
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
921
		}
922
923
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
924
		$timestamp = (int) $timestamp;
925
		$nonce     = esc_sql( $nonce );
926
927
		// Raw query so we can avoid races: add_option will also update.
928
		$show_errors = $wpdb->show_errors( false );
929
930
		$old_nonce = $wpdb->get_row(
931
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
932
		);
933
934
		if ( is_null( $old_nonce ) ) {
935
			$return = $wpdb->query(
936
				$wpdb->prepare(
937
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
938
					"jetpack_nonce_{$timestamp}_{$nonce}",
939
					time(),
940
					'no'
941
				)
942
			);
943
		} else {
944
			$return = false;
945
		}
946
947
		$wpdb->show_errors( $show_errors );
948
949
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
950
951
		return $return;
952
	}
953
954
	/**
955
	 * Cleans nonces that were saved when calling ::add_nonce.
956
	 *
957
	 * @todo Properly prepare the query before executing it.
958
	 *
959
	 * @param bool $all whether to clean even non-expired nonces.
960
	 */
961
	public function clean_nonces( $all = false ) {
962
		global $wpdb;
963
964
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
965
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
966
967
		if ( true !== $all ) {
968
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
969
			$sql_args[] = time() - 3600;
970
		}
971
972
		$sql .= ' ORDER BY `option_id` LIMIT 100';
973
974
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
975
976
		for ( $i = 0; $i < 1000; $i++ ) {
977
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
978
				break;
979
			}
980
		}
981
	}
982
983
	/**
984
	 * Builds the timeout limit for queries talking with the wpcom servers.
985
	 *
986
	 * Based on local php max_execution_time in php.ini
987
	 *
988
	 * @since 5.4
989
	 * @return int
990
	 **/
991
	public function get_max_execution_time() {
992
		$timeout = (int) ini_get( 'max_execution_time' );
993
994
		// Ensure exec time set in php.ini.
995
		if ( ! $timeout ) {
996
			$timeout = 30;
997
		}
998
		return $timeout;
999
	}
1000
1001
	/**
1002
	 * Sets a minimum request timeout, and returns the current timeout
1003
	 *
1004
	 * @since 5.4
1005
	 * @param Integer $min_timeout the minimum timeout value.
1006
	 **/
1007 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1008
		$timeout = $this->get_max_execution_time();
1009
		if ( $timeout < $min_timeout ) {
1010
			$timeout = $min_timeout;
1011
			set_time_limit( $timeout );
1012
		}
1013
		return $timeout;
1014
	}
1015
1016
	/**
1017
	 * Get our assumed site creation date.
1018
	 * Calculated based on the earlier date of either:
1019
	 * - Earliest admin user registration date.
1020
	 * - Earliest date of post of any post type.
1021
	 *
1022
	 * @since 7.2.0
1023
	 *
1024
	 * @return string Assumed site creation date and time.
1025
	 */
1026 View Code Duplication
	public function get_assumed_site_creation_date() {
1027
		$earliest_registered_users  = get_users(
1028
			array(
1029
				'role'    => 'administrator',
1030
				'orderby' => 'user_registered',
1031
				'order'   => 'ASC',
1032
				'fields'  => array( 'user_registered' ),
1033
				'number'  => 1,
1034
			)
1035
		);
1036
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1037
1038
		$earliest_posts = get_posts(
1039
			array(
1040
				'posts_per_page' => 1,
1041
				'post_type'      => 'any',
1042
				'post_status'    => 'any',
1043
				'orderby'        => 'date',
1044
				'order'          => 'ASC',
1045
			)
1046
		);
1047
1048
		// If there are no posts at all, we'll count only on user registration date.
1049
		if ( $earliest_posts ) {
1050
			$earliest_post_date = $earliest_posts[0]->post_date;
1051
		} else {
1052
			$earliest_post_date = PHP_INT_MAX;
1053
		}
1054
1055
		return min( $earliest_registration_date, $earliest_post_date );
1056
	}
1057
1058
	/**
1059
	 * Adds the activation source string as a parameter to passed arguments.
1060
	 *
1061
	 * @param Array $args arguments that need to have the source added.
1062
	 * @return Array $amended arguments.
1063
	 */
1064 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1065
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1066
1067
		if ( $activation_source_name ) {
1068
			$args['_as'] = urlencode( $activation_source_name );
1069
		}
1070
1071
		if ( $activation_source_keyword ) {
1072
			$args['_ak'] = urlencode( $activation_source_keyword );
1073
		}
1074
1075
		return $args;
1076
	}
1077
1078
	/**
1079
	 * Returns the callable that would be used to generate secrets.
1080
	 *
1081
	 * @return Callable a function that returns a secure string to be used as a secret.
1082
	 */
1083
	protected function get_secret_callable() {
1084
		if ( ! isset( $this->secret_callable ) ) {
1085
			/**
1086
			 * Allows modification of the callable that is used to generate connection secrets.
1087
			 *
1088
			 * @param Callable a function or method that returns a secret string.
1089
			 */
1090
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', 'wp_generate_password' );
1091
		}
1092
1093
		return $this->secret_callable;
1094
	}
1095
1096
	/**
1097
	 * Generates two secret tokens and the end of life timestamp for them.
1098
	 *
1099
	 * @param String  $action  The action name.
1100
	 * @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...
1101
	 * @param Integer $exp     Expiration time in seconds.
1102
	 */
1103
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1104
		$callable = $this->get_secret_callable();
1105
1106
		$secrets = \Jetpack_Options::get_raw_option(
1107
			self::SECRETS_OPTION_NAME,
1108
			array()
1109
		);
1110
1111
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1112
1113
		if (
1114
			isset( $secrets[ $secret_name ] ) &&
1115
			$secrets[ $secret_name ]['exp'] > time()
1116
		) {
1117
			return $secrets[ $secret_name ];
1118
		}
1119
1120
		$secret_value = array(
1121
			'secret_1' => call_user_func( $callable ),
1122
			'secret_2' => call_user_func( $callable ),
1123
			'exp'      => time() + $exp,
1124
		);
1125
1126
		$secrets[ $secret_name ] = $secret_value;
1127
1128
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1129
		return $secrets[ $secret_name ];
1130
	}
1131
1132
	/**
1133
	 * Returns two secret tokens and the end of life timestamp for them.
1134
	 *
1135
	 * @param String  $action  The action name.
1136
	 * @param Integer $user_id The user identifier.
1137
	 * @return string|array an array of secrets or an error string.
1138
	 */
1139
	public function get_secrets( $action, $user_id ) {
1140
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1141
		$secrets     = \Jetpack_Options::get_raw_option(
1142
			self::SECRETS_OPTION_NAME,
1143
			array()
1144
		);
1145
1146
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1147
			return self::SECRETS_MISSING;
1148
		}
1149
1150
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1151
			$this->delete_secrets( $action, $user_id );
1152
			return self::SECRETS_EXPIRED;
1153
		}
1154
1155
		return $secrets[ $secret_name ];
1156
	}
1157
1158
	/**
1159
	 * Deletes secret tokens in case they, for example, have expired.
1160
	 *
1161
	 * @param String  $action  The action name.
1162
	 * @param Integer $user_id The user identifier.
1163
	 */
1164
	public function delete_secrets( $action, $user_id ) {
1165
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1166
		$secrets     = \Jetpack_Options::get_raw_option(
1167
			self::SECRETS_OPTION_NAME,
1168
			array()
1169
		);
1170
		if ( isset( $secrets[ $secret_name ] ) ) {
1171
			unset( $secrets[ $secret_name ] );
1172
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1173
		}
1174
	}
1175
1176
	/**
1177
	 * Responds to a WordPress.com call to register the current site.
1178
	 * Should be changed to protected.
1179
	 *
1180
	 * @param array $registration_data Array of [ secret_1, user_id ].
1181
	 */
1182
	public function handle_registration( array $registration_data ) {
1183
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1184
		if ( empty( $registration_user_id ) ) {
1185
			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...
1186
		}
1187
1188
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1189
	}
1190
1191
	/**
1192
	 * Verify a Previously Generated Secret.
1193
	 *
1194
	 * @param string $action   The type of secret to verify.
1195
	 * @param string $secret_1 The secret string to compare to what is stored.
1196
	 * @param int    $user_id  The user ID of the owner of the secret.
1197
	 */
1198
	protected function verify_secrets( $action, $secret_1, $user_id ) {
1199
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1200
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1201
			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...
1202
		}
1203
1204
		$user = get_user_by( 'id', $user_id );
1205
1206
		/**
1207
		 * We've begun verifying the previously generated secret.
1208
		 *
1209
		 * @since 7.5.0
1210
		 *
1211
		 * @param string   $action The type of secret to verify.
1212
		 * @param \WP_User $user The user object.
1213
		 */
1214
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1215
1216
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1217
			/**
1218
			 * Verifying of the previously generated secret has failed.
1219
			 *
1220
			 * @since 7.5.0
1221
			 *
1222
			 * @param string    $action  The type of secret to verify.
1223
			 * @param \WP_User  $user The user object.
1224
			 * @param \WP_Error $error The error object.
1225
			 */
1226
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1227
1228
			return $error;
1229
		};
1230
1231
		$stored_secrets = $this->get_secrets( $action, $user_id );
1232
		$this->delete_secrets( $action, $user_id );
1233
1234
		if ( empty( $secret_1 ) ) {
1235
			return $return_error(
1236
				new \WP_Error(
1237
					'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...
1238
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1239
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1240
					400
1241
				)
1242
			);
1243
		} elseif ( ! is_string( $secret_1 ) ) {
1244
			return $return_error(
1245
				new \WP_Error(
1246
					'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...
1247
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1248
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1249
					400
1250
				)
1251
			);
1252
		} elseif ( empty( $user_id ) ) {
1253
			// $user_id is passed around during registration as "state".
1254
			return $return_error(
1255
				new \WP_Error(
1256
					'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...
1257
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1258
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1259
					400
1260
				)
1261
			);
1262
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1263
			return $return_error(
1264
				new \WP_Error(
1265
					'verify_secret_1_malformed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secret_1_malformed'.

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

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

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

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