Completed
Push — renovate/pin-dependencies ( 953baf...ee8058 )
by
unknown
07:00
created

Manager::setup_xmlrpc_handlers()   C

Complexity

Conditions 12
Paths 52

Size

Total Lines 78

Duplication

Lines 0
Ratio 0 %

Importance

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