Completed
Push — add/stats-package ( 873a22...c3aabb )
by
unknown
230:03 queued 222:25
created

Manager::get_connected_plugins()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 9
rs 9.9666
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
		add_filter(
79
			'jetpack_constant_default_value',
80
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
81
			10,
82
			2
83
		);
84
85
		$manager->setup_xmlrpc_handlers(
86
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
87
			$manager->is_active(),
88
			$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...
89
		);
90
91
		if ( $manager->is_active() ) {
92
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
93
		} else {
94
			add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
95
		}
96
97
		add_action( 'jetpack_clean_nonces', array( $manager, 'clean_nonces' ) );
98
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
99
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
100
		}
101
102
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
103
	}
104
105
	/**
106
	 * Sets up the XMLRPC request handlers.
107
	 *
108
	 * @param array                  $request_params incoming request parameters.
109
	 * @param Boolean                $is_active whether the connection is currently active.
110
	 * @param Boolean                $is_signed whether the signature check has been successful.
111
	 * @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...
112
	 */
113
	public function setup_xmlrpc_handlers(
114
		$request_params,
115
		$is_active,
116
		$is_signed,
117
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
118
	) {
119
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
120
121
		if (
122
			! isset( $request_params['for'] )
123
			|| 'jetpack' !== $request_params['for']
124
		) {
125
			return false;
126
		}
127
128
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
129
		if (
130
			isset( $request_params['jetpack'] )
131
			&& 'comms' === $request_params['jetpack']
132
		) {
133
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
134
				// Use the real constant here for WordPress' sake.
135
				define( 'XMLRPC_REQUEST', true );
136
			}
137
138
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
139
140
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
141
		}
142
143
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
144
			return false;
145
		}
146
		// Display errors can cause the XML to be not well formed.
147
		@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...
148
149
		if ( $xmlrpc_server ) {
150
			$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...
151
		} else {
152
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
153
		}
154
155
		$this->require_jetpack_authentication();
156
157
		if ( $is_active ) {
158
			// Hack to preserve $HTTP_RAW_POST_DATA.
159
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
160
161
			if ( $is_signed ) {
162
				// The actual API methods.
163
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
164
			} else {
165
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
166
				// active Jetpack connection, so that additional users can link their account.
167
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
168
			}
169
		} else {
170
			// The bootstrap API methods.
171
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
172
173
			if ( $is_signed ) {
174
				// The jetpack Provision method is available for blog-token-signed requests.
175
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
176
			} else {
177
				new XMLRPC_Connector( $this );
178
			}
179
		}
180
181
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
182
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
183
		return true;
184
	}
185
186
	/**
187
	 * Initializes the REST API connector on the init hook.
188
	 */
189
	public function initialize_rest_api_registration_connector() {
190
		new REST_Connector( $this );
191
	}
192
193
	/**
194
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
195
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
196
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
197
	 * which is accessible via a different URI. Most of the below is copied directly
198
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
199
	 *
200
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
201
	 */
202
	public function alternate_xmlrpc() {
203
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
204
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
205
		global $HTTP_RAW_POST_DATA;
206
207
		// Some browser-embedded clients send cookies. We don't want them.
208
		$_COOKIE = array();
209
210
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
211
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
212
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
213
		}
214
215
		// phpcs:enable
216
217
		include_once ABSPATH . 'wp-admin/includes/admin.php';
218
		include_once ABSPATH . WPINC . '/class-IXR.php';
219
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
220
221
		/**
222
		 * Filters the class used for handling XML-RPC requests.
223
		 *
224
		 * @since 3.1.0
225
		 *
226
		 * @param string $class The name of the XML-RPC server class.
227
		 */
228
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
229
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
230
231
		// Fire off the request.
232
		nocache_headers();
233
		$wp_xmlrpc_server->serve_request();
234
235
		exit;
236
	}
237
238
	/**
239
	 * Removes all XML-RPC methods that are not `jetpack.*`.
240
	 * Only used in our alternate XML-RPC endpoint, where we want to
241
	 * ensure that Core and other plugins' methods are not exposed.
242
	 *
243
	 * @param array $methods a list of registered WordPress XMLRPC methods.
244
	 * @return array filtered $methods
245
	 */
246
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
247
		$jetpack_methods = array();
248
249
		foreach ( $methods as $method => $callback ) {
250
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
251
				$jetpack_methods[ $method ] = $callback;
252
			}
253
		}
254
255
		return $jetpack_methods;
256
	}
257
258
	/**
259
	 * Removes all other authentication methods not to allow other
260
	 * methods to validate unauthenticated requests.
261
	 */
262
	public function require_jetpack_authentication() {
263
		// Don't let anyone authenticate.
264
		$_COOKIE = array();
265
		remove_all_filters( 'authenticate' );
266
		remove_all_actions( 'wp_login_failed' );
267
268
		if ( $this->is_active() ) {
269
			// Allow Jetpack authentication.
270
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
271
		}
272
	}
273
274
	/**
275
	 * Authenticates XML-RPC and other requests from the Jetpack Server
276
	 *
277
	 * @param WP_User|Mixed $user user object if authenticated.
278
	 * @param String        $username username.
279
	 * @param String        $password password string.
280
	 * @return WP_User|Mixed authenticated user or error.
281
	 */
282
	public function authenticate_jetpack( $user, $username, $password ) {
283
		if ( is_a( $user, '\\WP_User' ) ) {
284
			return $user;
285
		}
286
287
		$token_details = $this->verify_xml_rpc_signature();
288
289
		if ( ! $token_details ) {
290
			return $user;
291
		}
292
293
		if ( 'user' !== $token_details['type'] ) {
294
			return $user;
295
		}
296
297
		if ( ! $token_details['user_id'] ) {
298
			return $user;
299
		}
300
301
		nocache_headers();
302
303
		return new \WP_User( $token_details['user_id'] );
304
	}
305
306
	/**
307
	 * Verifies the signature of the current request.
308
	 *
309
	 * @return false|array
310
	 */
311
	public function verify_xml_rpc_signature() {
312
		if ( is_null( $this->xmlrpc_verification ) ) {
313
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
314
315
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
316
				/**
317
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
318
				 *
319
				 * Error codes:
320
				 * - malformed_token
321
				 * - malformed_user_id
322
				 * - unknown_token
323
				 * - could_not_sign
324
				 * - invalid_nonce
325
				 * - signature_mismatch
326
				 *
327
				 * @since 7.5.0
328
				 *
329
				 * @param WP_Error $signature_verification_error The verification error
330
				 */
331
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
332
			}
333
		}
334
335
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
336
	}
337
338
	/**
339
	 * Verifies the signature of the current request.
340
	 *
341
	 * This function has side effects and should not be used. Instead,
342
	 * use the memoized version `->verify_xml_rpc_signature()`.
343
	 *
344
	 * @internal
345
	 * @todo Refactor to use proper nonce verification.
346
	 */
347
	private function internal_verify_xml_rpc_signature() {
348
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
349
		// It's not for us.
350
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
351
			return false;
352
		}
353
354
		$signature_details = array(
355
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
356
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
357
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
358
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
359
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
360
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
361
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
362
		);
363
364
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
365
		@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...
366
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
367
368
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
369
370
		if (
371
			empty( $token_key )
372
		||
373
			empty( $version ) || strval( $jetpack_api_version ) !== $version ) {
374
			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...
375
		}
376
377
		if ( '0' === $user_id ) {
378
			$token_type = 'blog';
379
			$user_id    = 0;
380
		} else {
381
			$token_type = 'user';
382
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
383
				return new \WP_Error(
384
					'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...
385
					'Malformed user_id in request',
386
					compact( 'signature_details' )
387
				);
388
			}
389
			$user_id = (int) $user_id;
390
391
			$user = new \WP_User( $user_id );
392
			if ( ! $user || ! $user->exists() ) {
393
				return new \WP_Error(
394
					'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...
395
					sprintf( 'User %d does not exist', $user_id ),
396
					compact( 'signature_details' )
397
				);
398
			}
399
		}
400
401
		$token = $this->get_access_token( $user_id, $token_key, false );
402
		if ( is_wp_error( $token ) ) {
403
			$token->add_data( compact( 'signature_details' ) );
404
			return $token;
405
		} elseif ( ! $token ) {
406
			return new \WP_Error(
407
				'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...
408
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
409
				compact( 'signature_details' )
410
			);
411
		}
412
413
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
414
		// phpcs:disable WordPress.Security.NonceVerification.Missing
415
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
416
			$post_data   = $_POST;
417
			$file_hashes = array();
418
			foreach ( $post_data as $post_data_key => $post_data_value ) {
419
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
420
					continue;
421
				}
422
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
423
				$file_hashes[ $post_data_key ] = $post_data_value;
424
			}
425
426
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
427
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
428
				$post_data[ $post_data_key ] = $post_data_value;
429
			}
430
431
			ksort( $post_data );
432
433
			$body = http_build_query( stripslashes_deep( $post_data ) );
434
		} elseif ( is_null( $this->raw_post_data ) ) {
435
			$body = file_get_contents( 'php://input' );
436
		} else {
437
			$body = null;
438
		}
439
		// phpcs:enable
440
441
		$signature = $jetpack_signature->sign_current_request(
442
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
443
		);
444
445
		$signature_details['url'] = $jetpack_signature->current_request_url;
446
447
		if ( ! $signature ) {
448
			return new \WP_Error(
449
				'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...
450
				'Unknown signature error',
451
				compact( 'signature_details' )
452
			);
453
		} elseif ( is_wp_error( $signature ) ) {
454
			return $signature;
455
		}
456
457
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
458
		$timestamp = (int) $_GET['timestamp'];
459
		$nonce     = stripslashes( (string) $_GET['nonce'] );
460
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
461
462
		// Use up the nonce regardless of whether the signature matches.
463
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
464
			return new \WP_Error(
465
				'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...
466
				'Could not add nonce',
467
				compact( 'signature_details' )
468
			);
469
		}
470
471
		// Be careful about what you do with this debugging data.
472
		// If a malicious requester has access to the expected signature,
473
		// bad things might be possible.
474
		$signature_details['expected'] = $signature;
475
476
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
477
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
478
			return new \WP_Error(
479
				'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...
480
				'Signature mismatch',
481
				compact( 'signature_details' )
482
			);
483
		}
484
485
		/**
486
		 * Action for additional token checking.
487
		 *
488
		 * @since 7.7.0
489
		 *
490
		 * @param array $post_data request data.
491
		 * @param array $token_data token data.
492
		 */
493
		return apply_filters(
494
			'jetpack_signature_check_token',
495
			array(
496
				'type'      => $token_type,
497
				'token_key' => $token_key,
498
				'user_id'   => $token->external_user_id,
499
			),
500
			$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...
501
			$this->raw_post_data
502
		);
503
	}
504
505
	/**
506
	 * Returns true if the current site is connected to WordPress.com.
507
	 *
508
	 * @return Boolean is the site connected?
509
	 */
510
	public function is_active() {
511
		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...
512
	}
513
514
	/**
515
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
516
	 *
517
	 * @access public
518
	 *
519
	 * @return bool
520
	 */
521
	public function is_registered() {
522
		$blog_id   = \Jetpack_Options::get_option( 'id' );
523
		$has_token = $this->is_active();
524
		return $blog_id && $has_token;
525
	}
526
527
	/**
528
	 * Checks to see if the connection owner of the site is missing.
529
	 *
530
	 * @return bool
531
	 */
532
	public function is_missing_connection_owner() {
533
		$connection_owner = $this->get_connection_owner_id();
534
		if ( ! get_user_by( 'id', $connection_owner ) ) {
535
			return true;
536
		}
537
538
		return false;
539
	}
540
541
	/**
542
	 * Returns true if the user with the specified identifier is connected to
543
	 * WordPress.com.
544
	 *
545
	 * @param Integer|Boolean $user_id the user identifier.
546
	 * @return Boolean is the user connected?
547
	 */
548
	public function is_user_connected( $user_id = false ) {
549
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
550
		if ( ! $user_id ) {
551
			return false;
552
		}
553
554
		return (bool) $this->get_access_token( $user_id );
555
	}
556
557
	/**
558
	 * Returns the local user ID of the connection owner.
559
	 *
560
	 * @return string|int Returns the ID of the connection owner or False if no connection owner found.
561
	 */
562 View Code Duplication
	public function get_connection_owner_id() {
563
		$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...
564
		$connection_owner = false;
565
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
566
			$connection_owner = $user_token->external_user_id;
567
		}
568
569
		return $connection_owner;
570
	}
571
572
	/**
573
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
574
	 * Able to select by specific capability.
575
	 *
576
	 * @param string $capability The capability of the user.
577
	 * @return array Array of WP_User objects if found.
578
	 */
579
	public function get_connected_users( $capability = 'any' ) {
580
		$connected_users    = array();
581
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
582
583
		if ( ! empty( $connected_user_ids ) ) {
584
			foreach ( $connected_user_ids as $id ) {
585
				// Check for capability.
586
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
587
					continue;
588
				}
589
590
				$connected_users[] = get_userdata( $id );
591
			}
592
		}
593
594
		return $connected_users;
595
	}
596
597
	/**
598
	 * Get the wpcom user data of the current|specified connected user.
599
	 *
600
	 * @todo Refactor to properly load the XMLRPC client independently.
601
	 *
602
	 * @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...
603
	 * @return Object the user object.
604
	 */
605 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
606
		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...
607
			$user_id = get_current_user_id();
608
		}
609
610
		$transient_key    = "jetpack_connected_user_data_$user_id";
611
		$cached_user_data = get_transient( $transient_key );
612
613
		if ( $cached_user_data ) {
614
			return $cached_user_data;
615
		}
616
617
		$xml = new \Jetpack_IXR_Client(
618
			array(
619
				'user_id' => $user_id,
620
			)
621
		);
622
		$xml->query( 'wpcom.getUser' );
623
		if ( ! $xml->isError() ) {
624
			$user_data = $xml->getResponse();
625
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
626
			return $user_data;
627
		}
628
629
		return false;
630
	}
631
632
	/**
633
	 * Returns a user object of the connection owner.
634
	 *
635
	 * @return object|false False if no connection owner found.
636
	 */
637 View Code Duplication
	public function get_connection_owner() {
638
		$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...
639
640
		$connection_owner = false;
641
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
642
			$connection_owner = get_userdata( $user_token->external_user_id );
643
		}
644
645
		return $connection_owner;
646
	}
647
648
	/**
649
	 * Returns true if the provided user is the Jetpack connection owner.
650
	 * If user ID is not specified, the current user will be used.
651
	 *
652
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
653
	 * @return Boolean True the user the connection owner, false otherwise.
654
	 */
655 View Code Duplication
	public function is_connection_owner( $user_id = false ) {
656
		if ( ! $user_id ) {
657
			$user_id = get_current_user_id();
658
		}
659
660
		$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...
661
662
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
663
	}
664
665
	/**
666
	 * Connects the user with a specified ID to a WordPress.com user using the
667
	 * remote login flow.
668
	 *
669
	 * @access public
670
	 *
671
	 * @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...
672
	 * @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...
673
	 *                              admin_url().
674
	 * @return WP_Error only in case of a failed user lookup.
675
	 */
676
	public function connect_user( $user_id = null, $redirect_url = null ) {
677
		$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...
678
		if ( null === $user_id ) {
679
			$user = wp_get_current_user();
680
		} else {
681
			$user = get_user_by( 'ID', $user_id );
682
		}
683
684
		if ( empty( $user ) ) {
685
			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...
686
		}
687
688
		if ( null === $redirect_url ) {
689
			$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...
690
		}
691
692
		// Using wp_redirect intentionally because we're redirecting outside.
693
		wp_redirect( $this->get_authorization_url( $user ) ); // phpcs:ignore WordPress.Security.SafeRedirect
694
		exit();
695
	}
696
697
	/**
698
	 * Unlinks the current user from the linked WordPress.com user.
699
	 *
700
	 * @access public
701
	 * @static
702
	 *
703
	 * @todo Refactor to properly load the XMLRPC client independently.
704
	 *
705
	 * @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...
706
	 * @return Boolean Whether the disconnection of the user was successful.
707
	 */
708
	public static function disconnect_user( $user_id = null ) {
709
		$tokens = \Jetpack_Options::get_option( 'user_tokens' );
710
		if ( ! $tokens ) {
711
			return false;
712
		}
713
714
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
715
716
		if ( \Jetpack_Options::get_option( 'master_user' ) === $user_id ) {
717
			return false;
718
		}
719
720
		if ( ! isset( $tokens[ $user_id ] ) ) {
721
			return false;
722
		}
723
724
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
725
		$xml->query( 'jetpack.unlink_user', $user_id );
726
727
		unset( $tokens[ $user_id ] );
728
729
		\Jetpack_Options::update_option( 'user_tokens', $tokens );
730
731
		/**
732
		 * Fires after the current user has been unlinked from WordPress.com.
733
		 *
734
		 * @since 4.1.0
735
		 *
736
		 * @param int $user_id The current user's ID.
737
		 */
738
		do_action( 'jetpack_unlinked_user', $user_id );
739
740
		return true;
741
	}
742
743
	/**
744
	 * Returns the requested Jetpack API URL.
745
	 *
746
	 * @param String $relative_url the relative API path.
747
	 * @return String API URL.
748
	 */
749
	public function api_url( $relative_url ) {
750
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
751
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
752
753
		/**
754
		 * Filters whether the connection manager should use the iframe authorization
755
		 * flow instead of the regular redirect-based flow.
756
		 *
757
		 * @since 8.3.0
758
		 *
759
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
760
		 */
761
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
762
763
		// Do not modify anything that is not related to authorize requests.
764
		if ( 'authorize' === $relative_url && $iframe_flow ) {
765
			$relative_url = 'authorize_iframe';
766
		}
767
768
		/**
769
		 * Filters the API URL that Jetpack uses for server communication.
770
		 *
771
		 * @since 8.0.0
772
		 *
773
		 * @param String $url the generated URL.
774
		 * @param String $relative_url the relative URL that was passed as an argument.
775
		 * @param String $api_base the API base string that is being used.
776
		 * @param String $api_version the API version string that is being used.
777
		 */
778
		return apply_filters(
779
			'jetpack_api_url',
780
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
781
			$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...
782
			$api_base,
783
			$api_version
784
		);
785
	}
786
787
	/**
788
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
789
	 *
790
	 * @return String XMLRPC API URL.
791
	 */
792
	public function xmlrpc_api_url() {
793
		$base = preg_replace(
794
			'#(https?://[^?/]+)(/?.*)?$#',
795
			'\\1',
796
			Constants::get_constant( 'JETPACK__API_BASE' )
797
		);
798
		return untrailingslashit( $base ) . '/xmlrpc.php';
799
	}
800
801
	/**
802
	 * Attempts Jetpack registration which sets up the site for connection. Should
803
	 * remain public because the call to action comes from the current site, not from
804
	 * WordPress.com.
805
	 *
806
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
807
	 * @return Integer zero on success, or a bitmask on failure.
808
	 */
809
	public function register( $api_endpoint = 'register' ) {
810
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
811
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
812
813
		if (
814
			empty( $secrets['secret_1'] ) ||
815
			empty( $secrets['secret_2'] ) ||
816
			empty( $secrets['exp'] )
817
		) {
818
			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...
819
		}
820
821
		// Better to try (and fail) to set a higher timeout than this system
822
		// supports than to have register fail for more users than it should.
823
		$timeout = $this->set_min_time_limit( 60 ) / 2;
824
825
		$gmt_offset = get_option( 'gmt_offset' );
826
		if ( ! $gmt_offset ) {
827
			$gmt_offset = 0;
828
		}
829
830
		$stats_options = get_option( 'stats_options' );
831
		$stats_id      = isset( $stats_options['blog_id'] )
832
			? $stats_options['blog_id']
833
			: null;
834
835
		/**
836
		 * Filters the request body for additional property addition.
837
		 *
838
		 * @since 7.7.0
839
		 *
840
		 * @param array $post_data request data.
841
		 * @param Array $token_data token data.
842
		 */
843
		$body = apply_filters(
844
			'jetpack_register_request_body',
845
			array(
846
				'siteurl'         => site_url(),
847
				'home'            => home_url(),
848
				'gmt_offset'      => $gmt_offset,
849
				'timezone_string' => (string) get_option( 'timezone_string' ),
850
				'site_name'       => (string) get_option( 'blogname' ),
851
				'secret_1'        => $secrets['secret_1'],
852
				'secret_2'        => $secrets['secret_2'],
853
				'site_lang'       => get_locale(),
854
				'timeout'         => $timeout,
855
				'stats_id'        => $stats_id,
856
				'state'           => get_current_user_id(),
857
				'site_created'    => $this->get_assumed_site_creation_date(),
858
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
859
				'ABSPATH'         => Constants::get_constant( 'ABSPATH' ),
860
			)
861
		);
862
863
		$args = array(
864
			'method'  => 'POST',
865
			'body'    => $body,
866
			'headers' => array(
867
				'Accept' => 'application/json',
868
			),
869
			'timeout' => $timeout,
870
		);
871
872
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
873
874
		// TODO: fix URLs for bad hosts.
875
		$response = Client::_wp_remote_request(
876
			$this->api_url( $api_endpoint ),
877
			$args,
878
			true
879
		);
880
881
		// Make sure the response is valid and does not contain any Jetpack errors.
882
		$registration_details = $this->validate_remote_register_response( $response );
883
884
		if ( is_wp_error( $registration_details ) ) {
885
			return $registration_details;
886
		} elseif ( ! $registration_details ) {
887
			return new \WP_Error(
888
				'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...
889
				'Unknown error registering your Jetpack site.',
890
				wp_remote_retrieve_response_code( $response )
891
			);
892
		}
893
894
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
895
			return new \WP_Error(
896
				'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...
897
				'Unable to validate registration of your Jetpack site.',
898
				wp_remote_retrieve_response_code( $response )
899
			);
900
		}
901
902
		if ( isset( $registration_details->jetpack_public ) ) {
903
			$jetpack_public = (int) $registration_details->jetpack_public;
904
		} else {
905
			$jetpack_public = false;
906
		}
907
908
		\Jetpack_Options::update_options(
909
			array(
910
				'id'         => (int) $registration_details->jetpack_id,
911
				'blog_token' => (string) $registration_details->jetpack_secret,
912
				'public'     => $jetpack_public,
913
			)
914
		);
915
916
		/**
917
		 * Fires when a site is registered on WordPress.com.
918
		 *
919
		 * @since 3.7.0
920
		 *
921
		 * @param int $json->jetpack_id Jetpack Blog ID.
922
		 * @param string $json->jetpack_secret Jetpack Blog Token.
923
		 * @param int|bool $jetpack_public Is the site public.
924
		 */
925
		do_action(
926
			'jetpack_site_registered',
927
			$registration_details->jetpack_id,
928
			$registration_details->jetpack_secret,
929
			$jetpack_public
930
		);
931
932
		if ( isset( $registration_details->token ) ) {
933
			/**
934
			 * Fires when a user token is sent along with the registration data.
935
			 *
936
			 * @since 7.6.0
937
			 *
938
			 * @param object $token the administrator token for the newly registered site.
939
			 */
940
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
941
		}
942
943
		return true;
944
	}
945
946
	/**
947
	 * Takes the response from the Jetpack register new site endpoint and
948
	 * verifies it worked properly.
949
	 *
950
	 * @since 2.6
951
	 *
952
	 * @param Mixed $response the response object, or the error object.
953
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
954
	 **/
955
	protected function validate_remote_register_response( $response ) {
956
		if ( is_wp_error( $response ) ) {
957
			return new \WP_Error(
958
				'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...
959
				$response->get_error_message()
960
			);
961
		}
962
963
		$code   = wp_remote_retrieve_response_code( $response );
964
		$entity = wp_remote_retrieve_body( $response );
965
966
		if ( $entity ) {
967
			$registration_response = json_decode( $entity );
968
		} else {
969
			$registration_response = false;
970
		}
971
972
		$code_type = intval( $code / 100 );
973
		if ( 5 === $code_type ) {
974
			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...
975
		} elseif ( 408 === $code ) {
976
			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...
977
		} elseif ( ! empty( $registration_response->error ) ) {
978
			if (
979
				'xml_rpc-32700' === $registration_response->error
980
				&& ! function_exists( 'xml_parser_create' )
981
			) {
982
				$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' );
983
			} else {
984
				$error_description = isset( $registration_response->error_description )
985
					? (string) $registration_response->error_description
986
					: '';
987
			}
988
989
			return new \WP_Error(
990
				(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...
991
				$error_description,
992
				$code
993
			);
994
		} elseif ( 200 !== $code ) {
995
			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...
996
		}
997
998
		// Jetpack ID error block.
999
		if ( empty( $registration_response->jetpack_id ) ) {
1000
			return new \WP_Error(
1001
				'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...
1002
				/* translators: %s is an error message string */
1003
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1004
				$entity
1005
			);
1006
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1007
			return new \WP_Error(
1008
				'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...
1009
				/* translators: %s is an error message string */
1010
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1011
				$entity
1012
			);
1013 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1014
			return new \WP_Error(
1015
				'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...
1016
				/* translators: %s is an error message string */
1017
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1018
				$entity
1019
			);
1020
		}
1021
1022
		return $registration_response;
1023
	}
1024
1025
	/**
1026
	 * Adds a used nonce to a list of known nonces.
1027
	 *
1028
	 * @param int    $timestamp the current request timestamp.
1029
	 * @param string $nonce the nonce value.
1030
	 * @return bool whether the nonce is unique or not.
1031
	 */
1032
	public function add_nonce( $timestamp, $nonce ) {
1033
		global $wpdb;
1034
		static $nonces_used_this_request = array();
1035
1036
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
1037
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
1038
		}
1039
1040
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
1041
		$timestamp = (int) $timestamp;
1042
		$nonce     = esc_sql( $nonce );
1043
1044
		// Raw query so we can avoid races: add_option will also update.
1045
		$show_errors = $wpdb->show_errors( false );
1046
1047
		$old_nonce = $wpdb->get_row(
1048
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1049
		);
1050
1051
		if ( is_null( $old_nonce ) ) {
1052
			$return = $wpdb->query(
1053
				$wpdb->prepare(
1054
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1055
					"jetpack_nonce_{$timestamp}_{$nonce}",
1056
					time(),
1057
					'no'
1058
				)
1059
			);
1060
		} else {
1061
			$return = false;
1062
		}
1063
1064
		$wpdb->show_errors( $show_errors );
1065
1066
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1067
1068
		return $return;
1069
	}
1070
1071
	/**
1072
	 * Cleans nonces that were saved when calling ::add_nonce.
1073
	 *
1074
	 * @todo Properly prepare the query before executing it.
1075
	 *
1076
	 * @param bool $all whether to clean even non-expired nonces.
1077
	 */
1078
	public function clean_nonces( $all = false ) {
1079
		global $wpdb;
1080
1081
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1082
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1083
1084
		if ( true !== $all ) {
1085
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1086
			$sql_args[] = time() - 3600;
1087
		}
1088
1089
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1090
1091
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1092
1093
		for ( $i = 0; $i < 1000; $i++ ) {
1094
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1095
				break;
1096
			}
1097
		}
1098
	}
1099
1100
	/**
1101
	 * Builds the timeout limit for queries talking with the wpcom servers.
1102
	 *
1103
	 * Based on local php max_execution_time in php.ini
1104
	 *
1105
	 * @since 5.4
1106
	 * @return int
1107
	 **/
1108
	public function get_max_execution_time() {
1109
		$timeout = (int) ini_get( 'max_execution_time' );
1110
1111
		// Ensure exec time set in php.ini.
1112
		if ( ! $timeout ) {
1113
			$timeout = 30;
1114
		}
1115
		return $timeout;
1116
	}
1117
1118
	/**
1119
	 * Sets a minimum request timeout, and returns the current timeout
1120
	 *
1121
	 * @since 5.4
1122
	 * @param Integer $min_timeout the minimum timeout value.
1123
	 **/
1124 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1125
		$timeout = $this->get_max_execution_time();
1126
		if ( $timeout < $min_timeout ) {
1127
			$timeout = $min_timeout;
1128
			set_time_limit( $timeout );
1129
		}
1130
		return $timeout;
1131
	}
1132
1133
	/**
1134
	 * Get our assumed site creation date.
1135
	 * Calculated based on the earlier date of either:
1136
	 * - Earliest admin user registration date.
1137
	 * - Earliest date of post of any post type.
1138
	 *
1139
	 * @since 7.2.0
1140
	 *
1141
	 * @return string Assumed site creation date and time.
1142
	 */
1143
	public function get_assumed_site_creation_date() {
1144
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1145
		if ( ! empty( $cached_date ) ) {
1146
			return $cached_date;
1147
		}
1148
1149
		$earliest_registered_users  = get_users(
1150
			array(
1151
				'role'    => 'administrator',
1152
				'orderby' => 'user_registered',
1153
				'order'   => 'ASC',
1154
				'fields'  => array( 'user_registered' ),
1155
				'number'  => 1,
1156
			)
1157
		);
1158
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1159
1160
		$earliest_posts = get_posts(
1161
			array(
1162
				'posts_per_page' => 1,
1163
				'post_type'      => 'any',
1164
				'post_status'    => 'any',
1165
				'orderby'        => 'date',
1166
				'order'          => 'ASC',
1167
			)
1168
		);
1169
1170
		// If there are no posts at all, we'll count only on user registration date.
1171
		if ( $earliest_posts ) {
1172
			$earliest_post_date = $earliest_posts[0]->post_date;
1173
		} else {
1174
			$earliest_post_date = PHP_INT_MAX;
1175
		}
1176
1177
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1178
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1179
1180
		return $assumed_date;
1181
	}
1182
1183
	/**
1184
	 * Adds the activation source string as a parameter to passed arguments.
1185
	 *
1186
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1187
	 *
1188
	 * @param array $args arguments that need to have the source added.
1189
	 * @return array $amended arguments.
1190
	 */
1191 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1192
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1193
1194
		if ( $activation_source_name ) {
1195
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1196
			$args['_as'] = urlencode( $activation_source_name );
1197
		}
1198
1199
		if ( $activation_source_keyword ) {
1200
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1201
			$args['_ak'] = urlencode( $activation_source_keyword );
1202
		}
1203
1204
		return $args;
1205
	}
1206
1207
	/**
1208
	 * Returns the callable that would be used to generate secrets.
1209
	 *
1210
	 * @return Callable a function that returns a secure string to be used as a secret.
1211
	 */
1212
	protected function get_secret_callable() {
1213
		if ( ! isset( $this->secret_callable ) ) {
1214
			/**
1215
			 * Allows modification of the callable that is used to generate connection secrets.
1216
			 *
1217
			 * @param Callable a function or method that returns a secret string.
1218
			 */
1219
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', array( $this, 'secret_callable_method' ) );
1220
		}
1221
1222
		return $this->secret_callable;
1223
	}
1224
1225
	/**
1226
	 * Runs the wp_generate_password function with the required parameters. This is the
1227
	 * default implementation of the secret callable, can be overridden using the
1228
	 * jetpack_connection_secret_generator filter.
1229
	 *
1230
	 * @return String $secret value.
1231
	 */
1232
	private function secret_callable_method() {
1233
		return wp_generate_password( 32, false );
1234
	}
1235
1236
	/**
1237
	 * Generates two secret tokens and the end of life timestamp for them.
1238
	 *
1239
	 * @param String  $action  The action name.
1240
	 * @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...
1241
	 * @param Integer $exp     Expiration time in seconds.
1242
	 */
1243
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1244
		if ( false === $user_id ) {
1245
			$user_id = get_current_user_id();
1246
		}
1247
1248
		$callable = $this->get_secret_callable();
1249
1250
		$secrets = \Jetpack_Options::get_raw_option(
1251
			self::SECRETS_OPTION_NAME,
1252
			array()
1253
		);
1254
1255
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1256
1257
		if (
1258
			isset( $secrets[ $secret_name ] ) &&
1259
			$secrets[ $secret_name ]['exp'] > time()
1260
		) {
1261
			return $secrets[ $secret_name ];
1262
		}
1263
1264
		$secret_value = array(
1265
			'secret_1' => call_user_func( $callable ),
1266
			'secret_2' => call_user_func( $callable ),
1267
			'exp'      => time() + $exp,
1268
		);
1269
1270
		$secrets[ $secret_name ] = $secret_value;
1271
1272
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1273
		return $secrets[ $secret_name ];
1274
	}
1275
1276
	/**
1277
	 * Returns two secret tokens and the end of life timestamp for them.
1278
	 *
1279
	 * @param String  $action  The action name.
1280
	 * @param Integer $user_id The user identifier.
1281
	 * @return string|array an array of secrets or an error string.
1282
	 */
1283
	public function get_secrets( $action, $user_id ) {
1284
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1285
		$secrets     = \Jetpack_Options::get_raw_option(
1286
			self::SECRETS_OPTION_NAME,
1287
			array()
1288
		);
1289
1290
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1291
			return self::SECRETS_MISSING;
1292
		}
1293
1294
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1295
			$this->delete_secrets( $action, $user_id );
1296
			return self::SECRETS_EXPIRED;
1297
		}
1298
1299
		return $secrets[ $secret_name ];
1300
	}
1301
1302
	/**
1303
	 * Deletes secret tokens in case they, for example, have expired.
1304
	 *
1305
	 * @param String  $action  The action name.
1306
	 * @param Integer $user_id The user identifier.
1307
	 */
1308
	public function delete_secrets( $action, $user_id ) {
1309
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1310
		$secrets     = \Jetpack_Options::get_raw_option(
1311
			self::SECRETS_OPTION_NAME,
1312
			array()
1313
		);
1314
		if ( isset( $secrets[ $secret_name ] ) ) {
1315
			unset( $secrets[ $secret_name ] );
1316
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1317
		}
1318
	}
1319
1320
	/**
1321
	 * Deletes all connection tokens and transients from the local Jetpack site.
1322
	 * If the plugin object has been provided in the constructor, the function first checks
1323
	 * whether it's the only active connection.
1324
	 * If there are any other connections, the function will do nothing and return `false`
1325
	 * (unless `$ignore_connected_plugins` is set to `true`).
1326
	 *
1327
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1328
	 *
1329
	 * @return bool True if disconnected successfully, false otherwise.
1330
	 */
1331
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1332 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1333
			return false;
1334
		}
1335
1336
		/**
1337
		 * Fires upon the disconnect attempt.
1338
		 * Return `false` to prevent the disconnect.
1339
		 *
1340
		 * @since 8.7.0
1341
		 */
1342
		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...
1343
			return false;
1344
		}
1345
1346
		\Jetpack_Options::delete_option(
1347
			array(
1348
				'blog_token',
1349
				'user_token',
1350
				'user_tokens',
1351
				'master_user',
1352
				'time_diff',
1353
				'fallback_no_verify_ssl_certs',
1354
			)
1355
		);
1356
1357
		\Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
1358
1359
		// Delete cached connected user data.
1360
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1361
		delete_transient( $transient_key );
1362
1363
		return true;
1364
	}
1365
1366
	/**
1367
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1368
	 * If the plugin object has been provided in the constructor, the function first check
1369
	 * whether it's the only active connection.
1370
	 * If there are any other connections, the function will do nothing and return `false`
1371
	 * (unless `$ignore_connected_plugins` is set to `true`).
1372
	 *
1373
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1374
	 *
1375
	 * @return bool True if disconnected successfully, false otherwise.
1376
	 */
1377
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1378 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1379
			return false;
1380
		}
1381
1382
		/**
1383
		 * Fires upon the disconnect attempt.
1384
		 * Return `false` to prevent the disconnect.
1385
		 *
1386
		 * @since 8.7.0
1387
		 */
1388
		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...
1389
			return false;
1390
		}
1391
1392
		$xml = new \Jetpack_IXR_Client();
1393
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1394
1395
		return true;
1396
	}
1397
1398
	/**
1399
	 * Disconnect the plugin and remove the tokens.
1400
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1401
	 * This is a proxy method to simplify the Connection package API.
1402
	 *
1403
	 * @see Manager::disable_plugin()
1404
	 * @see Manager::disconnect_site_wpcom()
1405
	 * @see Manager::delete_all_connection_tokens()
1406
	 *
1407
	 * @return bool
1408
	 */
1409
	public function remove_connection() {
1410
		$this->disable_plugin();
1411
		$this->disconnect_site_wpcom();
1412
		$this->delete_all_connection_tokens();
1413
1414
		return true;
1415
	}
1416
1417
	/**
1418
	 * Responds to a WordPress.com call to register the current site.
1419
	 * Should be changed to protected.
1420
	 *
1421
	 * @param array $registration_data Array of [ secret_1, user_id ].
1422
	 */
1423
	public function handle_registration( array $registration_data ) {
1424
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1425
		if ( empty( $registration_user_id ) ) {
1426
			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...
1427
		}
1428
1429
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1430
	}
1431
1432
	/**
1433
	 * Verify a Previously Generated Secret.
1434
	 *
1435
	 * @param string $action   The type of secret to verify.
1436
	 * @param string $secret_1 The secret string to compare to what is stored.
1437
	 * @param int    $user_id  The user ID of the owner of the secret.
1438
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1439
	 */
1440
	public function verify_secrets( $action, $secret_1, $user_id ) {
1441
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1442
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1443
			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...
1444
		}
1445
1446
		$user = get_user_by( 'id', $user_id );
1447
1448
		/**
1449
		 * We've begun verifying the previously generated secret.
1450
		 *
1451
		 * @since 7.5.0
1452
		 *
1453
		 * @param string   $action The type of secret to verify.
1454
		 * @param \WP_User $user The user object.
1455
		 */
1456
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1457
1458
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1459
			/**
1460
			 * Verifying of the previously generated secret has failed.
1461
			 *
1462
			 * @since 7.5.0
1463
			 *
1464
			 * @param string    $action  The type of secret to verify.
1465
			 * @param \WP_User  $user The user object.
1466
			 * @param \WP_Error $error The error object.
1467
			 */
1468
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1469
1470
			return $error;
1471
		};
1472
1473
		$stored_secrets = $this->get_secrets( $action, $user_id );
1474
		$this->delete_secrets( $action, $user_id );
1475
1476
		$error = null;
1477
		if ( empty( $secret_1 ) ) {
1478
			$error = $return_error(
1479
				new \WP_Error(
1480
					'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...
1481
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1482
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1483
					400
1484
				)
1485
			);
1486
		} elseif ( ! is_string( $secret_1 ) ) {
1487
			$error = $return_error(
1488
				new \WP_Error(
1489
					'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...
1490
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1491
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1492
					400
1493
				)
1494
			);
1495
		} elseif ( empty( $user_id ) ) {
1496
			// $user_id is passed around during registration as "state".
1497
			$error = $return_error(
1498
				new \WP_Error(
1499
					'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...
1500
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1501
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1502
					400
1503
				)
1504
			);
1505
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1506
			$error = $return_error(
1507
				new \WP_Error(
1508
					'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...
1509
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1510
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1511
					400
1512
				)
1513
			);
1514
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1515
			$error = $return_error(
1516
				new \WP_Error(
1517
					'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...
1518
					__( 'Verification secrets not found', 'jetpack' ),
1519
					400
1520
				)
1521
			);
1522
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1523
			$error = $return_error(
1524
				new \WP_Error(
1525
					'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...
1526
					__( 'Verification took too long', 'jetpack' ),
1527
					400
1528
				)
1529
			);
1530
		} elseif ( ! $stored_secrets ) {
1531
			$error = $return_error(
1532
				new \WP_Error(
1533
					'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...
1534
					__( 'Verification secrets are empty', 'jetpack' ),
1535
					400
1536
				)
1537
			);
1538
		} elseif ( is_wp_error( $stored_secrets ) ) {
1539
			$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...
1540
			$error = $return_error( $stored_secrets );
1541
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1542
			$error = $return_error(
1543
				new \WP_Error(
1544
					'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...
1545
					__( 'Verification secrets are incomplete', 'jetpack' ),
1546
					400
1547
				)
1548
			);
1549
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1550
			$error = $return_error(
1551
				new \WP_Error(
1552
					'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...
1553
					__( 'Secret mismatch', 'jetpack' ),
1554
					400
1555
				)
1556
			);
1557
		}
1558
1559
		// Something went wrong during the checks, returning the error.
1560
		if ( ! empty( $error ) ) {
1561
			return $error;
1562
		}
1563
1564
		/**
1565
		 * We've succeeded at verifying the previously generated secret.
1566
		 *
1567
		 * @since 7.5.0
1568
		 *
1569
		 * @param string   $action The type of secret to verify.
1570
		 * @param \WP_User $user The user object.
1571
		 */
1572
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1573
1574
		return $stored_secrets['secret_2'];
1575
	}
1576
1577
	/**
1578
	 * Responds to a WordPress.com call to authorize the current user.
1579
	 * Should be changed to protected.
1580
	 */
1581
	public function handle_authorization() {
1582
1583
	}
1584
1585
	/**
1586
	 * Obtains the auth token.
1587
	 *
1588
	 * @param array $data The request data.
1589
	 * @return object|\WP_Error Returns the auth token on success.
1590
	 *                          Returns a \WP_Error on failure.
1591
	 */
1592
	public function get_token( $data ) {
1593
		$roles = new Roles();
1594
		$role  = $roles->translate_current_user_to_role();
1595
1596
		if ( ! $role ) {
1597
			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...
1598
		}
1599
1600
		$client_secret = $this->get_access_token();
1601
		if ( ! $client_secret ) {
1602
			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...
1603
		}
1604
1605
		/**
1606
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1607
		 * data processing.
1608
		 *
1609
		 * @since 8.0.0
1610
		 *
1611
		 * @param string $redirect_url Defaults to the site admin URL.
1612
		 */
1613
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1614
1615
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1616
1617
		/**
1618
		* Filter the URL to redirect the user back to when the authentication process
1619
		* is complete.
1620
		*
1621
		* @since 8.0.0
1622
		*
1623
		* @param string $redirect_url Defaults to the site URL.
1624
		*/
1625
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1626
1627
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1628
			? $data['redirect_uri']
1629
			: add_query_arg(
1630
				array(
1631
					'action'   => 'authorize',
1632
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1633
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1634
				),
1635
				esc_url( $processing_url )
1636
			);
1637
1638
		/**
1639
		 * Filters the token request data.
1640
		 *
1641
		 * @since 8.0.0
1642
		 *
1643
		 * @param array $request_data request data.
1644
		 */
1645
		$body = apply_filters(
1646
			'jetpack_token_request_body',
1647
			array(
1648
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1649
				'client_secret' => $client_secret->secret,
1650
				'grant_type'    => 'authorization_code',
1651
				'code'          => $data['code'],
1652
				'redirect_uri'  => $redirect_uri,
1653
			)
1654
		);
1655
1656
		$args = array(
1657
			'method'  => 'POST',
1658
			'body'    => $body,
1659
			'headers' => array(
1660
				'Accept' => 'application/json',
1661
			),
1662
		);
1663
1664
		add_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1665
		$response = Client::_wp_remote_request( Utils::fix_url_for_bad_hosts( $this->api_url( 'token' ) ), $args );
1666
		remove_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1667
1668
		if ( is_wp_error( $response ) ) {
1669
			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...
1670
		}
1671
1672
		$code   = wp_remote_retrieve_response_code( $response );
1673
		$entity = wp_remote_retrieve_body( $response );
1674
1675
		if ( $entity ) {
1676
			$json = json_decode( $entity );
1677
		} else {
1678
			$json = false;
1679
		}
1680
1681
		if ( 200 !== $code || ! empty( $json->error ) ) {
1682
			if ( empty( $json->error ) ) {
1683
				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...
1684
			}
1685
1686
			/* translators: Error description string. */
1687
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1688
1689
			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...
1690
		}
1691
1692
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1693
			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...
1694
		}
1695
1696
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1697
			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...
1698
		}
1699
1700
		if ( empty( $json->scope ) ) {
1701
			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...
1702
		}
1703
1704
		// TODO: get rid of the error silencer.
1705
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1706
		@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...
1707
		if ( empty( $role ) || empty( $hmac ) ) {
1708
			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...
1709
		}
1710
1711
		if ( $this->sign_role( $role ) !== $json->scope ) {
1712
			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...
1713
		}
1714
1715
		$cap = $roles->translate_role_to_cap( $role );
1716
		if ( ! $cap ) {
1717
			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...
1718
		}
1719
1720
		if ( ! current_user_can( $cap ) ) {
1721
			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...
1722
		}
1723
1724
		/**
1725
		 * Fires after user has successfully received an auth token.
1726
		 *
1727
		 * @since 3.9.0
1728
		 */
1729
		do_action( 'jetpack_user_authorized' );
1730
1731
		return (string) $json->access_token;
1732
	}
1733
1734
	/**
1735
	 * Increases the request timeout value to 30 seconds.
1736
	 *
1737
	 * @return int Returns 30.
1738
	 */
1739
	public function increase_timeout() {
1740
		return 30;
1741
	}
1742
1743
	/**
1744
	 * Builds a URL to the Jetpack connection auth page.
1745
	 *
1746
	 * @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...
1747
	 * @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...
1748
	 * @return string Connect URL.
1749
	 */
1750
	public function get_authorization_url( $user = null, $redirect = null ) {
1751
1752
		if ( empty( $user ) ) {
1753
			$user = wp_get_current_user();
1754
		}
1755
1756
		$roles       = new Roles();
1757
		$role        = $roles->translate_user_to_role( $user );
1758
		$signed_role = $this->sign_role( $role );
1759
1760
		/**
1761
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1762
		 * data processing.
1763
		 *
1764
		 * @since 8.0.0
1765
		 *
1766
		 * @param string $redirect_url Defaults to the site admin URL.
1767
		 */
1768
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1769
1770
		/**
1771
		 * Filter the URL to redirect the user back to when the authorization process
1772
		 * is complete.
1773
		 *
1774
		 * @since 8.0.0
1775
		 *
1776
		 * @param string $redirect_url Defaults to the site URL.
1777
		 */
1778
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1779
1780
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1781
1782
		/**
1783
		 * Filter the type of authorization.
1784
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1785
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1786
		 *
1787
		 * @since 4.3.3
1788
		 *
1789
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1790
		 */
1791
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1792
1793
		/**
1794
		 * Filters the user connection request data for additional property addition.
1795
		 *
1796
		 * @since 8.0.0
1797
		 *
1798
		 * @param array $request_data request data.
1799
		 */
1800
		$body = apply_filters(
1801
			'jetpack_connect_request_body',
1802
			array(
1803
				'response_type' => 'code',
1804
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1805
				'redirect_uri'  => add_query_arg(
1806
					array(
1807
						'action'   => 'authorize',
1808
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1809
						'redirect' => rawurlencode( $redirect ),
1810
					),
1811
					esc_url( $processing_url )
1812
				),
1813
				'state'         => $user->ID,
1814
				'scope'         => $signed_role,
1815
				'user_email'    => $user->user_email,
1816
				'user_login'    => $user->user_login,
1817
				'is_active'     => $this->is_active(),
1818
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1819
				'auth_type'     => $auth_type,
1820
				'secret'        => $secrets['secret_1'],
1821
				'blogname'      => get_option( 'blogname' ),
1822
				'site_url'      => site_url(),
1823
				'home_url'      => home_url(),
1824
				'site_icon'     => get_site_icon_url(),
1825
				'site_lang'     => get_locale(),
1826
				'site_created'  => $this->get_assumed_site_creation_date(),
1827
			)
1828
		);
1829
1830
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1831
1832
		$api_url = $this->api_url( 'authorize' );
1833
1834
		return add_query_arg( $body, $api_url );
1835
	}
1836
1837
	/**
1838
	 * Authorizes the user by obtaining and storing the user token.
1839
	 *
1840
	 * @param array $data The request data.
1841
	 * @return string|\WP_Error Returns a string on success.
1842
	 *                          Returns a \WP_Error on failure.
1843
	 */
1844
	public function authorize( $data = array() ) {
1845
		/**
1846
		 * Action fired when user authorization starts.
1847
		 *
1848
		 * @since 8.0.0
1849
		 */
1850
		do_action( 'jetpack_authorize_starting' );
1851
1852
		$roles = new Roles();
1853
		$role  = $roles->translate_current_user_to_role();
1854
1855
		if ( ! $role ) {
1856
			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...
1857
		}
1858
1859
		$cap = $roles->translate_role_to_cap( $role );
1860
		if ( ! $cap ) {
1861
			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...
1862
		}
1863
1864
		if ( ! empty( $data['error'] ) ) {
1865
			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...
1866
		}
1867
1868
		if ( ! isset( $data['state'] ) ) {
1869
			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...
1870
		}
1871
1872
		if ( ! ctype_digit( $data['state'] ) ) {
1873
			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...
1874
		}
1875
1876
		$current_user_id = get_current_user_id();
1877
		if ( $current_user_id !== (int) $data['state'] ) {
1878
			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...
1879
		}
1880
1881
		if ( empty( $data['code'] ) ) {
1882
			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...
1883
		}
1884
1885
		$token = $this->get_token( $data );
1886
1887 View Code Duplication
		if ( is_wp_error( $token ) ) {
1888
			$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...
1889
			if ( empty( $code ) ) {
1890
				$code = 'invalid_token';
1891
			}
1892
			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...
1893
		}
1894
1895
		if ( ! $token ) {
1896
			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...
1897
		}
1898
1899
		$is_master_user = ! $this->is_active();
1900
1901
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
1902
1903
		if ( ! $is_master_user ) {
1904
			/**
1905
			 * Action fired when a secondary user has been authorized.
1906
			 *
1907
			 * @since 8.0.0
1908
			 */
1909
			do_action( 'jetpack_authorize_ending_linked' );
1910
			return 'linked';
1911
		}
1912
1913
		/**
1914
		 * Action fired when the master user has been authorized.
1915
		 *
1916
		 * @since 8.0.0
1917
		 *
1918
		 * @param array $data The request data.
1919
		 */
1920
		do_action( 'jetpack_authorize_ending_authorized', $data );
1921
1922
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
1923
1924
		// Start nonce cleaner.
1925
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
1926
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
1927
1928
		return 'authorized';
1929
	}
1930
1931
	/**
1932
	 * Disconnects from the Jetpack servers.
1933
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1934
	 */
1935
	public function disconnect_site() {
1936
1937
	}
1938
1939
	/**
1940
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1941
	 *
1942
	 * @param string $text The string to hash.
1943
	 * @return string
1944
	 */
1945
	public function sha1_base64( $text ) {
1946
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1947
	}
1948
1949
	/**
1950
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1951
	 *
1952
	 * @param string $domain The domain to check.
1953
	 *
1954
	 * @return bool|WP_Error
1955
	 */
1956
	public function is_usable_domain( $domain ) {
1957
1958
		// If it's empty, just fail out.
1959
		if ( ! $domain ) {
1960
			return new \WP_Error(
1961
				'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...
1962
				/* translators: %1$s is a domain name. */
1963
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1964
			);
1965
		}
1966
1967
		/**
1968
		 * Skips the usuable domain check when connecting a site.
1969
		 *
1970
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1971
		 *
1972
		 * @since 4.1.0
1973
		 *
1974
		 * @param bool If the check should be skipped. Default false.
1975
		 */
1976
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1977
			return true;
1978
		}
1979
1980
		// None of the explicit localhosts.
1981
		$forbidden_domains = array(
1982
			'wordpress.com',
1983
			'localhost',
1984
			'localhost.localdomain',
1985
			'127.0.0.1',
1986
			'local.wordpress.test',         // VVV pattern.
1987
			'local.wordpress-trunk.test',   // VVV pattern.
1988
			'src.wordpress-develop.test',   // VVV pattern.
1989
			'build.wordpress-develop.test', // VVV pattern.
1990
		);
1991 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1992
			return new \WP_Error(
1993
				'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...
1994
				sprintf(
1995
					/* translators: %1$s is a domain name. */
1996
					__(
1997
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1998
						'jetpack'
1999
					),
2000
					$domain
2001
				)
2002
			);
2003
		}
2004
2005
		// No .test or .local domains.
2006 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
2007
			return new \WP_Error(
2008
				'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...
2009
				sprintf(
2010
					/* translators: %1$s is a domain name. */
2011
					__(
2012
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
2013
						'jetpack'
2014
					),
2015
					$domain
2016
				)
2017
			);
2018
		}
2019
2020
		// No WPCOM subdomains.
2021 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
2022
			return new \WP_Error(
2023
				'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...
2024
				sprintf(
2025
					/* translators: %1$s is a domain name. */
2026
					__(
2027
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
2028
						'jetpack'
2029
					),
2030
					$domain
2031
				)
2032
			);
2033
		}
2034
2035
		// If PHP was compiled without support for the Filter module (very edge case).
2036
		if ( ! function_exists( 'filter_var' ) ) {
2037
			// Just pass back true for now, and let wpcom sort it out.
2038
			return true;
2039
		}
2040
2041
		return true;
2042
	}
2043
2044
	/**
2045
	 * Gets the requested token.
2046
	 *
2047
	 * Tokens are one of two types:
2048
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
2049
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
2050
	 *    are not associated with a user account. They represent the site's connection with
2051
	 *    the Jetpack servers.
2052
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
2053
	 *
2054
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
2055
	 * token, and $private is a secret that should never be displayed anywhere or sent
2056
	 * over the network; it's used only for signing things.
2057
	 *
2058
	 * Blog Tokens can be "Normal" or "Special".
2059
	 * * Normal: The result of a normal connection flow. They look like
2060
	 *   "{$random_string_1}.{$random_string_2}"
2061
	 *   That is, $token_key and $private are both random strings.
2062
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
2063
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
2064
	 *   constant (rare).
2065
	 * * Special: A connection token for sites that have gone through an alternative
2066
	 *   connection flow. They look like:
2067
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
2068
	 *   That is, $private is a random string and $token_key has a special structure with
2069
	 *   lots of semicolons.
2070
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
2071
	 *   JETPACK_BLOG_TOKEN constant.
2072
	 *
2073
	 * In particular, note that Normal Blog Tokens never start with ";" and that
2074
	 * Special Blog Tokens always do.
2075
	 *
2076
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
2077
	 * order:
2078
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
2079
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
2080
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
2081
	 *
2082
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
2083
	 * @param string|false $token_key If provided, check that the token matches the provided input.
2084
	 * @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.
2085
	 *
2086
	 * @return object|false
2087
	 */
2088
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
2089
		$possible_special_tokens = array();
2090
		$possible_normal_tokens  = array();
2091
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
2092
2093
		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...
2094
			if ( ! $user_tokens ) {
2095
				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...
2096
			}
2097
			if ( self::JETPACK_MASTER_USER === $user_id ) {
2098
				$user_id = \Jetpack_Options::get_option( 'master_user' );
2099
				if ( ! $user_id ) {
2100
					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...
2101
				}
2102
			}
2103
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
2104
				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...
2105
			}
2106
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
2107 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
2108
				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...
2109
			}
2110 View Code Duplication
			if ( $user_token_chunks[2] !== (string) $user_id ) {
2111
				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...
2112
			}
2113
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
2114
		} else {
2115
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
2116
			if ( $stored_blog_token ) {
2117
				$possible_normal_tokens[] = $stored_blog_token;
2118
			}
2119
2120
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
2121
2122
			if ( $defined_tokens_string ) {
2123
				$defined_tokens = explode( ',', $defined_tokens_string );
2124
				foreach ( $defined_tokens as $defined_token ) {
2125
					if ( ';' === $defined_token[0] ) {
2126
						$possible_special_tokens[] = $defined_token;
2127
					} else {
2128
						$possible_normal_tokens[] = $defined_token;
2129
					}
2130
				}
2131
			}
2132
		}
2133
2134
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2135
			$possible_tokens = $possible_normal_tokens;
2136
		} else {
2137
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
2138
		}
2139
2140
		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...
2141
			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...
2142
		}
2143
2144
		$valid_token = false;
2145
2146
		if ( false === $token_key ) {
2147
			// Use first token.
2148
			$valid_token = $possible_tokens[0];
2149
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2150
			// Use first normal token.
2151
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
2152
		} else {
2153
			// Use the token matching $token_key or false if none.
2154
			// Ensure we check the full key.
2155
			$token_check = rtrim( $token_key, '.' ) . '.';
2156
2157
			foreach ( $possible_tokens as $possible_token ) {
2158
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
2159
					$valid_token = $possible_token;
2160
					break;
2161
				}
2162
			}
2163
		}
2164
2165
		if ( ! $valid_token ) {
2166
			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...
2167
		}
2168
2169
		return (object) array(
2170
			'secret'           => $valid_token,
2171
			'external_user_id' => (int) $user_id,
2172
		);
2173
	}
2174
2175
	/**
2176
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2177
	 * since it is passed by reference to various methods.
2178
	 * Capture it here so we can verify the signature later.
2179
	 *
2180
	 * @param array $methods an array of available XMLRPC methods.
2181
	 * @return array the same array, since this method doesn't add or remove anything.
2182
	 */
2183
	public function xmlrpc_methods( $methods ) {
2184
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
2185
		return $methods;
2186
	}
2187
2188
	/**
2189
	 * Resets the raw post data parameter for testing purposes.
2190
	 */
2191
	public function reset_raw_post_data() {
2192
		$this->raw_post_data = null;
2193
	}
2194
2195
	/**
2196
	 * Registering an additional method.
2197
	 *
2198
	 * @param array $methods an array of available XMLRPC methods.
2199
	 * @return array the amended array in case the method is added.
2200
	 */
2201
	public function public_xmlrpc_methods( $methods ) {
2202
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2203
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2204
		}
2205
		return $methods;
2206
	}
2207
2208
	/**
2209
	 * Handles a getOptions XMLRPC method call.
2210
	 *
2211
	 * @param array $args method call arguments.
2212
	 * @return an amended XMLRPC server options array.
2213
	 */
2214
	public function jetpack_get_options( $args ) {
2215
		global $wp_xmlrpc_server;
2216
2217
		$wp_xmlrpc_server->escape( $args );
2218
2219
		$username = $args[1];
2220
		$password = $args[2];
2221
2222
		$user = $wp_xmlrpc_server->login( $username, $password );
2223
		if ( ! $user ) {
2224
			return $wp_xmlrpc_server->error;
2225
		}
2226
2227
		$options   = array();
2228
		$user_data = $this->get_connected_user_data();
2229
		if ( is_array( $user_data ) ) {
2230
			$options['jetpack_user_id']         = array(
2231
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2232
				'readonly' => true,
2233
				'value'    => $user_data['ID'],
2234
			);
2235
			$options['jetpack_user_login']      = array(
2236
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2237
				'readonly' => true,
2238
				'value'    => $user_data['login'],
2239
			);
2240
			$options['jetpack_user_email']      = array(
2241
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2242
				'readonly' => true,
2243
				'value'    => $user_data['email'],
2244
			);
2245
			$options['jetpack_user_site_count'] = array(
2246
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2247
				'readonly' => true,
2248
				'value'    => $user_data['site_count'],
2249
			);
2250
		}
2251
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2252
		$args                           = stripslashes_deep( $args );
2253
		return $wp_xmlrpc_server->wp_getOptions( $args );
2254
	}
2255
2256
	/**
2257
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2258
	 *
2259
	 * @param array $options standard Core options.
2260
	 * @return array amended options.
2261
	 */
2262
	public function xmlrpc_options( $options ) {
2263
		$jetpack_client_id = false;
2264
		if ( $this->is_active() ) {
2265
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2266
		}
2267
		$options['jetpack_version'] = array(
2268
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2269
			'readonly' => true,
2270
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2271
		);
2272
2273
		$options['jetpack_client_id'] = array(
2274
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2275
			'readonly' => true,
2276
			'value'    => $jetpack_client_id,
2277
		);
2278
		return $options;
2279
	}
2280
2281
	/**
2282
	 * Resets the saved authentication state in between testing requests.
2283
	 */
2284
	public function reset_saved_auth_state() {
2285
		$this->xmlrpc_verification = null;
2286
	}
2287
2288
	/**
2289
	 * Sign a user role with the master access token.
2290
	 * If not specified, will default to the current user.
2291
	 *
2292
	 * @access public
2293
	 *
2294
	 * @param string $role    User role.
2295
	 * @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...
2296
	 * @return string Signed user role.
2297
	 */
2298
	public function sign_role( $role, $user_id = null ) {
2299
		if ( empty( $user_id ) ) {
2300
			$user_id = (int) get_current_user_id();
2301
		}
2302
2303
		if ( ! $user_id ) {
2304
			return false;
2305
		}
2306
2307
		$token = $this->get_access_token();
2308
		if ( ! $token || is_wp_error( $token ) ) {
2309
			return false;
2310
		}
2311
2312
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2313
	}
2314
2315
	/**
2316
	 * Set the plugin instance.
2317
	 *
2318
	 * @param Plugin $plugin_instance The plugin instance.
2319
	 *
2320
	 * @return $this
2321
	 */
2322
	public function set_plugin_instance( Plugin $plugin_instance ) {
2323
		$this->plugin = $plugin_instance;
2324
2325
		return $this;
2326
	}
2327
2328
	/**
2329
	 * Retrieve the plugin management object.
2330
	 *
2331
	 * @return Plugin
2332
	 */
2333
	public function get_plugin() {
2334
		return $this->plugin;
2335
	}
2336
2337
	/**
2338
	 * Get all connected plugins information, excluding those disconnected by user.
2339
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2340
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2341
	 * so please make sure not to run the method too early in the code.
2342
	 *
2343
	 * @return array|WP_Error
2344
	 */
2345
	public function get_connected_plugins() {
2346
		$maybe_plugins = Plugin_Storage::get_all( true );
2347
2348
		if ( $maybe_plugins instanceof WP_Error ) {
2349
			return $maybe_plugins;
2350
		}
2351
2352
		return $maybe_plugins;
2353
	}
2354
2355
	/**
2356
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2357
	 * Note: this method does not remove any access tokens.
2358
	 *
2359
	 * @return bool
2360
	 */
2361
	public function disable_plugin() {
2362
		if ( ! $this->plugin ) {
2363
			return false;
2364
		}
2365
2366
		return $this->plugin->disable();
2367
	}
2368
2369
	/**
2370
	 * Force plugin reconnect after user-initiated disconnect.
2371
	 * After its called, the plugin will be allowed to use the connection again.
2372
	 * Note: this method does not initialize access tokens.
2373
	 *
2374
	 * @return bool
2375
	 */
2376
	public function enable_plugin() {
2377
		if ( ! $this->plugin ) {
2378
			return false;
2379
		}
2380
2381
		return $this->plugin->enable();
2382
	}
2383
2384
	/**
2385
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2386
	 * If no plugin slug was passed into the constructor, always returns true.
2387
	 *
2388
	 * @return bool
2389
	 */
2390
	public function is_plugin_enabled() {
2391
		if ( ! $this->plugin ) {
2392
			return true;
2393
		}
2394
2395
		return $this->plugin->is_enabled();
2396
	}
2397
2398
}
2399