Completed
Push — add/user-authentication ( 651ac4...684086 )
by
unknown
26:10 queued 18:04
created

Manager::setup_xmlrpc_handlers()   C

Complexity

Conditions 12
Paths 52

Size

Total Lines 79

Duplication

Lines 0
Ratio 0 %

Importance

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