Completed
Push — update/move_authorize ( c90f72 )
by
unknown
83:16 queued 76:56
created

Manager::authorize()   C

Complexity

Conditions 12
Paths 12

Size

Total Lines 81

Duplication

Lines 7
Ratio 8.64 %

Importance

Changes 0
Metric Value
cc 12
nc 12
nop 1
dl 7
loc 81
rs 5.9878
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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

An additional type check may prevent trouble.

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

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

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

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

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

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

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

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

Loading history...
1308
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1309
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1310
					400
1311
				)
1312
			);
1313
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1314
			$error = $return_error(
1315
				new \WP_Error(
1316
					'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...
1317
					__( 'Verification secrets not found', 'jetpack' ),
1318
					400
1319
				)
1320
			);
1321
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1322
			$error = $return_error(
1323
				new \WP_Error(
1324
					'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...
1325
					__( 'Verification took too long', 'jetpack' ),
1326
					400
1327
				)
1328
			);
1329
		} elseif ( ! $stored_secrets ) {
1330
			$error = $return_error(
1331
				new \WP_Error(
1332
					'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...
1333
					__( 'Verification secrets are empty', 'jetpack' ),
1334
					400
1335
				)
1336
			);
1337
		} elseif ( is_wp_error( $stored_secrets ) ) {
1338
			$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...
1339
			$error = $return_error( $stored_secrets );
1340
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1341
			$error = $return_error(
1342
				new \WP_Error(
1343
					'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...
1344
					__( 'Verification secrets are incomplete', 'jetpack' ),
1345
					400
1346
				)
1347
			);
1348
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1349
			$error = $return_error(
1350
				new \WP_Error(
1351
					'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...
1352
					__( 'Secret mismatch', 'jetpack' ),
1353
					400
1354
				)
1355
			);
1356
		}
1357
1358
		// Something went wrong during the checks, returning the error.
1359
		if ( ! empty( $error ) ) {
1360
			return $error;
1361
		}
1362
1363
		/**
1364
		 * We've succeeded at verifying the previously generated secret.
1365
		 *
1366
		 * @since 7.5.0
1367
		 *
1368
		 * @param string   $action The type of secret to verify.
1369
		 * @param \WP_User $user The user object.
1370
		 */
1371
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1372
1373
		return $stored_secrets['secret_2'];
1374
	}
1375
1376
	/**
1377
	 * Responds to a WordPress.com call to authorize the current user.
1378
	 * Should be changed to protected.
1379
	 */
1380
	public function handle_authorization() {
1381
1382
	}
1383
1384
	/**
1385
	 * Builds a URL to the Jetpack connection auth page.
1386
	 * This needs rethinking.
1387
	 *
1388
	 * @param bool        $raw If true, URL will not be escaped.
1389
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
1390
	 *                              If string, will be a custom redirect.
1391
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
1392
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0.
1393
	 *
1394
	 * @return string Connect URL
1395
	 */
1396
	public function build_connect_url( $raw, $redirect, $from, $register ) {
1397
		return array( $raw, $redirect, $from, $register );
1398
	}
1399
1400
	/**
1401
	 * Authorizes the user by obtaining and storing the user token.
1402
	 *
1403
	 * @param array $data The request data.
1404
	 * @return string|\WP_Error Returns a string on success.
1405
	 *                          Returns a \WP_Error on failure.
1406
	 */
1407
	public function authorize( $data = array() ) {
1408
		/**
1409
		 * Action fired when user authorization starts.
1410
		 *
1411
		 * @since 8.0.0
1412
		 */
1413
		do_action( 'jetpack_authorize_starting' );
1414
1415
		$roles = new Roles();
1416
		$role  = $roles->translate_current_user_to_role();
1417
1418
		if ( ! $role ) {
1419
			return new \WP_Error( 'no_role', 'Invalid request.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_role'.

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

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

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

Loading history...
1420
		}
1421
1422
		$cap = $roles->translate_role_to_cap( $role );
1423
		if ( ! $cap ) {
1424
			return new \WP_Error( 'no_cap', 'Invalid request.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_cap'.

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

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

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

Loading history...
1425
		}
1426
1427
		if ( ! empty( $data['error'] ) ) {
1428
			return new \WP_Error( $data['error'], 'Error included in the request.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $data['error'].

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

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

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

Loading history...
1429
		}
1430
1431
		if ( ! isset( $data['state'] ) ) {
1432
			return new \WP_Error( 'no_state', 'Request must include state.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_state'.

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

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

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

Loading history...
1433
		}
1434
1435
		if ( ! ctype_digit( $data['state'] ) ) {
1436
			return new \WP_Error( $data['error'], 'State must be an integer.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $data['error'].

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

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

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

Loading history...
1437
		}
1438
1439
		$current_user_id = get_current_user_id();
1440
		if ( $current_user_id !== (int) $data['state'] ) {
1441
			return new \WP_Error( 'wrong_state', 'State does not match current user.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wrong_state'.

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

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

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

Loading history...
1442
		}
1443
1444
		if ( empty( $data['code'] ) ) {
1445
			return new \WP_Error( 'no_code', 'Request must include an authorization code.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_code'.

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

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

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

Loading history...
1446
		}
1447
1448
		$client_server = new \Jetpack_Client_Server();
1449
		$token         = $client_server->get_token( $data );
1450
1451 View Code Duplication
		if ( is_wp_error( $token ) ) {
1452
			$code = $token->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<Jetpack_Error>.

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

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

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

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

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

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

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

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

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

Loading history...
1457
		}
1458
1459
		if ( ! $token ) {
1460
			return new \WP_Error( 'no_token', 'Error generating token.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_token'.

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

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

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

Loading history...
1461
		}
1462
1463
		$is_master_user = ! $this->is_active();
1464
1465
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
1466
1467
		if ( ! $is_master_user ) {
1468
			/**
1469
			 * Action fired when a secondary user has been authorized.
1470
			 *
1471
			 * @since 8.0.0
1472
			 */
1473
			do_action( 'jetpack_authorize_ending_linked' );
1474
			return 'linked';
1475
		}
1476
1477
		/**
1478
		 * Action fired when the master user has been authorized.
1479
		 *
1480
		 * @since 8.0.0
1481
		 *
1482
		 * @param array $data The request data.
1483
		 */
1484
		do_action( 'jetpack_authorize_ending_authorized', $data );
1485
1486
		return 'authorized';
1487
	}
1488
1489
	/**
1490
	 * Disconnects from the Jetpack servers.
1491
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1492
	 */
1493
	public function disconnect_site() {
1494
1495
	}
1496
1497
	/**
1498
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1499
	 *
1500
	 * @param string $text The string to hash.
1501
	 * @return string
1502
	 */
1503
	public function sha1_base64( $text ) {
1504
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1505
	}
1506
1507
	/**
1508
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1509
	 *
1510
	 * @param string $domain The domain to check.
1511
	 *
1512
	 * @return bool|WP_Error
1513
	 */
1514
	public function is_usable_domain( $domain ) {
1515
1516
		// If it's empty, just fail out.
1517
		if ( ! $domain ) {
1518
			return new \WP_Error(
1519
				'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...
1520
				/* translators: %1$s is a domain name. */
1521
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1522
			);
1523
		}
1524
1525
		/**
1526
		 * Skips the usuable domain check when connecting a site.
1527
		 *
1528
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1529
		 *
1530
		 * @since 4.1.0
1531
		 *
1532
		 * @param bool If the check should be skipped. Default false.
1533
		 */
1534
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1535
			return true;
1536
		}
1537
1538
		// None of the explicit localhosts.
1539
		$forbidden_domains = array(
1540
			'wordpress.com',
1541
			'localhost',
1542
			'localhost.localdomain',
1543
			'127.0.0.1',
1544
			'local.wordpress.test',         // VVV pattern.
1545
			'local.wordpress-trunk.test',   // VVV pattern.
1546
			'src.wordpress-develop.test',   // VVV pattern.
1547
			'build.wordpress-develop.test', // VVV pattern.
1548
		);
1549 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1550
			return new \WP_Error(
1551
				'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...
1552
				sprintf(
1553
					/* translators: %1$s is a domain name. */
1554
					__(
1555
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1556
						'jetpack'
1557
					),
1558
					$domain
1559
				)
1560
			);
1561
		}
1562
1563
		// No .test or .local domains.
1564 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1565
			return new \WP_Error(
1566
				'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...
1567
				sprintf(
1568
					/* translators: %1$s is a domain name. */
1569
					__(
1570
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1571
						'jetpack'
1572
					),
1573
					$domain
1574
				)
1575
			);
1576
		}
1577
1578
		// No WPCOM subdomains.
1579 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1580
			return new \WP_Error(
1581
				'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...
1582
				sprintf(
1583
					/* translators: %1$s is a domain name. */
1584
					__(
1585
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1586
						'jetpack'
1587
					),
1588
					$domain
1589
				)
1590
			);
1591
		}
1592
1593
		// If PHP was compiled without support for the Filter module (very edge case).
1594
		if ( ! function_exists( 'filter_var' ) ) {
1595
			// Just pass back true for now, and let wpcom sort it out.
1596
			return true;
1597
		}
1598
1599
		return true;
1600
	}
1601
1602
	/**
1603
	 * Gets the requested token.
1604
	 *
1605
	 * Tokens are one of two types:
1606
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
1607
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
1608
	 *    are not associated with a user account. They represent the site's connection with
1609
	 *    the Jetpack servers.
1610
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
1611
	 *
1612
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
1613
	 * token, and $private is a secret that should never be displayed anywhere or sent
1614
	 * over the network; it's used only for signing things.
1615
	 *
1616
	 * Blog Tokens can be "Normal" or "Special".
1617
	 * * Normal: The result of a normal connection flow. They look like
1618
	 *   "{$random_string_1}.{$random_string_2}"
1619
	 *   That is, $token_key and $private are both random strings.
1620
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
1621
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
1622
	 *   constant (rare).
1623
	 * * Special: A connection token for sites that have gone through an alternative
1624
	 *   connection flow. They look like:
1625
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
1626
	 *   That is, $private is a random string and $token_key has a special structure with
1627
	 *   lots of semicolons.
1628
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
1629
	 *   JETPACK_BLOG_TOKEN constant.
1630
	 *
1631
	 * In particular, note that Normal Blog Tokens never start with ";" and that
1632
	 * Special Blog Tokens always do.
1633
	 *
1634
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
1635
	 * order:
1636
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
1637
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
1638
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
1639
	 *
1640
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1641
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1642
	 * @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.
1643
	 *
1644
	 * @return object|false
1645
	 */
1646
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1647
		$possible_special_tokens = array();
1648
		$possible_normal_tokens  = array();
1649
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
1650
1651
		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...
1652
			if ( ! $user_tokens ) {
1653
				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...
1654
			}
1655
			if ( self::JETPACK_MASTER_USER === $user_id ) {
1656
				$user_id = \Jetpack_Options::get_option( 'master_user' );
1657
				if ( ! $user_id ) {
1658
					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...
1659
				}
1660
			}
1661
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
1662
				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...
1663
			}
1664
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
1665 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
1666
				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...
1667
			}
1668 View Code Duplication
			if ( $user_token_chunks[2] !== (string) $user_id ) {
1669
				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...
1670
			}
1671
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
1672
		} else {
1673
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
1674
			if ( $stored_blog_token ) {
1675
				$possible_normal_tokens[] = $stored_blog_token;
1676
			}
1677
1678
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
1679
1680
			if ( $defined_tokens_string ) {
1681
				$defined_tokens = explode( ',', $defined_tokens_string );
1682
				foreach ( $defined_tokens as $defined_token ) {
1683
					if ( ';' === $defined_token[0] ) {
1684
						$possible_special_tokens[] = $defined_token;
1685
					} else {
1686
						$possible_normal_tokens[] = $defined_token;
1687
					}
1688
				}
1689
			}
1690
		}
1691
1692
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1693
			$possible_tokens = $possible_normal_tokens;
1694
		} else {
1695
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
1696
		}
1697
1698
		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...
1699
			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...
1700
		}
1701
1702
		$valid_token = false;
1703
1704
		if ( false === $token_key ) {
1705
			// Use first token.
1706
			$valid_token = $possible_tokens[0];
1707
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1708
			// Use first normal token.
1709
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
1710
		} else {
1711
			// Use the token matching $token_key or false if none.
1712
			// Ensure we check the full key.
1713
			$token_check = rtrim( $token_key, '.' ) . '.';
1714
1715
			foreach ( $possible_tokens as $possible_token ) {
1716
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
1717
					$valid_token = $possible_token;
1718
					break;
1719
				}
1720
			}
1721
		}
1722
1723
		if ( ! $valid_token ) {
1724
			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...
1725
		}
1726
1727
		return (object) array(
1728
			'secret'           => $valid_token,
1729
			'external_user_id' => (int) $user_id,
1730
		);
1731
	}
1732
1733
	/**
1734
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
1735
	 * since it is passed by reference to various methods.
1736
	 * Capture it here so we can verify the signature later.
1737
	 *
1738
	 * @param Array $methods an array of available XMLRPC methods.
1739
	 * @return Array the same array, since this method doesn't add or remove anything.
1740
	 */
1741
	public function xmlrpc_methods( $methods ) {
1742
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
1743
		return $methods;
1744
	}
1745
1746
	/**
1747
	 * Resets the raw post data parameter for testing purposes.
1748
	 */
1749
	public function reset_raw_post_data() {
1750
		$this->raw_post_data = null;
1751
	}
1752
1753
	/**
1754
	 * Registering an additional method.
1755
	 *
1756
	 * @param Array $methods an array of available XMLRPC methods.
1757
	 * @return Array the amended array in case the method is added.
1758
	 */
1759
	public function public_xmlrpc_methods( $methods ) {
1760
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
1761
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
1762
		}
1763
		return $methods;
1764
	}
1765
1766
	/**
1767
	 * Handles a getOptions XMLRPC method call.
1768
	 *
1769
	 * @param Array $args method call arguments.
1770
	 * @return an amended XMLRPC server options array.
1771
	 */
1772
	public function jetpack_get_options( $args ) {
1773
		global $wp_xmlrpc_server;
1774
1775
		$wp_xmlrpc_server->escape( $args );
1776
1777
		$username = $args[1];
1778
		$password = $args[2];
1779
1780
		$user = $wp_xmlrpc_server->login( $username, $password );
1781
		if ( ! $user ) {
1782
			return $wp_xmlrpc_server->error;
1783
		}
1784
1785
		$options   = array();
1786
		$user_data = $this->get_connected_user_data();
1787
		if ( is_array( $user_data ) ) {
1788
			$options['jetpack_user_id']         = array(
1789
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
1790
				'readonly' => true,
1791
				'value'    => $user_data['ID'],
1792
			);
1793
			$options['jetpack_user_login']      = array(
1794
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
1795
				'readonly' => true,
1796
				'value'    => $user_data['login'],
1797
			);
1798
			$options['jetpack_user_email']      = array(
1799
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
1800
				'readonly' => true,
1801
				'value'    => $user_data['email'],
1802
			);
1803
			$options['jetpack_user_site_count'] = array(
1804
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
1805
				'readonly' => true,
1806
				'value'    => $user_data['site_count'],
1807
			);
1808
		}
1809
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
1810
		$args                           = stripslashes_deep( $args );
1811
		return $wp_xmlrpc_server->wp_getOptions( $args );
1812
	}
1813
1814
	/**
1815
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
1816
	 *
1817
	 * @param Array $options standard Core options.
1818
	 * @return Array amended options.
1819
	 */
1820
	public function xmlrpc_options( $options ) {
1821
		$jetpack_client_id = false;
1822
		if ( $this->is_active() ) {
1823
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
1824
		}
1825
		$options['jetpack_version'] = array(
1826
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
1827
			'readonly' => true,
1828
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
1829
		);
1830
1831
		$options['jetpack_client_id'] = array(
1832
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
1833
			'readonly' => true,
1834
			'value'    => $jetpack_client_id,
1835
		);
1836
		return $options;
1837
	}
1838
1839
	/**
1840
	 * Resets the saved authentication state in between testing requests.
1841
	 */
1842
	public function reset_saved_auth_state() {
1843
		$this->xmlrpc_verification = null;
1844
	}
1845
1846
	/**
1847
	 * Sign a user role with the master access token.
1848
	 * If not specified, will default to the current user.
1849
	 *
1850
	 * @access public
1851
	 *
1852
	 * @param string $role    User role.
1853
	 * @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...
1854
	 * @return string Signed user role.
1855
	 */
1856
	public function sign_role( $role, $user_id = null ) {
1857
		if ( empty( $user_id ) ) {
1858
			$user_id = (int) get_current_user_id();
1859
		}
1860
1861
		if ( ! $user_id ) {
1862
			return false;
1863
		}
1864
1865
		$token = $this->get_access_token();
1866
		if ( ! $token || is_wp_error( $token ) ) {
1867
			return false;
1868
		}
1869
1870
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
1871
	}
1872
}
1873