Completed
Push — add/layout-for-widgetless-over... ( 1fed47...f2b0fc )
by
unknown
10:50 queued 03:04
created

Manager::xmlrpc_api_url()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * The Jetpack Connection manager class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Tracking;
13
use WP_Error;
14
15
/**
16
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
17
 * and Jetpack.
18
 */
19
class Manager {
20
21
	const SECRETS_MISSING        = 'secrets_missing';
22
	const SECRETS_EXPIRED        = 'secrets_expired';
23
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
24
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
25
	const JETPACK_MASTER_USER    = true;
26
27
	/**
28
	 * The procedure that should be run to generate secrets.
29
	 *
30
	 * @var Callable
31
	 */
32
	protected $secret_callable;
33
34
	/**
35
	 * A copy of the raw POST data for signature verification purposes.
36
	 *
37
	 * @var String
38
	 */
39
	protected $raw_post_data;
40
41
	/**
42
	 * Verification data needs to be stored to properly verify everything.
43
	 *
44
	 * @var Object
45
	 */
46
	private $xmlrpc_verification = null;
47
48
	/**
49
	 * Plugin management object.
50
	 *
51
	 * @var Plugin
52
	 */
53
	private $plugin = null;
54
55
	/**
56
	 * Initialize the object.
57
	 * Make sure to call the "Configure" first.
58
	 *
59
	 * @param string $plugin_slug Slug of the plugin using the connection (optional, but encouraged).
0 ignored issues
show
Documentation introduced by
Should the type for parameter $plugin_slug not be string|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...
60
	 *
61
	 * @see \Automattic\Jetpack\Config
62
	 */
63
	public function __construct( $plugin_slug = null ) {
64
		if ( $plugin_slug && is_string( $plugin_slug ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $plugin_slug of type string|null is loosely compared to true; this is ambiguous if the string can be empty. 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 string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
65
			$this->set_plugin_instance( new Plugin( $plugin_slug ) );
66
		}
67
	}
68
69
	/**
70
	 * Initializes required listeners. This is done separately from the constructors
71
	 * because some objects sometimes need to instantiate separate objects of this class.
72
	 *
73
	 * @todo Implement a proper nonce verification.
74
	 */
75
	public static function configure() {
76
		$manager = new self();
77
78
		$manager->setup_xmlrpc_handlers(
79
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
80
			$manager->is_active(),
81
			$manager->verify_xml_rpc_signature()
0 ignored issues
show
Bug introduced by
It seems like $manager->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...
82
		);
83
84
		if ( $manager->is_active() ) {
85
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
86
		} else {
87
			add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
88
		}
89
90
		add_action( 'jetpack_clean_nonces', array( $manager, 'clean_nonces' ) );
91
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
92
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
93
		}
94
95
		add_filter(
96
			'jetpack_constant_default_value',
97
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
98
			10,
99
			2
100
		);
101
102
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
103
104
	}
105
106
	/**
107
	 * Sets up the XMLRPC request handlers.
108
	 *
109
	 * @param array                  $request_params incoming request parameters.
110
	 * @param Boolean                $is_active whether the connection is currently active.
111
	 * @param Boolean                $is_signed whether the signature check has been successful.
112
	 * @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...
113
	 */
114
	public function setup_xmlrpc_handlers(
115
		$request_params,
116
		$is_active,
117
		$is_signed,
118
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
119
	) {
120
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
121
122
		if (
123
			! isset( $request_params['for'] )
124
			|| 'jetpack' !== $request_params['for']
125
		) {
126
			return false;
127
		}
128
129
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
130
		if (
131
			isset( $request_params['jetpack'] )
132
			&& 'comms' === $request_params['jetpack']
133
		) {
134
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
135
				// Use the real constant here for WordPress' sake.
136
				define( 'XMLRPC_REQUEST', true );
137
			}
138
139
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
140
141
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
142
		}
143
144
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
145
			return false;
146
		}
147
		// Display errors can cause the XML to be not well formed.
148
		@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...
149
150
		if ( $xmlrpc_server ) {
151
			$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...
152
		} else {
153
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
154
		}
155
156
		$this->require_jetpack_authentication();
157
158
		if ( $is_active ) {
159
			// Hack to preserve $HTTP_RAW_POST_DATA.
160
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
161
162
			if ( $is_signed ) {
163
				// The actual API methods.
164
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
165
			} else {
166
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
167
				// active Jetpack connection, so that additional users can link their account.
168
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
169
			}
170
		} else {
171
			// The bootstrap API methods.
172
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
173
174
			if ( $is_signed ) {
175
				// The jetpack Provision method is available for blog-token-signed requests.
176
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
177
			} else {
178
				new XMLRPC_Connector( $this );
179
			}
180
		}
181
182
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
183
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
184
		return true;
185
	}
186
187
	/**
188
	 * Initializes the REST API connector on the init hook.
189
	 */
190
	public function initialize_rest_api_registration_connector() {
191
		new REST_Connector( $this );
192
	}
193
194
	/**
195
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
196
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
197
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
198
	 * which is accessible via a different URI. Most of the below is copied directly
199
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
200
	 *
201
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
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 fix for mozBlog and other cases where '<?xml' isn't on the very first line.
212
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
213
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
214
		}
215
216
		// phpcs:enable
217
218
		include_once ABSPATH . 'wp-admin/includes/admin.php';
219
		include_once ABSPATH . WPINC . '/class-IXR.php';
220
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
221
222
		/**
223
		 * Filters the class used for handling XML-RPC requests.
224
		 *
225
		 * @since 3.1.0
226
		 *
227
		 * @param string $class The name of the XML-RPC server class.
228
		 */
229
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
230
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
231
232
		// Fire off the request.
233
		nocache_headers();
234
		$wp_xmlrpc_server->serve_request();
235
236
		exit;
237
	}
238
239
	/**
240
	 * Removes all XML-RPC methods that are not `jetpack.*`.
241
	 * Only used in our alternate XML-RPC endpoint, where we want to
242
	 * ensure that Core and other plugins' methods are not exposed.
243
	 *
244
	 * @param array $methods a list of registered WordPress XMLRPC methods.
245
	 * @return array filtered $methods
246
	 */
247
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
248
		$jetpack_methods = array();
249
250
		foreach ( $methods as $method => $callback ) {
251
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
252
				$jetpack_methods[ $method ] = $callback;
253
			}
254
		}
255
256
		return $jetpack_methods;
257
	}
258
259
	/**
260
	 * Removes all other authentication methods not to allow other
261
	 * methods to validate unauthenticated requests.
262
	 */
263
	public function require_jetpack_authentication() {
264
		// Don't let anyone authenticate.
265
		$_COOKIE = array();
266
		remove_all_filters( 'authenticate' );
267
		remove_all_actions( 'wp_login_failed' );
268
269
		if ( $this->is_active() ) {
270
			// Allow Jetpack authentication.
271
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
272
		}
273
	}
274
275
	/**
276
	 * Authenticates XML-RPC and other requests from the Jetpack Server
277
	 *
278
	 * @param WP_User|Mixed $user user object if authenticated.
279
	 * @param String        $username username.
280
	 * @param String        $password password string.
281
	 * @return WP_User|Mixed authenticated user or error.
282
	 */
283
	public function authenticate_jetpack( $user, $username, $password ) {
284
		if ( is_a( $user, '\\WP_User' ) ) {
285
			return $user;
286
		}
287
288
		$token_details = $this->verify_xml_rpc_signature();
289
290
		if ( ! $token_details ) {
291
			return $user;
292
		}
293
294
		if ( 'user' !== $token_details['type'] ) {
295
			return $user;
296
		}
297
298
		if ( ! $token_details['user_id'] ) {
299
			return $user;
300
		}
301
302
		nocache_headers();
303
304
		return new \WP_User( $token_details['user_id'] );
305
	}
306
307
	/**
308
	 * Verifies the signature of the current request.
309
	 *
310
	 * @return false|array
311
	 */
312
	public function verify_xml_rpc_signature() {
313
		if ( is_null( $this->xmlrpc_verification ) ) {
314
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
315
316
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
317
				/**
318
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
319
				 *
320
				 * Error codes:
321
				 * - malformed_token
322
				 * - malformed_user_id
323
				 * - unknown_token
324
				 * - could_not_sign
325
				 * - invalid_nonce
326
				 * - signature_mismatch
327
				 *
328
				 * @since 7.5.0
329
				 *
330
				 * @param WP_Error $signature_verification_error The verification error
331
				 */
332
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
333
			}
334
		}
335
336
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
337
	}
338
339
	/**
340
	 * Verifies the signature of the current request.
341
	 *
342
	 * This function has side effects and should not be used. Instead,
343
	 * use the memoized version `->verify_xml_rpc_signature()`.
344
	 *
345
	 * @internal
346
	 * @todo Refactor to use proper nonce verification.
347
	 */
348
	private function internal_verify_xml_rpc_signature() {
349
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
350
		// It's not for us.
351
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
352
			return false;
353
		}
354
355
		$signature_details = array(
356
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
357
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
358
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
359
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
360
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
361
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
362
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
363
		);
364
365
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
366
		@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...
367
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
368
369
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
370
371
		if (
372
			empty( $token_key )
373
		||
374
			empty( $version ) || strval( $jetpack_api_version ) !== $version ) {
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
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
459
		$timestamp = (int) $_GET['timestamp'];
460
		$nonce     = stripslashes( (string) $_GET['nonce'] );
461
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
462
463
		// Use up the nonce regardless of whether the signature matches.
464
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
465
			return new \WP_Error(
466
				'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...
467
				'Could not add nonce',
468
				compact( 'signature_details' )
469
			);
470
		}
471
472
		// Be careful about what you do with this debugging data.
473
		// If a malicious requester has access to the expected signature,
474
		// bad things might be possible.
475
		$signature_details['expected'] = $signature;
476
477
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
478
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
479
			return new \WP_Error(
480
				'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...
481
				'Signature mismatch',
482
				compact( 'signature_details' )
483
			);
484
		}
485
486
		/**
487
		 * Action for additional token checking.
488
		 *
489
		 * @since 7.7.0
490
		 *
491
		 * @param array $post_data request data.
492
		 * @param array $token_data token data.
493
		 */
494
		return apply_filters(
495
			'jetpack_signature_check_token',
496
			array(
497
				'type'      => $token_type,
498
				'token_key' => $token_key,
499
				'user_id'   => $token->external_user_id,
500
			),
501
			$token,
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $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...
502
			$this->raw_post_data
503
		);
504
	}
505
506
	/**
507
	 * Returns true if the current site is connected to WordPress.com.
508
	 *
509
	 * @return Boolean is the site connected?
510
	 */
511
	public function is_active() {
512
		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...
513
	}
514
515
	/**
516
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
517
	 *
518
	 * @access public
519
	 *
520
	 * @return bool
521
	 */
522
	public function is_registered() {
523
		$blog_id   = \Jetpack_Options::get_option( 'id' );
524
		$has_token = $this->is_active();
525
		return $blog_id && $has_token;
526
	}
527
528
	/**
529
	 * Checks to see if the connection owner of the site is missing.
530
	 *
531
	 * @return bool
532
	 */
533
	public function is_missing_connection_owner() {
534
		$connection_owner = $this->get_connection_owner_id();
535
		if ( ! get_user_by( 'id', $connection_owner ) ) {
536
			return true;
537
		}
538
539
		return false;
540
	}
541
542
	/**
543
	 * Returns true if the user with the specified identifier is connected to
544
	 * WordPress.com.
545
	 *
546
	 * @param Integer|Boolean $user_id the user identifier.
547
	 * @return Boolean is the user connected?
548
	 */
549
	public function is_user_connected( $user_id = false ) {
550
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
551
		if ( ! $user_id ) {
552
			return false;
553
		}
554
555
		return (bool) $this->get_access_token( $user_id );
556
	}
557
558
	/**
559
	 * Returns the local user ID of the connection owner.
560
	 *
561
	 * @return string|int Returns the ID of the connection owner or False if no connection owner found.
562
	 */
563 View Code Duplication
	public function get_connection_owner_id() {
564
		$user_token       = $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...
565
		$connection_owner = false;
566
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
567
			$connection_owner = $user_token->external_user_id;
568
		}
569
570
		return $connection_owner;
571
	}
572
573
	/**
574
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
575
	 * Able to select by specific capability.
576
	 *
577
	 * @param string $capability The capability of the user.
578
	 * @return array Array of WP_User objects if found.
579
	 */
580
	public function get_connected_users( $capability = 'any' ) {
581
		$connected_users    = array();
582
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
583
584
		if ( ! empty( $connected_user_ids ) ) {
585
			foreach ( $connected_user_ids as $id ) {
586
				// Check for capability.
587
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
588
					continue;
589
				}
590
591
				$connected_users[] = get_userdata( $id );
592
			}
593
		}
594
595
		return $connected_users;
596
	}
597
598
	/**
599
	 * Get the wpcom user data of the current|specified connected user.
600
	 *
601
	 * @todo Refactor to properly load the XMLRPC client independently.
602
	 *
603
	 * @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...
604
	 * @return Object the user object.
605
	 */
606 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
607
		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...
608
			$user_id = get_current_user_id();
609
		}
610
611
		$transient_key    = "jetpack_connected_user_data_$user_id";
612
		$cached_user_data = get_transient( $transient_key );
613
614
		if ( $cached_user_data ) {
615
			return $cached_user_data;
616
		}
617
618
		$xml = new \Jetpack_IXR_Client(
619
			array(
620
				'user_id' => $user_id,
621
			)
622
		);
623
		$xml->query( 'wpcom.getUser' );
624
		if ( ! $xml->isError() ) {
625
			$user_data = $xml->getResponse();
626
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
627
			return $user_data;
628
		}
629
630
		return false;
631
	}
632
633
	/**
634
	 * Returns a user object of the connection owner.
635
	 *
636
	 * @return object|false False if no connection owner found.
637
	 */
638 View Code Duplication
	public function get_connection_owner() {
639
		$user_token = $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...
640
641
		$connection_owner = false;
642
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
643
			$connection_owner = get_userdata( $user_token->external_user_id );
644
		}
645
646
		return $connection_owner;
647
	}
648
649
	/**
650
	 * Returns true if the provided user is the Jetpack connection owner.
651
	 * If user ID is not specified, the current user will be used.
652
	 *
653
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
654
	 * @return Boolean True the user the connection owner, false otherwise.
655
	 */
656 View Code Duplication
	public function is_connection_owner( $user_id = false ) {
657
		if ( ! $user_id ) {
658
			$user_id = get_current_user_id();
659
		}
660
661
		$user_token = $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...
662
663
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
664
	}
665
666
	/**
667
	 * Connects the user with a specified ID to a WordPress.com user using the
668
	 * remote login flow.
669
	 *
670
	 * @access public
671
	 *
672
	 * @param Integer $user_id (optional) the user identifier, defaults to current user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
673
	 * @param String  $redirect_url the URL to redirect the user to for processing, defaults to
0 ignored issues
show
Documentation introduced by
Should the type for parameter $redirect_url not be string|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...
674
	 *                              admin_url().
675
	 * @return WP_Error only in case of a failed user lookup.
676
	 */
677
	public function connect_user( $user_id = null, $redirect_url = null ) {
678
		$user = null;
0 ignored issues
show
Unused Code introduced by
$user is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
679
		if ( null === $user_id ) {
680
			$user = wp_get_current_user();
681
		} else {
682
			$user = get_user_by( 'ID', $user_id );
683
		}
684
685
		if ( empty( $user ) ) {
686
			return new \WP_Error( 'user_not_found', 'Attempting to connect a non-existent user.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_not_found'.

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...
687
		}
688
689
		if ( null === $redirect_url ) {
690
			$redirect_url = admin_url();
0 ignored issues
show
Unused Code introduced by
$redirect_url is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
691
		}
692
693
		// Using wp_redirect intentionally because we're redirecting outside.
694
		wp_redirect( $this->get_authorization_url( $user ) ); // phpcs:ignore WordPress.Security.SafeRedirect
695
		exit();
696
	}
697
698
	/**
699
	 * Unlinks the current user from the linked WordPress.com user.
700
	 *
701
	 * @access public
702
	 * @static
703
	 *
704
	 * @todo Refactor to properly load the XMLRPC client independently.
705
	 *
706
	 * @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...
707
	 * @return Boolean Whether the disconnection of the user was successful.
708
	 */
709
	public static function disconnect_user( $user_id = null ) {
710
		$tokens = \Jetpack_Options::get_option( 'user_tokens' );
711
		if ( ! $tokens ) {
712
			return false;
713
		}
714
715
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
716
717
		if ( \Jetpack_Options::get_option( 'master_user' ) === $user_id ) {
718
			return false;
719
		}
720
721
		if ( ! isset( $tokens[ $user_id ] ) ) {
722
			return false;
723
		}
724
725
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
726
		$xml->query( 'jetpack.unlink_user', $user_id );
727
728
		unset( $tokens[ $user_id ] );
729
730
		\Jetpack_Options::update_option( 'user_tokens', $tokens );
731
732
		/**
733
		 * Fires after the current user has been unlinked from WordPress.com.
734
		 *
735
		 * @since 4.1.0
736
		 *
737
		 * @param int $user_id The current user's ID.
738
		 */
739
		do_action( 'jetpack_unlinked_user', $user_id );
740
741
		return true;
742
	}
743
744
	/**
745
	 * Returns the requested Jetpack API URL.
746
	 *
747
	 * @param String $relative_url the relative API path.
748
	 * @return String API URL.
749
	 */
750
	public function api_url( $relative_url ) {
751
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
752
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
753
754
		/**
755
		 * Filters whether the connection manager should use the iframe authorization
756
		 * flow instead of the regular redirect-based flow.
757
		 *
758
		 * @since 8.3.0
759
		 *
760
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
761
		 */
762
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
763
764
		// Do not modify anything that is not related to authorize requests.
765
		if ( 'authorize' === $relative_url && $iframe_flow ) {
766
			$relative_url = 'authorize_iframe';
767
		}
768
769
		/**
770
		 * Filters the API URL that Jetpack uses for server communication.
771
		 *
772
		 * @since 8.0.0
773
		 *
774
		 * @param String $url the generated URL.
775
		 * @param String $relative_url the relative URL that was passed as an argument.
776
		 * @param String $api_base the API base string that is being used.
777
		 * @param String $api_version the API version string that is being used.
778
		 */
779
		return apply_filters(
780
			'jetpack_api_url',
781
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
782
			$relative_url,
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $relative_url.

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...
783
			$api_base,
784
			$api_version
785
		);
786
	}
787
788
	/**
789
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
790
	 *
791
	 * @return String XMLRPC API URL.
792
	 */
793
	public function xmlrpc_api_url() {
794
		$base = preg_replace(
795
			'#(https?://[^?/]+)(/?.*)?$#',
796
			'\\1',
797
			Constants::get_constant( 'JETPACK__API_BASE' )
798
		);
799
		return untrailingslashit( $base ) . '/xmlrpc.php';
800
	}
801
802
	/**
803
	 * Attempts Jetpack registration which sets up the site for connection. Should
804
	 * remain public because the call to action comes from the current site, not from
805
	 * WordPress.com.
806
	 *
807
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
808
	 * @return Integer zero on success, or a bitmask on failure.
809
	 */
810
	public function register( $api_endpoint = 'register' ) {
811
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
812
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
813
814
		if (
815
			empty( $secrets['secret_1'] ) ||
816
			empty( $secrets['secret_2'] ) ||
817
			empty( $secrets['exp'] )
818
		) {
819
			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...
820
		}
821
822
		// Better to try (and fail) to set a higher timeout than this system
823
		// supports than to have register fail for more users than it should.
824
		$timeout = $this->set_min_time_limit( 60 ) / 2;
825
826
		$gmt_offset = get_option( 'gmt_offset' );
827
		if ( ! $gmt_offset ) {
828
			$gmt_offset = 0;
829
		}
830
831
		$stats_options = get_option( 'stats_options' );
832
		$stats_id      = isset( $stats_options['blog_id'] )
833
			? $stats_options['blog_id']
834
			: null;
835
836
		/**
837
		 * Filters the request body for additional property addition.
838
		 *
839
		 * @since 7.7.0
840
		 *
841
		 * @param array $post_data request data.
842
		 * @param Array $token_data token data.
843
		 */
844
		$body = apply_filters(
845
			'jetpack_register_request_body',
846
			array(
847
				'siteurl'         => site_url(),
848
				'home'            => home_url(),
849
				'gmt_offset'      => $gmt_offset,
850
				'timezone_string' => (string) get_option( 'timezone_string' ),
851
				'site_name'       => (string) get_option( 'blogname' ),
852
				'secret_1'        => $secrets['secret_1'],
853
				'secret_2'        => $secrets['secret_2'],
854
				'site_lang'       => get_locale(),
855
				'timeout'         => $timeout,
856
				'stats_id'        => $stats_id,
857
				'state'           => get_current_user_id(),
858
				'site_created'    => $this->get_assumed_site_creation_date(),
859
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
860
				'ABSPATH'         => Constants::get_constant( 'ABSPATH' ),
861
			)
862
		);
863
864
		$args = array(
865
			'method'  => 'POST',
866
			'body'    => $body,
867
			'headers' => array(
868
				'Accept' => 'application/json',
869
			),
870
			'timeout' => $timeout,
871
		);
872
873
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
874
875
		// TODO: fix URLs for bad hosts.
876
		$response = Client::_wp_remote_request(
877
			$this->api_url( $api_endpoint ),
878
			$args,
879
			true
880
		);
881
882
		// Make sure the response is valid and does not contain any Jetpack errors.
883
		$registration_details = $this->validate_remote_register_response( $response );
884
885
		if ( is_wp_error( $registration_details ) ) {
886
			return $registration_details;
887
		} elseif ( ! $registration_details ) {
888
			return new \WP_Error(
889
				'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...
890
				'Unknown error registering your Jetpack site.',
891
				wp_remote_retrieve_response_code( $response )
892
			);
893
		}
894
895
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
896
			return new \WP_Error(
897
				'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...
898
				'Unable to validate registration of your Jetpack site.',
899
				wp_remote_retrieve_response_code( $response )
900
			);
901
		}
902
903
		if ( isset( $registration_details->jetpack_public ) ) {
904
			$jetpack_public = (int) $registration_details->jetpack_public;
905
		} else {
906
			$jetpack_public = false;
907
		}
908
909
		\Jetpack_Options::update_options(
910
			array(
911
				'id'         => (int) $registration_details->jetpack_id,
912
				'blog_token' => (string) $registration_details->jetpack_secret,
913
				'public'     => $jetpack_public,
914
			)
915
		);
916
917
		/**
918
		 * Fires when a site is registered on WordPress.com.
919
		 *
920
		 * @since 3.7.0
921
		 *
922
		 * @param int $json->jetpack_id Jetpack Blog ID.
923
		 * @param string $json->jetpack_secret Jetpack Blog Token.
924
		 * @param int|bool $jetpack_public Is the site public.
925
		 */
926
		do_action(
927
			'jetpack_site_registered',
928
			$registration_details->jetpack_id,
929
			$registration_details->jetpack_secret,
930
			$jetpack_public
931
		);
932
933
		if ( isset( $registration_details->token ) ) {
934
			/**
935
			 * Fires when a user token is sent along with the registration data.
936
			 *
937
			 * @since 7.6.0
938
			 *
939
			 * @param object $token the administrator token for the newly registered site.
940
			 */
941
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
942
		}
943
944
		return true;
945
	}
946
947
	/**
948
	 * Takes the response from the Jetpack register new site endpoint and
949
	 * verifies it worked properly.
950
	 *
951
	 * @since 2.6
952
	 *
953
	 * @param Mixed $response the response object, or the error object.
954
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
955
	 **/
956
	protected function validate_remote_register_response( $response ) {
957
		if ( is_wp_error( $response ) ) {
958
			return new \WP_Error(
959
				'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...
960
				$response->get_error_message()
961
			);
962
		}
963
964
		$code   = wp_remote_retrieve_response_code( $response );
965
		$entity = wp_remote_retrieve_body( $response );
966
967
		if ( $entity ) {
968
			$registration_response = json_decode( $entity );
969
		} else {
970
			$registration_response = false;
971
		}
972
973
		$code_type = intval( $code / 100 );
974
		if ( 5 === $code_type ) {
975
			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...
976
		} elseif ( 408 === $code ) {
977
			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...
978
		} elseif ( ! empty( $registration_response->error ) ) {
979
			if (
980
				'xml_rpc-32700' === $registration_response->error
981
				&& ! function_exists( 'xml_parser_create' )
982
			) {
983
				$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' );
984
			} else {
985
				$error_description = isset( $registration_response->error_description )
986
					? (string) $registration_response->error_description
987
					: '';
988
			}
989
990
			return new \WP_Error(
991
				(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...
992
				$error_description,
993
				$code
994
			);
995
		} elseif ( 200 !== $code ) {
996
			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...
997
		}
998
999
		// Jetpack ID error block.
1000
		if ( empty( $registration_response->jetpack_id ) ) {
1001
			return new \WP_Error(
1002
				'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...
1003
				/* translators: %s is an error message string */
1004
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1005
				$entity
1006
			);
1007
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1008
			return new \WP_Error(
1009
				'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...
1010
				/* translators: %s is an error message string */
1011
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1012
				$entity
1013
			);
1014 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1015
			return new \WP_Error(
1016
				'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...
1017
				/* translators: %s is an error message string */
1018
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1019
				$entity
1020
			);
1021
		}
1022
1023
		return $registration_response;
1024
	}
1025
1026
	/**
1027
	 * Adds a used nonce to a list of known nonces.
1028
	 *
1029
	 * @param int    $timestamp the current request timestamp.
1030
	 * @param string $nonce the nonce value.
1031
	 * @return bool whether the nonce is unique or not.
1032
	 */
1033
	public function add_nonce( $timestamp, $nonce ) {
1034
		global $wpdb;
1035
		static $nonces_used_this_request = array();
1036
1037
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
1038
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
1039
		}
1040
1041
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
1042
		$timestamp = (int) $timestamp;
1043
		$nonce     = esc_sql( $nonce );
1044
1045
		// Raw query so we can avoid races: add_option will also update.
1046
		$show_errors = $wpdb->show_errors( false );
1047
1048
		$old_nonce = $wpdb->get_row(
1049
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1050
		);
1051
1052
		if ( is_null( $old_nonce ) ) {
1053
			$return = $wpdb->query(
1054
				$wpdb->prepare(
1055
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1056
					"jetpack_nonce_{$timestamp}_{$nonce}",
1057
					time(),
1058
					'no'
1059
				)
1060
			);
1061
		} else {
1062
			$return = false;
1063
		}
1064
1065
		$wpdb->show_errors( $show_errors );
1066
1067
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1068
1069
		return $return;
1070
	}
1071
1072
	/**
1073
	 * Cleans nonces that were saved when calling ::add_nonce.
1074
	 *
1075
	 * @todo Properly prepare the query before executing it.
1076
	 *
1077
	 * @param bool $all whether to clean even non-expired nonces.
1078
	 */
1079
	public function clean_nonces( $all = false ) {
1080
		global $wpdb;
1081
1082
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1083
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1084
1085
		if ( true !== $all ) {
1086
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1087
			$sql_args[] = time() - 3600;
1088
		}
1089
1090
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1091
1092
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1093
1094
		for ( $i = 0; $i < 1000; $i++ ) {
1095
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1096
				break;
1097
			}
1098
		}
1099
	}
1100
1101
	/**
1102
	 * Builds the timeout limit for queries talking with the wpcom servers.
1103
	 *
1104
	 * Based on local php max_execution_time in php.ini
1105
	 *
1106
	 * @since 5.4
1107
	 * @return int
1108
	 **/
1109
	public function get_max_execution_time() {
1110
		$timeout = (int) ini_get( 'max_execution_time' );
1111
1112
		// Ensure exec time set in php.ini.
1113
		if ( ! $timeout ) {
1114
			$timeout = 30;
1115
		}
1116
		return $timeout;
1117
	}
1118
1119
	/**
1120
	 * Sets a minimum request timeout, and returns the current timeout
1121
	 *
1122
	 * @since 5.4
1123
	 * @param Integer $min_timeout the minimum timeout value.
1124
	 **/
1125 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1126
		$timeout = $this->get_max_execution_time();
1127
		if ( $timeout < $min_timeout ) {
1128
			$timeout = $min_timeout;
1129
			set_time_limit( $timeout );
1130
		}
1131
		return $timeout;
1132
	}
1133
1134
	/**
1135
	 * Get our assumed site creation date.
1136
	 * Calculated based on the earlier date of either:
1137
	 * - Earliest admin user registration date.
1138
	 * - Earliest date of post of any post type.
1139
	 *
1140
	 * @since 7.2.0
1141
	 *
1142
	 * @return string Assumed site creation date and time.
1143
	 */
1144
	public function get_assumed_site_creation_date() {
1145
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1146
		if ( ! empty( $cached_date ) ) {
1147
			return $cached_date;
1148
		}
1149
1150
		$earliest_registered_users  = get_users(
1151
			array(
1152
				'role'    => 'administrator',
1153
				'orderby' => 'user_registered',
1154
				'order'   => 'ASC',
1155
				'fields'  => array( 'user_registered' ),
1156
				'number'  => 1,
1157
			)
1158
		);
1159
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1160
1161
		$earliest_posts = get_posts(
1162
			array(
1163
				'posts_per_page' => 1,
1164
				'post_type'      => 'any',
1165
				'post_status'    => 'any',
1166
				'orderby'        => 'date',
1167
				'order'          => 'ASC',
1168
			)
1169
		);
1170
1171
		// If there are no posts at all, we'll count only on user registration date.
1172
		if ( $earliest_posts ) {
1173
			$earliest_post_date = $earliest_posts[0]->post_date;
1174
		} else {
1175
			$earliest_post_date = PHP_INT_MAX;
1176
		}
1177
1178
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1179
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1180
1181
		return $assumed_date;
1182
	}
1183
1184
	/**
1185
	 * Adds the activation source string as a parameter to passed arguments.
1186
	 *
1187
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1188
	 *
1189
	 * @param array $args arguments that need to have the source added.
1190
	 * @return array $amended arguments.
1191
	 */
1192 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1193
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1194
1195
		if ( $activation_source_name ) {
1196
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1197
			$args['_as'] = urlencode( $activation_source_name );
1198
		}
1199
1200
		if ( $activation_source_keyword ) {
1201
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1202
			$args['_ak'] = urlencode( $activation_source_keyword );
1203
		}
1204
1205
		return $args;
1206
	}
1207
1208
	/**
1209
	 * Returns the callable that would be used to generate secrets.
1210
	 *
1211
	 * @return Callable a function that returns a secure string to be used as a secret.
1212
	 */
1213
	protected function get_secret_callable() {
1214
		if ( ! isset( $this->secret_callable ) ) {
1215
			/**
1216
			 * Allows modification of the callable that is used to generate connection secrets.
1217
			 *
1218
			 * @param Callable a function or method that returns a secret string.
1219
			 */
1220
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', array( $this, 'secret_callable_method' ) );
1221
		}
1222
1223
		return $this->secret_callable;
1224
	}
1225
1226
	/**
1227
	 * Runs the wp_generate_password function with the required parameters. This is the
1228
	 * default implementation of the secret callable, can be overridden using the
1229
	 * jetpack_connection_secret_generator filter.
1230
	 *
1231
	 * @return String $secret value.
1232
	 */
1233
	private function secret_callable_method() {
1234
		return wp_generate_password( 32, false );
1235
	}
1236
1237
	/**
1238
	 * Generates two secret tokens and the end of life timestamp for them.
1239
	 *
1240
	 * @param String  $action  The action name.
1241
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be false|integer?

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

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

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

Loading history...
1242
	 * @param Integer $exp     Expiration time in seconds.
1243
	 */
1244
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1245
		if ( false === $user_id ) {
1246
			$user_id = get_current_user_id();
1247
		}
1248
1249
		$callable = $this->get_secret_callable();
1250
1251
		$secrets = \Jetpack_Options::get_raw_option(
1252
			self::SECRETS_OPTION_NAME,
1253
			array()
1254
		);
1255
1256
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1257
1258
		if (
1259
			isset( $secrets[ $secret_name ] ) &&
1260
			$secrets[ $secret_name ]['exp'] > time()
1261
		) {
1262
			return $secrets[ $secret_name ];
1263
		}
1264
1265
		$secret_value = array(
1266
			'secret_1' => call_user_func( $callable ),
1267
			'secret_2' => call_user_func( $callable ),
1268
			'exp'      => time() + $exp,
1269
		);
1270
1271
		$secrets[ $secret_name ] = $secret_value;
1272
1273
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1274
		return $secrets[ $secret_name ];
1275
	}
1276
1277
	/**
1278
	 * Returns two secret tokens and the end of life timestamp for them.
1279
	 *
1280
	 * @param String  $action  The action name.
1281
	 * @param Integer $user_id The user identifier.
1282
	 * @return string|array an array of secrets or an error string.
1283
	 */
1284
	public function get_secrets( $action, $user_id ) {
1285
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1286
		$secrets     = \Jetpack_Options::get_raw_option(
1287
			self::SECRETS_OPTION_NAME,
1288
			array()
1289
		);
1290
1291
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1292
			return self::SECRETS_MISSING;
1293
		}
1294
1295
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1296
			$this->delete_secrets( $action, $user_id );
1297
			return self::SECRETS_EXPIRED;
1298
		}
1299
1300
		return $secrets[ $secret_name ];
1301
	}
1302
1303
	/**
1304
	 * Deletes secret tokens in case they, for example, have expired.
1305
	 *
1306
	 * @param String  $action  The action name.
1307
	 * @param Integer $user_id The user identifier.
1308
	 */
1309
	public function delete_secrets( $action, $user_id ) {
1310
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1311
		$secrets     = \Jetpack_Options::get_raw_option(
1312
			self::SECRETS_OPTION_NAME,
1313
			array()
1314
		);
1315
		if ( isset( $secrets[ $secret_name ] ) ) {
1316
			unset( $secrets[ $secret_name ] );
1317
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1318
		}
1319
	}
1320
1321
	/**
1322
	 * Deletes all connection tokens and transients from the local Jetpack site.
1323
	 * If the plugin object has been provided in the constructor, the function first checks
1324
	 * whether it's the only active connection.
1325
	 * If there are any other connections, the function will do nothing and return `false`
1326
	 * (unless `$ignore_connected_plugins` is set to `true`).
1327
	 *
1328
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1329
	 *
1330
	 * @return bool True if disconnected successfully, false otherwise.
1331
	 */
1332
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1333 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1334
			return false;
1335
		}
1336
1337
		/**
1338
		 * Fires upon the disconnect attempt.
1339
		 * Return `false` to prevent the disconnect.
1340
		 *
1341
		 * @since 8.7.0
1342
		 */
1343
		if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', true, $this ) ) {
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this.

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

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

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

Loading history...
1344
			return false;
1345
		}
1346
1347
		\Jetpack_Options::delete_option(
1348
			array(
1349
				'blog_token',
1350
				'user_token',
1351
				'user_tokens',
1352
				'master_user',
1353
				'time_diff',
1354
				'fallback_no_verify_ssl_certs',
1355
			)
1356
		);
1357
1358
		\Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
1359
1360
		// Delete cached connected user data.
1361
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1362
		delete_transient( $transient_key );
1363
1364
		return true;
1365
	}
1366
1367
	/**
1368
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1369
	 * If the plugin object has been provided in the constructor, the function first check
1370
	 * whether it's the only active connection.
1371
	 * If there are any other connections, the function will do nothing and return `false`
1372
	 * (unless `$ignore_connected_plugins` is set to `true`).
1373
	 *
1374
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1375
	 *
1376
	 * @return bool True if disconnected successfully, false otherwise.
1377
	 */
1378
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1379 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1380
			return false;
1381
		}
1382
1383
		/**
1384
		 * Fires upon the disconnect attempt.
1385
		 * Return `false` to prevent the disconnect.
1386
		 *
1387
		 * @since 8.7.0
1388
		 */
1389
		if ( ! apply_filters( 'jetpack_connection_disconnect_site_wpcom', true, $this ) ) {
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this.

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...
1390
			return false;
1391
		}
1392
1393
		$xml = new \Jetpack_IXR_Client();
1394
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1395
1396
		return true;
1397
	}
1398
1399
	/**
1400
	 * Disconnect the plugin and remove the tokens.
1401
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1402
	 * This is a proxy method to simplify the Connection package API.
1403
	 *
1404
	 * @see Manager::disable_plugin()
1405
	 * @see Manager::disconnect_site_wpcom()
1406
	 * @see Manager::delete_all_connection_tokens()
1407
	 *
1408
	 * @return bool
1409
	 */
1410
	public function remove_connection() {
1411
		$this->disable_plugin();
1412
		$this->disconnect_site_wpcom();
1413
		$this->delete_all_connection_tokens();
1414
1415
		return true;
1416
	}
1417
1418
	/**
1419
	 * Responds to a WordPress.com call to register the current site.
1420
	 * Should be changed to protected.
1421
	 *
1422
	 * @param array $registration_data Array of [ secret_1, user_id ].
1423
	 */
1424
	public function handle_registration( array $registration_data ) {
1425
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1426
		if ( empty( $registration_user_id ) ) {
1427
			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...
1428
		}
1429
1430
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1431
	}
1432
1433
	/**
1434
	 * Verify a Previously Generated Secret.
1435
	 *
1436
	 * @param string $action   The type of secret to verify.
1437
	 * @param string $secret_1 The secret string to compare to what is stored.
1438
	 * @param int    $user_id  The user ID of the owner of the secret.
1439
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1440
	 */
1441
	public function verify_secrets( $action, $secret_1, $user_id ) {
1442
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1443
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1444
			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...
1445
		}
1446
1447
		$user = get_user_by( 'id', $user_id );
1448
1449
		/**
1450
		 * We've begun verifying the previously generated secret.
1451
		 *
1452
		 * @since 7.5.0
1453
		 *
1454
		 * @param string   $action The type of secret to verify.
1455
		 * @param \WP_User $user The user object.
1456
		 */
1457
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1458
1459
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1460
			/**
1461
			 * Verifying of the previously generated secret has failed.
1462
			 *
1463
			 * @since 7.5.0
1464
			 *
1465
			 * @param string    $action  The type of secret to verify.
1466
			 * @param \WP_User  $user The user object.
1467
			 * @param \WP_Error $error The error object.
1468
			 */
1469
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1470
1471
			return $error;
1472
		};
1473
1474
		$stored_secrets = $this->get_secrets( $action, $user_id );
1475
		$this->delete_secrets( $action, $user_id );
1476
1477
		$error = null;
1478
		if ( empty( $secret_1 ) ) {
1479
			$error = $return_error(
1480
				new \WP_Error(
1481
					'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...
1482
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1483
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1484
					400
1485
				)
1486
			);
1487
		} elseif ( ! is_string( $secret_1 ) ) {
1488
			$error = $return_error(
1489
				new \WP_Error(
1490
					'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...
1491
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1492
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1493
					400
1494
				)
1495
			);
1496
		} elseif ( empty( $user_id ) ) {
1497
			// $user_id is passed around during registration as "state".
1498
			$error = $return_error(
1499
				new \WP_Error(
1500
					'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...
1501
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1502
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1503
					400
1504
				)
1505
			);
1506
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1507
			$error = $return_error(
1508
				new \WP_Error(
1509
					'state_malformed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'state_malformed'.

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

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

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

Loading history...
1510
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1511
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1512
					400
1513
				)
1514
			);
1515
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1516
			$error = $return_error(
1517
				new \WP_Error(
1518
					'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...
1519
					__( 'Verification secrets not found', 'jetpack' ),
1520
					400
1521
				)
1522
			);
1523
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1524
			$error = $return_error(
1525
				new \WP_Error(
1526
					'verify_secrets_expired',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

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

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

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

Loading history...
1527
					__( 'Verification took too long', 'jetpack' ),
1528
					400
1529
				)
1530
			);
1531
		} elseif ( ! $stored_secrets ) {
1532
			$error = $return_error(
1533
				new \WP_Error(
1534
					'verify_secrets_empty',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_empty'.

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

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

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

Loading history...
1535
					__( 'Verification secrets are empty', 'jetpack' ),
1536
					400
1537
				)
1538
			);
1539
		} elseif ( is_wp_error( $stored_secrets ) ) {
1540
			$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...
1541
			$error = $return_error( $stored_secrets );
1542
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1543
			$error = $return_error(
1544
				new \WP_Error(
1545
					'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...
1546
					__( 'Verification secrets are incomplete', 'jetpack' ),
1547
					400
1548
				)
1549
			);
1550
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1551
			$error = $return_error(
1552
				new \WP_Error(
1553
					'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...
1554
					__( 'Secret mismatch', 'jetpack' ),
1555
					400
1556
				)
1557
			);
1558
		}
1559
1560
		// Something went wrong during the checks, returning the error.
1561
		if ( ! empty( $error ) ) {
1562
			return $error;
1563
		}
1564
1565
		/**
1566
		 * We've succeeded at verifying the previously generated secret.
1567
		 *
1568
		 * @since 7.5.0
1569
		 *
1570
		 * @param string   $action The type of secret to verify.
1571
		 * @param \WP_User $user The user object.
1572
		 */
1573
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1574
1575
		return $stored_secrets['secret_2'];
1576
	}
1577
1578
	/**
1579
	 * Responds to a WordPress.com call to authorize the current user.
1580
	 * Should be changed to protected.
1581
	 */
1582
	public function handle_authorization() {
1583
1584
	}
1585
1586
	/**
1587
	 * Obtains the auth token.
1588
	 *
1589
	 * @param array $data The request data.
1590
	 * @return object|\WP_Error Returns the auth token on success.
1591
	 *                          Returns a \WP_Error on failure.
1592
	 */
1593
	public function get_token( $data ) {
1594
		$roles = new Roles();
1595
		$role  = $roles->translate_current_user_to_role();
1596
1597
		if ( ! $role ) {
1598
			return new \WP_Error( 'role', __( 'An administrator for this blog must set up the Jetpack connection.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'role'.

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

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

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

Loading history...
1599
		}
1600
1601
		$client_secret = $this->get_access_token();
1602
		if ( ! $client_secret ) {
1603
			return new \WP_Error( 'client_secret', __( 'You need to register your Jetpack before connecting it.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'client_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...
1604
		}
1605
1606
		/**
1607
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1608
		 * data processing.
1609
		 *
1610
		 * @since 8.0.0
1611
		 *
1612
		 * @param string $redirect_url Defaults to the site admin URL.
1613
		 */
1614
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1615
1616
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1617
1618
		/**
1619
		* Filter the URL to redirect the user back to when the authentication process
1620
		* is complete.
1621
		*
1622
		* @since 8.0.0
1623
		*
1624
		* @param string $redirect_url Defaults to the site URL.
1625
		*/
1626
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1627
1628
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1629
			? $data['redirect_uri']
1630
			: add_query_arg(
1631
				array(
1632
					'action'   => 'authorize',
1633
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1634
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1635
				),
1636
				esc_url( $processing_url )
1637
			);
1638
1639
		/**
1640
		 * Filters the token request data.
1641
		 *
1642
		 * @since 8.0.0
1643
		 *
1644
		 * @param array $request_data request data.
1645
		 */
1646
		$body = apply_filters(
1647
			'jetpack_token_request_body',
1648
			array(
1649
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1650
				'client_secret' => $client_secret->secret,
1651
				'grant_type'    => 'authorization_code',
1652
				'code'          => $data['code'],
1653
				'redirect_uri'  => $redirect_uri,
1654
			)
1655
		);
1656
1657
		$args = array(
1658
			'method'  => 'POST',
1659
			'body'    => $body,
1660
			'headers' => array(
1661
				'Accept' => 'application/json',
1662
			),
1663
		);
1664
1665
		add_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1666
		$response = Client::_wp_remote_request( Utils::fix_url_for_bad_hosts( $this->api_url( 'token' ) ), $args );
1667
		remove_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1668
1669
		if ( is_wp_error( $response ) ) {
1670
			return new \WP_Error( 'token_http_request_failed', $response->get_error_message() );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_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...
1671
		}
1672
1673
		$code   = wp_remote_retrieve_response_code( $response );
1674
		$entity = wp_remote_retrieve_body( $response );
1675
1676
		if ( $entity ) {
1677
			$json = json_decode( $entity );
1678
		} else {
1679
			$json = false;
1680
		}
1681
1682
		if ( 200 !== $code || ! empty( $json->error ) ) {
1683
			if ( empty( $json->error ) ) {
1684
				return new \WP_Error( 'unknown', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown'.

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...
1685
			}
1686
1687
			/* translators: Error description string. */
1688
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1689
1690
			return new \WP_Error( (string) $json->error, $error_description, $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with (string) $json->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...
1691
		}
1692
1693
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1694
			return new \WP_Error( 'access_token', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'access_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...
1695
		}
1696
1697
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1698
			return new \WP_Error( 'token_type', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_type'.

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...
1699
		}
1700
1701
		if ( empty( $json->scope ) ) {
1702
			return new \WP_Error( 'scope', 'No Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1703
		}
1704
1705
		// TODO: get rid of the error silencer.
1706
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1707
		@list( $role, $hmac ) = explode( ':', $json->scope );
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...
1708
		if ( empty( $role ) || empty( $hmac ) ) {
1709
			return new \WP_Error( 'scope', 'Malformed Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1710
		}
1711
1712
		if ( $this->sign_role( $role ) !== $json->scope ) {
1713
			return new \WP_Error( 'scope', 'Invalid Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1714
		}
1715
1716
		$cap = $roles->translate_role_to_cap( $role );
1717
		if ( ! $cap ) {
1718
			return new \WP_Error( 'scope', 'No Cap', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1719
		}
1720
1721
		if ( ! current_user_can( $cap ) ) {
1722
			return new \WP_Error( 'scope', 'current_user_cannot', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1723
		}
1724
1725
		/**
1726
		 * Fires after user has successfully received an auth token.
1727
		 *
1728
		 * @since 3.9.0
1729
		 */
1730
		do_action( 'jetpack_user_authorized' );
1731
1732
		return (string) $json->access_token;
1733
	}
1734
1735
	/**
1736
	 * Increases the request timeout value to 30 seconds.
1737
	 *
1738
	 * @return int Returns 30.
1739
	 */
1740
	public function increase_timeout() {
1741
		return 30;
1742
	}
1743
1744
	/**
1745
	 * Builds a URL to the Jetpack connection auth page.
1746
	 *
1747
	 * @param WP_User $user (optional) defaults to the current logged in user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user not be WP_User|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...
1748
	 * @param String  $redirect (optional) a redirect URL to use instead of the default.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $redirect not be string|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...
1749
	 * @return string Connect URL.
1750
	 */
1751
	public function get_authorization_url( $user = null, $redirect = null ) {
1752
1753
		if ( empty( $user ) ) {
1754
			$user = wp_get_current_user();
1755
		}
1756
1757
		$roles       = new Roles();
1758
		$role        = $roles->translate_user_to_role( $user );
1759
		$signed_role = $this->sign_role( $role );
1760
1761
		/**
1762
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1763
		 * data processing.
1764
		 *
1765
		 * @since 8.0.0
1766
		 *
1767
		 * @param string $redirect_url Defaults to the site admin URL.
1768
		 */
1769
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1770
1771
		/**
1772
		 * Filter the URL to redirect the user back to when the authorization process
1773
		 * is complete.
1774
		 *
1775
		 * @since 8.0.0
1776
		 *
1777
		 * @param string $redirect_url Defaults to the site URL.
1778
		 */
1779
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1780
1781
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1782
1783
		/**
1784
		 * Filter the type of authorization.
1785
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1786
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1787
		 *
1788
		 * @since 4.3.3
1789
		 *
1790
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1791
		 */
1792
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1793
1794
		/**
1795
		 * Filters the user connection request data for additional property addition.
1796
		 *
1797
		 * @since 8.0.0
1798
		 *
1799
		 * @param array $request_data request data.
1800
		 */
1801
		$body = apply_filters(
1802
			'jetpack_connect_request_body',
1803
			array(
1804
				'response_type' => 'code',
1805
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1806
				'redirect_uri'  => add_query_arg(
1807
					array(
1808
						'action'   => 'authorize',
1809
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1810
						'redirect' => rawurlencode( $redirect ),
1811
					),
1812
					esc_url( $processing_url )
1813
				),
1814
				'state'         => $user->ID,
1815
				'scope'         => $signed_role,
1816
				'user_email'    => $user->user_email,
1817
				'user_login'    => $user->user_login,
1818
				'is_active'     => $this->is_active(),
1819
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1820
				'auth_type'     => $auth_type,
1821
				'secret'        => $secrets['secret_1'],
1822
				'blogname'      => get_option( 'blogname' ),
1823
				'site_url'      => site_url(),
1824
				'home_url'      => home_url(),
1825
				'site_icon'     => get_site_icon_url(),
1826
				'site_lang'     => get_locale(),
1827
				'site_created'  => $this->get_assumed_site_creation_date(),
1828
			)
1829
		);
1830
1831
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1832
1833
		$api_url = $this->api_url( 'authorize' );
1834
1835
		return add_query_arg( $body, $api_url );
1836
	}
1837
1838
	/**
1839
	 * Authorizes the user by obtaining and storing the user token.
1840
	 *
1841
	 * @param array $data The request data.
1842
	 * @return string|\WP_Error Returns a string on success.
1843
	 *                          Returns a \WP_Error on failure.
1844
	 */
1845
	public function authorize( $data = array() ) {
1846
		/**
1847
		 * Action fired when user authorization starts.
1848
		 *
1849
		 * @since 8.0.0
1850
		 */
1851
		do_action( 'jetpack_authorize_starting' );
1852
1853
		$roles = new Roles();
1854
		$role  = $roles->translate_current_user_to_role();
1855
1856
		if ( ! $role ) {
1857
			return new \WP_Error( 'no_role', 'Invalid request.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_role'.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
1884
		}
1885
1886
		$token = $this->get_token( $data );
1887
1888 View Code Duplication
		if ( is_wp_error( $token ) ) {
1889
			$code = $token->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
1898
		}
1899
1900
		$is_master_user = ! $this->is_active();
1901
1902
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
1903
1904
		if ( ! $is_master_user ) {
1905
			/**
1906
			 * Action fired when a secondary user has been authorized.
1907
			 *
1908
			 * @since 8.0.0
1909
			 */
1910
			do_action( 'jetpack_authorize_ending_linked' );
1911
			return 'linked';
1912
		}
1913
1914
		/**
1915
		 * Action fired when the master user has been authorized.
1916
		 *
1917
		 * @since 8.0.0
1918
		 *
1919
		 * @param array $data The request data.
1920
		 */
1921
		do_action( 'jetpack_authorize_ending_authorized', $data );
1922
1923
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
1924
1925
		// Start nonce cleaner.
1926
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
1927
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
1928
1929
		return 'authorized';
1930
	}
1931
1932
	/**
1933
	 * Disconnects from the Jetpack servers.
1934
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1935
	 */
1936
	public function disconnect_site() {
1937
1938
	}
1939
1940
	/**
1941
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1942
	 *
1943
	 * @param string $text The string to hash.
1944
	 * @return string
1945
	 */
1946
	public function sha1_base64( $text ) {
1947
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1948
	}
1949
1950
	/**
1951
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1952
	 *
1953
	 * @param string $domain The domain to check.
1954
	 *
1955
	 * @return bool|WP_Error
1956
	 */
1957
	public function is_usable_domain( $domain ) {
1958
1959
		// If it's empty, just fail out.
1960
		if ( ! $domain ) {
1961
			return new \WP_Error(
1962
				'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...
1963
				/* translators: %1$s is a domain name. */
1964
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1965
			);
1966
		}
1967
1968
		/**
1969
		 * Skips the usuable domain check when connecting a site.
1970
		 *
1971
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1972
		 *
1973
		 * @since 4.1.0
1974
		 *
1975
		 * @param bool If the check should be skipped. Default false.
1976
		 */
1977
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1978
			return true;
1979
		}
1980
1981
		// None of the explicit localhosts.
1982
		$forbidden_domains = array(
1983
			'wordpress.com',
1984
			'localhost',
1985
			'localhost.localdomain',
1986
			'127.0.0.1',
1987
			'local.wordpress.test',         // VVV pattern.
1988
			'local.wordpress-trunk.test',   // VVV pattern.
1989
			'src.wordpress-develop.test',   // VVV pattern.
1990
			'build.wordpress-develop.test', // VVV pattern.
1991
		);
1992 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1993
			return new \WP_Error(
1994
				'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...
1995
				sprintf(
1996
					/* translators: %1$s is a domain name. */
1997
					__(
1998
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1999
						'jetpack'
2000
					),
2001
					$domain
2002
				)
2003
			);
2004
		}
2005
2006
		// No .test or .local domains.
2007 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
2008
			return new \WP_Error(
2009
				'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...
2010
				sprintf(
2011
					/* translators: %1$s is a domain name. */
2012
					__(
2013
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
2014
						'jetpack'
2015
					),
2016
					$domain
2017
				)
2018
			);
2019
		}
2020
2021
		// No WPCOM subdomains.
2022 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
2023
			return new \WP_Error(
2024
				'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...
2025
				sprintf(
2026
					/* translators: %1$s is a domain name. */
2027
					__(
2028
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
2029
						'jetpack'
2030
					),
2031
					$domain
2032
				)
2033
			);
2034
		}
2035
2036
		// If PHP was compiled without support for the Filter module (very edge case).
2037
		if ( ! function_exists( 'filter_var' ) ) {
2038
			// Just pass back true for now, and let wpcom sort it out.
2039
			return true;
2040
		}
2041
2042
		return true;
2043
	}
2044
2045
	/**
2046
	 * Gets the requested token.
2047
	 *
2048
	 * Tokens are one of two types:
2049
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
2050
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
2051
	 *    are not associated with a user account. They represent the site's connection with
2052
	 *    the Jetpack servers.
2053
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
2054
	 *
2055
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
2056
	 * token, and $private is a secret that should never be displayed anywhere or sent
2057
	 * over the network; it's used only for signing things.
2058
	 *
2059
	 * Blog Tokens can be "Normal" or "Special".
2060
	 * * Normal: The result of a normal connection flow. They look like
2061
	 *   "{$random_string_1}.{$random_string_2}"
2062
	 *   That is, $token_key and $private are both random strings.
2063
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
2064
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
2065
	 *   constant (rare).
2066
	 * * Special: A connection token for sites that have gone through an alternative
2067
	 *   connection flow. They look like:
2068
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
2069
	 *   That is, $private is a random string and $token_key has a special structure with
2070
	 *   lots of semicolons.
2071
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
2072
	 *   JETPACK_BLOG_TOKEN constant.
2073
	 *
2074
	 * In particular, note that Normal Blog Tokens never start with ";" and that
2075
	 * Special Blog Tokens always do.
2076
	 *
2077
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
2078
	 * order:
2079
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
2080
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
2081
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
2082
	 *
2083
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
2084
	 * @param string|false $token_key If provided, check that the token matches the provided input.
2085
	 * @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.
2086
	 *
2087
	 * @return object|false
2088
	 */
2089
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
2090
		$possible_special_tokens = array();
2091
		$possible_normal_tokens  = array();
2092
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
2093
2094
		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...
2095
			if ( ! $user_tokens ) {
2096
				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...
2097
			}
2098
			if ( self::JETPACK_MASTER_USER === $user_id ) {
2099
				$user_id = \Jetpack_Options::get_option( 'master_user' );
2100
				if ( ! $user_id ) {
2101
					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...
2102
				}
2103
			}
2104
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
2105
				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...
2106
			}
2107
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
2108 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
2109
				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...
2110
			}
2111 View Code Duplication
			if ( $user_token_chunks[2] !== (string) $user_id ) {
2112
				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...
2113
			}
2114
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
2115
		} else {
2116
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
2117
			if ( $stored_blog_token ) {
2118
				$possible_normal_tokens[] = $stored_blog_token;
2119
			}
2120
2121
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
2122
2123
			if ( $defined_tokens_string ) {
2124
				$defined_tokens = explode( ',', $defined_tokens_string );
2125
				foreach ( $defined_tokens as $defined_token ) {
2126
					if ( ';' === $defined_token[0] ) {
2127
						$possible_special_tokens[] = $defined_token;
2128
					} else {
2129
						$possible_normal_tokens[] = $defined_token;
2130
					}
2131
				}
2132
			}
2133
		}
2134
2135
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2136
			$possible_tokens = $possible_normal_tokens;
2137
		} else {
2138
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
2139
		}
2140
2141
		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...
2142
			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...
2143
		}
2144
2145
		$valid_token = false;
2146
2147
		if ( false === $token_key ) {
2148
			// Use first token.
2149
			$valid_token = $possible_tokens[0];
2150
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2151
			// Use first normal token.
2152
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
2153
		} else {
2154
			// Use the token matching $token_key or false if none.
2155
			// Ensure we check the full key.
2156
			$token_check = rtrim( $token_key, '.' ) . '.';
2157
2158
			foreach ( $possible_tokens as $possible_token ) {
2159
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
2160
					$valid_token = $possible_token;
2161
					break;
2162
				}
2163
			}
2164
		}
2165
2166
		if ( ! $valid_token ) {
2167
			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...
2168
		}
2169
2170
		return (object) array(
2171
			'secret'           => $valid_token,
2172
			'external_user_id' => (int) $user_id,
2173
		);
2174
	}
2175
2176
	/**
2177
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2178
	 * since it is passed by reference to various methods.
2179
	 * Capture it here so we can verify the signature later.
2180
	 *
2181
	 * @param array $methods an array of available XMLRPC methods.
2182
	 * @return array the same array, since this method doesn't add or remove anything.
2183
	 */
2184
	public function xmlrpc_methods( $methods ) {
2185
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
2186
		return $methods;
2187
	}
2188
2189
	/**
2190
	 * Resets the raw post data parameter for testing purposes.
2191
	 */
2192
	public function reset_raw_post_data() {
2193
		$this->raw_post_data = null;
2194
	}
2195
2196
	/**
2197
	 * Registering an additional method.
2198
	 *
2199
	 * @param array $methods an array of available XMLRPC methods.
2200
	 * @return array the amended array in case the method is added.
2201
	 */
2202
	public function public_xmlrpc_methods( $methods ) {
2203
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2204
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2205
		}
2206
		return $methods;
2207
	}
2208
2209
	/**
2210
	 * Handles a getOptions XMLRPC method call.
2211
	 *
2212
	 * @param array $args method call arguments.
2213
	 * @return an amended XMLRPC server options array.
2214
	 */
2215
	public function jetpack_get_options( $args ) {
2216
		global $wp_xmlrpc_server;
2217
2218
		$wp_xmlrpc_server->escape( $args );
2219
2220
		$username = $args[1];
2221
		$password = $args[2];
2222
2223
		$user = $wp_xmlrpc_server->login( $username, $password );
2224
		if ( ! $user ) {
2225
			return $wp_xmlrpc_server->error;
2226
		}
2227
2228
		$options   = array();
2229
		$user_data = $this->get_connected_user_data();
2230
		if ( is_array( $user_data ) ) {
2231
			$options['jetpack_user_id']         = array(
2232
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2233
				'readonly' => true,
2234
				'value'    => $user_data['ID'],
2235
			);
2236
			$options['jetpack_user_login']      = array(
2237
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2238
				'readonly' => true,
2239
				'value'    => $user_data['login'],
2240
			);
2241
			$options['jetpack_user_email']      = array(
2242
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2243
				'readonly' => true,
2244
				'value'    => $user_data['email'],
2245
			);
2246
			$options['jetpack_user_site_count'] = array(
2247
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2248
				'readonly' => true,
2249
				'value'    => $user_data['site_count'],
2250
			);
2251
		}
2252
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2253
		$args                           = stripslashes_deep( $args );
2254
		return $wp_xmlrpc_server->wp_getOptions( $args );
2255
	}
2256
2257
	/**
2258
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2259
	 *
2260
	 * @param array $options standard Core options.
2261
	 * @return array amended options.
2262
	 */
2263
	public function xmlrpc_options( $options ) {
2264
		$jetpack_client_id = false;
2265
		if ( $this->is_active() ) {
2266
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2267
		}
2268
		$options['jetpack_version'] = array(
2269
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2270
			'readonly' => true,
2271
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2272
		);
2273
2274
		$options['jetpack_client_id'] = array(
2275
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2276
			'readonly' => true,
2277
			'value'    => $jetpack_client_id,
2278
		);
2279
		return $options;
2280
	}
2281
2282
	/**
2283
	 * Resets the saved authentication state in between testing requests.
2284
	 */
2285
	public function reset_saved_auth_state() {
2286
		$this->xmlrpc_verification = null;
2287
	}
2288
2289
	/**
2290
	 * Sign a user role with the master access token.
2291
	 * If not specified, will default to the current user.
2292
	 *
2293
	 * @access public
2294
	 *
2295
	 * @param string $role    User role.
2296
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
2297
	 * @return string Signed user role.
2298
	 */
2299
	public function sign_role( $role, $user_id = null ) {
2300
		if ( empty( $user_id ) ) {
2301
			$user_id = (int) get_current_user_id();
2302
		}
2303
2304
		if ( ! $user_id ) {
2305
			return false;
2306
		}
2307
2308
		$token = $this->get_access_token();
2309
		if ( ! $token || is_wp_error( $token ) ) {
2310
			return false;
2311
		}
2312
2313
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2314
	}
2315
2316
	/**
2317
	 * Set the plugin instance.
2318
	 *
2319
	 * @param Plugin $plugin_instance The plugin instance.
2320
	 *
2321
	 * @return $this
2322
	 */
2323
	public function set_plugin_instance( Plugin $plugin_instance ) {
2324
		$this->plugin = $plugin_instance;
2325
2326
		return $this;
2327
	}
2328
2329
	/**
2330
	 * Retrieve the plugin management object.
2331
	 *
2332
	 * @return Plugin
2333
	 */
2334
	public function get_plugin() {
2335
		return $this->plugin;
2336
	}
2337
2338
	/**
2339
	 * Get all connected plugins information, excluding those disconnected by user.
2340
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2341
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2342
	 * so please make sure not to run the method too early in the code.
2343
	 *
2344
	 * @return array|WP_Error
2345
	 */
2346
	public function get_connected_plugins() {
2347
		$maybe_plugins = Plugin_Storage::get_all( true );
2348
2349
		if ( $maybe_plugins instanceof WP_Error ) {
2350
			return $maybe_plugins;
2351
		}
2352
2353
		return $maybe_plugins;
2354
	}
2355
2356
	/**
2357
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2358
	 * Note: this method does not remove any access tokens.
2359
	 *
2360
	 * @return bool
2361
	 */
2362
	public function disable_plugin() {
2363
		if ( ! $this->plugin ) {
2364
			return false;
2365
		}
2366
2367
		return $this->plugin->disable();
2368
	}
2369
2370
	/**
2371
	 * Force plugin reconnect after user-initiated disconnect.
2372
	 * After its called, the plugin will be allowed to use the connection again.
2373
	 * Note: this method does not initialize access tokens.
2374
	 *
2375
	 * @return bool
2376
	 */
2377
	public function enable_plugin() {
2378
		if ( ! $this->plugin ) {
2379
			return false;
2380
		}
2381
2382
		return $this->plugin->enable();
2383
	}
2384
2385
	/**
2386
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2387
	 * If no plugin slug was passed into the constructor, always returns true.
2388
	 *
2389
	 * @return bool
2390
	 */
2391
	public function is_plugin_enabled() {
2392
		if ( ! $this->plugin ) {
2393
			return true;
2394
		}
2395
2396
		return $this->plugin->is_enabled();
2397
	}
2398
2399
}
2400