Completed
Push — add/user-authentication ( 5b501c...0adfb5 )
by Marin
09:51 queued 02:32
created

Manager::is_usable_domain()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 87

Duplication

Lines 39
Ratio 44.83 %

Importance

Changes 0
Metric Value
cc 7
nc 7
nop 1
dl 39
loc 87
rs 7.3503
c 0
b 0
f 0

How to fix   Long Method   

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

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

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

An additional type check may prevent trouble.

Loading history...
58
		);
59
60
		// All the XMLRPC functionality has been moved into setup_xmlrpc_handlers.
61
		if (
62
			! $is_jetpack_xmlrpc_request
63
			&& is_admin()
64
			&& isset( $_POST['action'] ) // phpcs:ignore WordPress.Security.NonceVerification
65
			&& (
66
				'jetpack_upload_file' === $_POST['action']  // phpcs:ignore WordPress.Security.NonceVerification
67
				|| 'jetpack_update_file' === $_POST['action']  // phpcs:ignore WordPress.Security.NonceVerification
68
			)
69
		) {
70
			$this->require_jetpack_authentication();
71
			$this->add_remote_request_handlers();
0 ignored issues
show
Bug introduced by
The method add_remote_request_handlers() does not seem to exist on object<Automattic\Jetpack\Connection\Manager>.

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...
72
			return;
73
		}
74
75
		if ( $this->is_active() ) {
76
			add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
77
			add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
78
		} else {
79
			add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
80
		}
81
	}
82
83
	/**
84
	 * Sets up the XMLRPC request handlers.
85
	 *
86
	 * @param Array                  $request_params incoming request parameters.
87
	 * @param Boolean                $is_active whether the connection is currently active.
88
	 * @param Boolean                $is_signed whether the signature check has been successful.
89
	 * @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...
90
	 */
91
	public function setup_xmlrpc_handlers(
92
		$request_params,
93
		$is_active,
94
		$is_signed,
95
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
96
	) {
97
		if (
98
			! isset( $request_params['for'] )
99
			|| 'jetpack' !== $request_params['for']
100
		) {
101
			return false;
102
		}
103
104
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
105
		if (
106
			isset( $request_params['jetpack'] )
107
			&& 'comms' === $request_params['jetpack']
108
		) {
109
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
110
				// Use the real constant here for WordPress' sake.
111
				define( 'XMLRPC_REQUEST', true );
112
			}
113
114
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
115
116
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
117
		}
118
119
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
120
			return false;
121
		}
122
		// Display errors can cause the XML to be not well formed.
123
		@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...
124
125
		if ( $xmlrpc_server ) {
126
			$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...
127
		} else {
128
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
129
		}
130
131
		$this->require_jetpack_authentication();
132
133
		if ( $is_active ) {
134
			// Hack to preserve $HTTP_RAW_POST_DATA.
135
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
136
137
			if ( $is_signed ) {
138
				// The actual API methods.
139
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
140
			} else {
141
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
142
				// active Jetpack connection, so that additional users can link their account.
143
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
144
			}
145
		} else {
146
			// The bootstrap API methods.
147
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
148
149
			if ( $is_signed ) {
150
				// The jetpack Provision method is available for blog-token-signed requests.
151
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
152
			} else {
153
				new XMLRPC_Connector( $this );
154
			}
155
		}
156
157
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
158
159
		add_action( 'jetpack_clean_nonces', array( $this, 'clean_nonces' ) );
160
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
161
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
162
		}
163
164
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
165
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
166
167
		return true;
168
	}
169
170
	/**
171
	 * Initializes the REST API connector on the init hook.
172
	 */
173
	public function initialize_rest_api_registration_connector() {
174
		new REST_Connector( $this );
175
	}
176
177
	/**
178
	 * Initializes all needed hooks and request handlers. Handles API calls, upload
179
	 * requests, authentication requests. Also XMLRPC options requests.
180
	 * Fallback XMLRPC is also a bridge, but probably can be a class that inherits
181
	 * this one. Among other things it should strip existing methods.
182
	 *
183
	 * @param Array $methods an array of API method names for the Connection to accept and
184
	 *                       pass on to existing callables. It's possible to specify whether
185
	 *                       each method should be available for unauthenticated calls or not.
186
	 * @see Jetpack::__construct
187
	 */
188
	public function initialize( $methods ) {
189
		$methods;
190
	}
191
192
	/**
193
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
194
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
195
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
196
	 * which is accessible via a different URI. Most of the below is copied directly
197
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
198
	 */
199
	public function alternate_xmlrpc() {
200
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
201
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
202
		global $HTTP_RAW_POST_DATA;
203
204
		// Some browser-embedded clients send cookies. We don't want them.
205
		$_COOKIE = array();
206
207
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
208
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
209
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
210
		}
211
212
		// phpcs:enable
213
214
		include_once ABSPATH . 'wp-admin/includes/admin.php';
215
		include_once ABSPATH . WPINC . '/class-IXR.php';
216
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
217
218
		/**
219
		 * Filters the class used for handling XML-RPC requests.
220
		 *
221
		 * @since 3.1.0
222
		 *
223
		 * @param string $class The name of the XML-RPC server class.
224
		 */
225
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
226
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
227
228
		// Fire off the request.
229
		nocache_headers();
230
		$wp_xmlrpc_server->serve_request();
231
232
		exit;
233
	}
234
235
	/**
236
	 * Removes all XML-RPC methods that are not `jetpack.*`.
237
	 * Only used in our alternate XML-RPC endpoint, where we want to
238
	 * ensure that Core and other plugins' methods are not exposed.
239
	 *
240
	 * @param array $methods a list of registered WordPress XMLRPC methods.
241
	 * @return array filtered $methods
242
	 */
243
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
244
		$jetpack_methods = array();
245
246
		foreach ( $methods as $method => $callback ) {
247
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
248
				$jetpack_methods[ $method ] = $callback;
249
			}
250
		}
251
252
		return $jetpack_methods;
253
	}
254
255
	/**
256
	 * Removes all other authentication methods not to allow other
257
	 * methods to validate unauthenticated requests.
258
	 */
259
	public function require_jetpack_authentication() {
260
		// Don't let anyone authenticate.
261
		$_COOKIE = array();
262
		remove_all_filters( 'authenticate' );
263
		remove_all_actions( 'wp_login_failed' );
264
265
		if ( $this->is_active() ) {
266
			// Allow Jetpack authentication.
267
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
268
		}
269
	}
270
271
	/**
272
	 * Authenticates XML-RPC and other requests from the Jetpack Server
273
	 *
274
	 * @param WP_User|Mixed $user user object if authenticated.
275
	 * @param String        $username username.
276
	 * @param String        $password password string.
277
	 * @return WP_User|Mixed authenticated user or error.
278
	 */
279
	public function authenticate_jetpack( $user, $username, $password ) {
280
		if ( is_a( $user, '\WP_User' ) ) {
281
			return $user;
282
		}
283
284
		$token_details = $this->verify_xml_rpc_signature();
285
286
		if ( ! $token_details ) {
287
			return $user;
288
		}
289
290
		if ( 'user' !== $token_details['type'] ) {
291
			return $user;
292
		}
293
294
		if ( ! $token_details['user_id'] ) {
295
			return $user;
296
		}
297
298
		nocache_headers();
299
300
		return new \WP_User( $token_details['user_id'] );
301
	}
302
303
	/**
304
	 * Verifies the signature of the current request.
305
	 *
306
	 * @return false|array
307
	 */
308
	public function verify_xml_rpc_signature() {
309
		if ( is_null( $this->xmlrpc_verification ) ) {
310
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
311
312
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
313
				/**
314
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
315
				 *
316
				 * Error codes:
317
				 * - malformed_token
318
				 * - malformed_user_id
319
				 * - unknown_token
320
				 * - could_not_sign
321
				 * - invalid_nonce
322
				 * - signature_mismatch
323
				 *
324
				 * @since 7.5.0
325
				 *
326
				 * @param WP_Error $signature_verification_error The verification error
327
				 */
328
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
329
			}
330
		}
331
332
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
333
	}
334
335
	/**
336
	 * Verifies the signature of the current request.
337
	 *
338
	 * This function has side effects and should not be used. Instead,
339
	 * use the memoized version `->verify_xml_rpc_signature()`.
340
	 *
341
	 * @internal
342
	 */
343
	private function internal_verify_xml_rpc_signature() {
344
		// It's not for us.
345
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
346
			return false;
347
		}
348
349
		$signature_details = array(
350
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
351
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
352
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
353
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
354
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
355
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
356
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
357
		);
358
359
		@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...
360
		if (
361
			empty( $token_key )
362
		||
363
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
364
		) {
365
			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...
366
		}
367
368
		if ( '0' === $user_id ) {
369
			$token_type = 'blog';
370
			$user_id    = 0;
371
		} else {
372
			$token_type = 'user';
373
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
374
				return new \WP_Error(
375
					'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...
376
					'Malformed user_id in request',
377
					compact( 'signature_details' )
378
				);
379
			}
380
			$user_id = (int) $user_id;
381
382
			$user = new \WP_User( $user_id );
383
			if ( ! $user || ! $user->exists() ) {
384
				return new \WP_Error(
385
					'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...
386
					sprintf( 'User %d does not exist', $user_id ),
387
					compact( 'signature_details' )
388
				);
389
			}
390
		}
391
392
		$token = $this->get_access_token( $user_id, $token_key, false );
393
		if ( is_wp_error( $token ) ) {
394
			$token->add_data( compact( 'signature_details' ) );
395
			return $token;
396
		} elseif ( ! $token ) {
397
			return new \WP_Error(
398
				'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...
399
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
400
				compact( 'signature_details' )
401
			);
402
		}
403
404
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
405
		// phpcs:disable WordPress.Security.NonceVerification.Missing
406
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
407
			$post_data   = $_POST;
408
			$file_hashes = array();
409
			foreach ( $post_data as $post_data_key => $post_data_value ) {
410
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
411
					continue;
412
				}
413
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
414
				$file_hashes[ $post_data_key ] = $post_data_value;
415
			}
416
417
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
418
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
419
				$post_data[ $post_data_key ] = $post_data_value;
420
			}
421
422
			ksort( $post_data );
423
424
			$body = http_build_query( stripslashes_deep( $post_data ) );
425
		} elseif ( is_null( $this->raw_post_data ) ) {
426
			$body = file_get_contents( 'php://input' );
427
		} else {
428
			$body = null;
429
		}
430
		// phpcs:enable
431
432
		$signature = $jetpack_signature->sign_current_request(
433
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
434
		);
435
436
		$signature_details['url'] = $jetpack_signature->current_request_url;
437
438
		if ( ! $signature ) {
439
			return new \WP_Error(
440
				'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...
441
				'Unknown signature error',
442
				compact( 'signature_details' )
443
			);
444
		} elseif ( is_wp_error( $signature ) ) {
445
			return $signature;
446
		}
447
448
		$timestamp = (int) $_GET['timestamp'];
449
		$nonce     = stripslashes( (string) $_GET['nonce'] );
450
451
		// Use up the nonce regardless of whether the signature matches.
452
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
453
			return new \WP_Error(
454
				'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...
455
				'Could not add nonce',
456
				compact( 'signature_details' )
457
			);
458
		}
459
460
		// Be careful about what you do with this debugging data.
461
		// If a malicious requester has access to the expected signature,
462
		// bad things might be possible.
463
		$signature_details['expected'] = $signature;
464
465
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
466
			return new \WP_Error(
467
				'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...
468
				'Signature mismatch',
469
				compact( 'signature_details' )
470
			);
471
		}
472
473
		/**
474
		 * Action for additional token checking.
475
		 *
476
		 * @since 7.7.0
477
		 *
478
		 * @param Array $post_data request data.
479
		 * @param Array $token_data token data.
480
		 */
481
		return apply_filters(
482
			'jetpack_signature_check_token',
483
			array(
484
				'type'      => $token_type,
485
				'token_key' => $token_key,
486
				'user_id'   => $token->external_user_id,
487
			),
488
			$token,
489
			$this->raw_post_data
490
		);
491
	}
492
493
	/**
494
	 * Returns true if the current site is connected to WordPress.com.
495
	 *
496
	 * @return Boolean is the site connected?
497
	 */
498
	public function is_active() {
499
		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...
500
	}
501
502
	/**
503
	 * Returns true if the user with the specified identifier is connected to
504
	 * WordPress.com.
505
	 *
506
	 * @param Integer|Boolean $user_id the user identifier.
507
	 * @return Boolean is the user connected?
508
	 */
509
	public function is_user_connected( $user_id = false ) {
510
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
511
		if ( ! $user_id ) {
512
			return false;
513
		}
514
515
		return (bool) $this->get_access_token( $user_id );
516
	}
517
518
	/**
519
	 * Get the wpcom user data of the current|specified connected user.
520
	 *
521
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

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

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

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

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

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