Completed
Push — add/handling-connection-errors ( 6caa3b...241bc5 )
by
unknown
12:48 queued 05:35
created

Manager::get_secrets()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 2
dl 0
loc 18
rs 9.6666
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\Status;
13
use Automattic\Jetpack\Tracking;
14
use WP_Error;
15
16
/**
17
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
18
 * and Jetpack.
19
 */
20
class Manager {
21
22
	const SECRETS_MISSING        = 'secrets_missing';
23
	const SECRETS_EXPIRED        = 'secrets_expired';
24
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
25
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
26
	const JETPACK_MASTER_USER    = true;
27
28
	/**
29
	 * The procedure that should be run to generate secrets.
30
	 *
31
	 * @var Callable
32
	 */
33
	protected $secret_callable;
34
35
	/**
36
	 * A copy of the raw POST data for signature verification purposes.
37
	 *
38
	 * @var String
39
	 */
40
	protected $raw_post_data;
41
42
	/**
43
	 * Verification data needs to be stored to properly verify everything.
44
	 *
45
	 * @var Object
46
	 */
47
	private $xmlrpc_verification = null;
48
49
	/**
50
	 * Plugin management object.
51
	 *
52
	 * @var Plugin
53
	 */
54
	private $plugin = null;
55
56
	/**
57
	 * Initialize the object.
58
	 * Make sure to call the "Configure" first.
59
	 *
60
	 * @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...
61
	 *
62
	 * @see \Automattic\Jetpack\Config
63
	 */
64
	public function __construct( $plugin_slug = null ) {
65
		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...
66
			$this->set_plugin_instance( new Plugin( $plugin_slug ) );
67
		}
68
	}
69
70
	/**
71
	 * Initializes required listeners. This is done separately from the constructors
72
	 * because some objects sometimes need to instantiate separate objects of this class.
73
	 *
74
	 * @todo Implement a proper nonce verification.
75
	 */
76
	public static function configure() {
77
		$manager = new self();
78
79
		add_filter(
80
			'jetpack_constant_default_value',
81
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
82
			10,
83
			2
84
		);
85
86
		$manager->setup_xmlrpc_handlers(
87
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
88
			$manager->is_active(),
89
			$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...
90
		);
91
92
		$manager->error_handler = Error_Handler::get_instance();
0 ignored issues
show
Bug introduced by
The property error_handler 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...
93
94
		if ( $manager->is_active() ) {
95
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
96
		} else {
97
			add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
98
		}
99
100
		add_action( 'jetpack_clean_nonces', array( $manager, 'clean_nonces' ) );
101
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
102
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
103
		}
104
105
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
106
107
		add_filter( 'map_meta_cap', array( $manager, 'jetpack_connection_custom_caps' ), 1, 4 );
108
	}
109
110
	/**
111
	 * Sets up the XMLRPC request handlers.
112
	 *
113
	 * @param array                  $request_params incoming request parameters.
114
	 * @param Boolean                $is_active whether the connection is currently active.
115
	 * @param Boolean                $is_signed whether the signature check has been successful.
116
	 * @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...
117
	 */
118
	public function setup_xmlrpc_handlers(
119
		$request_params,
120
		$is_active,
121
		$is_signed,
122
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
123
	) {
124
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
125
126
		if (
127
			! isset( $request_params['for'] )
128
			|| 'jetpack' !== $request_params['for']
129
		) {
130
			return false;
131
		}
132
133
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
134
		if (
135
			isset( $request_params['jetpack'] )
136
			&& 'comms' === $request_params['jetpack']
137
		) {
138
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
139
				// Use the real constant here for WordPress' sake.
140
				define( 'XMLRPC_REQUEST', true );
141
			}
142
143
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
144
145
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
146
		}
147
148
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
149
			return false;
150
		}
151
		// Display errors can cause the XML to be not well formed.
152
		@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...
153
154
		if ( $xmlrpc_server ) {
155
			$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...
156
		} else {
157
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
158
		}
159
160
		$this->require_jetpack_authentication();
161
162
		if ( $is_active ) {
163
			// Hack to preserve $HTTP_RAW_POST_DATA.
164
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
165
166
			if ( $is_signed ) {
167
				// The actual API methods.
168
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
169
			} else {
170
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
171
				// active Jetpack connection, so that additional users can link their account.
172
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
173
			}
174
		} else {
175
			// The bootstrap API methods.
176
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
177
178
			if ( $is_signed ) {
179
				// The jetpack Provision method is available for blog-token-signed requests.
180
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
181
			} else {
182
				new XMLRPC_Connector( $this );
183
			}
184
		}
185
186
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
187
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
188
		return true;
189
	}
190
191
	/**
192
	 * Initializes the REST API connector on the init hook.
193
	 */
194
	public function initialize_rest_api_registration_connector() {
195
		new REST_Connector( $this );
196
	}
197
198
	/**
199
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
200
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
201
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
202
	 * which is accessible via a different URI. Most of the below is copied directly
203
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
204
	 *
205
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
206
	 */
207
	public function alternate_xmlrpc() {
208
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
209
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
210
		global $HTTP_RAW_POST_DATA;
211
212
		// Some browser-embedded clients send cookies. We don't want them.
213
		$_COOKIE = array();
214
215
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
216
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
217
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
218
		}
219
220
		// phpcs:enable
221
222
		include_once ABSPATH . 'wp-admin/includes/admin.php';
223
		include_once ABSPATH . WPINC . '/class-IXR.php';
224
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
225
226
		/**
227
		 * Filters the class used for handling XML-RPC requests.
228
		 *
229
		 * @since 3.1.0
230
		 *
231
		 * @param string $class The name of the XML-RPC server class.
232
		 */
233
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
234
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
235
236
		// Fire off the request.
237
		nocache_headers();
238
		$wp_xmlrpc_server->serve_request();
239
240
		exit;
241
	}
242
243
	/**
244
	 * Removes all XML-RPC methods that are not `jetpack.*`.
245
	 * Only used in our alternate XML-RPC endpoint, where we want to
246
	 * ensure that Core and other plugins' methods are not exposed.
247
	 *
248
	 * @param array $methods a list of registered WordPress XMLRPC methods.
249
	 * @return array filtered $methods
250
	 */
251
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
252
		$jetpack_methods = array();
253
254
		foreach ( $methods as $method => $callback ) {
255
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
256
				$jetpack_methods[ $method ] = $callback;
257
			}
258
		}
259
260
		return $jetpack_methods;
261
	}
262
263
	/**
264
	 * Removes all other authentication methods not to allow other
265
	 * methods to validate unauthenticated requests.
266
	 */
267
	public function require_jetpack_authentication() {
268
		// Don't let anyone authenticate.
269
		$_COOKIE = array();
270
		remove_all_filters( 'authenticate' );
271
		remove_all_actions( 'wp_login_failed' );
272
273
		if ( $this->is_active() ) {
274
			// Allow Jetpack authentication.
275
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
276
		}
277
	}
278
279
	/**
280
	 * Authenticates XML-RPC and other requests from the Jetpack Server
281
	 *
282
	 * @param WP_User|Mixed $user user object if authenticated.
283
	 * @param String        $username username.
284
	 * @param String        $password password string.
285
	 * @return WP_User|Mixed authenticated user or error.
286
	 */
287
	public function authenticate_jetpack( $user, $username, $password ) {
288
		if ( is_a( $user, '\\WP_User' ) ) {
289
			return $user;
290
		}
291
292
		$token_details = $this->verify_xml_rpc_signature();
293
294
		if ( ! $token_details ) {
295
			return $user;
296
		}
297
298
		if ( 'user' !== $token_details['type'] ) {
299
			return $user;
300
		}
301
302
		if ( ! $token_details['user_id'] ) {
303
			return $user;
304
		}
305
306
		nocache_headers();
307
308
		return new \WP_User( $token_details['user_id'] );
309
	}
310
311
	/**
312
	 * Verifies the signature of the current request.
313
	 *
314
	 * @return false|array
315
	 */
316
	public function verify_xml_rpc_signature() {
317
		if ( is_null( $this->xmlrpc_verification ) ) {
318
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
319
320
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
321
				/**
322
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
323
				 *
324
				 * @since 7.5.0
325
				 *
326
				 * @param WP_Error $signature_verification_error The verification error
327
				 */
328
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
329
330
				Error_Handler::get_instance()->report_error( $this->xmlrpc_verification );
331
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
		$has_blog_id    = (bool) \Jetpack_Options::get_option( 'id' );
523
		$has_blog_token = (bool) $this->get_access_token( false );
524
		return $has_blog_id && $has_blog_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
	 * Sets the Connection custom capabilities.
1102
	 *
1103
	 * @param string[] $caps    Array of the user's capabilities.
1104
	 * @param string   $cap     Capability name.
1105
	 * @param int      $user_id The user ID.
1106
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1107
	 */
1108
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) {
1109
		$is_development_mode = ( new Status() )->is_development_mode();
1110
		switch ( $cap ) {
1111
			case 'jetpack_connect':
1112
			case 'jetpack_reconnect':
1113
				if ( $is_development_mode ) {
1114
					$caps = array( 'do_not_allow' );
1115
					break;
1116
				}
1117
				// Pass through. If it's not development mode, these should match disconnect.
1118
				// Let users disconnect if it's development mode, just in case things glitch.
1119
			case 'jetpack_disconnect':
1120
				/**
1121
				 * Filters the jetpack_disconnect capability.
1122
				 *
1123
				 * @since 8.7.0
1124
				 *
1125
				 * @param array An array containing the capability name.
1126
				 */
1127
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1128
				break;
1129
			case 'jetpack_connect_user':
1130
				if ( $is_development_mode ) {
1131
					$caps = array( 'do_not_allow' );
1132
					break;
1133
				}
1134
				$caps = array( 'read' );
1135
				break;
1136
		}
1137
		return $caps;
1138
	}
1139
1140
	/**
1141
	 * Builds the timeout limit for queries talking with the wpcom servers.
1142
	 *
1143
	 * Based on local php max_execution_time in php.ini
1144
	 *
1145
	 * @since 5.4
1146
	 * @return int
1147
	 **/
1148
	public function get_max_execution_time() {
1149
		$timeout = (int) ini_get( 'max_execution_time' );
1150
1151
		// Ensure exec time set in php.ini.
1152
		if ( ! $timeout ) {
1153
			$timeout = 30;
1154
		}
1155
		return $timeout;
1156
	}
1157
1158
	/**
1159
	 * Sets a minimum request timeout, and returns the current timeout
1160
	 *
1161
	 * @since 5.4
1162
	 * @param Integer $min_timeout the minimum timeout value.
1163
	 **/
1164 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1165
		$timeout = $this->get_max_execution_time();
1166
		if ( $timeout < $min_timeout ) {
1167
			$timeout = $min_timeout;
1168
			set_time_limit( $timeout );
1169
		}
1170
		return $timeout;
1171
	}
1172
1173
	/**
1174
	 * Get our assumed site creation date.
1175
	 * Calculated based on the earlier date of either:
1176
	 * - Earliest admin user registration date.
1177
	 * - Earliest date of post of any post type.
1178
	 *
1179
	 * @since 7.2.0
1180
	 *
1181
	 * @return string Assumed site creation date and time.
1182
	 */
1183
	public function get_assumed_site_creation_date() {
1184
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1185
		if ( ! empty( $cached_date ) ) {
1186
			return $cached_date;
1187
		}
1188
1189
		$earliest_registered_users  = get_users(
1190
			array(
1191
				'role'    => 'administrator',
1192
				'orderby' => 'user_registered',
1193
				'order'   => 'ASC',
1194
				'fields'  => array( 'user_registered' ),
1195
				'number'  => 1,
1196
			)
1197
		);
1198
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1199
1200
		$earliest_posts = get_posts(
1201
			array(
1202
				'posts_per_page' => 1,
1203
				'post_type'      => 'any',
1204
				'post_status'    => 'any',
1205
				'orderby'        => 'date',
1206
				'order'          => 'ASC',
1207
			)
1208
		);
1209
1210
		// If there are no posts at all, we'll count only on user registration date.
1211
		if ( $earliest_posts ) {
1212
			$earliest_post_date = $earliest_posts[0]->post_date;
1213
		} else {
1214
			$earliest_post_date = PHP_INT_MAX;
1215
		}
1216
1217
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1218
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1219
1220
		return $assumed_date;
1221
	}
1222
1223
	/**
1224
	 * Adds the activation source string as a parameter to passed arguments.
1225
	 *
1226
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1227
	 *
1228
	 * @param array $args arguments that need to have the source added.
1229
	 * @return array $amended arguments.
1230
	 */
1231 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1232
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1233
1234
		if ( $activation_source_name ) {
1235
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1236
			$args['_as'] = urlencode( $activation_source_name );
1237
		}
1238
1239
		if ( $activation_source_keyword ) {
1240
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1241
			$args['_ak'] = urlencode( $activation_source_keyword );
1242
		}
1243
1244
		return $args;
1245
	}
1246
1247
	/**
1248
	 * Returns the callable that would be used to generate secrets.
1249
	 *
1250
	 * @return Callable a function that returns a secure string to be used as a secret.
1251
	 */
1252
	protected function get_secret_callable() {
1253
		if ( ! isset( $this->secret_callable ) ) {
1254
			/**
1255
			 * Allows modification of the callable that is used to generate connection secrets.
1256
			 *
1257
			 * @param Callable a function or method that returns a secret string.
1258
			 */
1259
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', array( $this, 'secret_callable_method' ) );
1260
		}
1261
1262
		return $this->secret_callable;
1263
	}
1264
1265
	/**
1266
	 * Runs the wp_generate_password function with the required parameters. This is the
1267
	 * default implementation of the secret callable, can be overridden using the
1268
	 * jetpack_connection_secret_generator filter.
1269
	 *
1270
	 * @return String $secret value.
1271
	 */
1272
	private function secret_callable_method() {
1273
		return wp_generate_password( 32, false );
1274
	}
1275
1276
	/**
1277
	 * Generates 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.
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...
1281
	 * @param Integer $exp     Expiration time in seconds.
1282
	 */
1283
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1284
		if ( false === $user_id ) {
1285
			$user_id = get_current_user_id();
1286
		}
1287
1288
		$callable = $this->get_secret_callable();
1289
1290
		$secrets = \Jetpack_Options::get_raw_option(
1291
			self::SECRETS_OPTION_NAME,
1292
			array()
1293
		);
1294
1295
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1296
1297
		if (
1298
			isset( $secrets[ $secret_name ] ) &&
1299
			$secrets[ $secret_name ]['exp'] > time()
1300
		) {
1301
			return $secrets[ $secret_name ];
1302
		}
1303
1304
		$secret_value = array(
1305
			'secret_1' => call_user_func( $callable ),
1306
			'secret_2' => call_user_func( $callable ),
1307
			'exp'      => time() + $exp,
1308
		);
1309
1310
		$secrets[ $secret_name ] = $secret_value;
1311
1312
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1313
		return $secrets[ $secret_name ];
1314
	}
1315
1316
	/**
1317
	 * Returns two secret tokens and the end of life timestamp for them.
1318
	 *
1319
	 * @param String  $action  The action name.
1320
	 * @param Integer $user_id The user identifier.
1321
	 * @return string|array an array of secrets or an error string.
1322
	 */
1323
	public function get_secrets( $action, $user_id ) {
1324
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1325
		$secrets     = \Jetpack_Options::get_raw_option(
1326
			self::SECRETS_OPTION_NAME,
1327
			array()
1328
		);
1329
1330
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1331
			return self::SECRETS_MISSING;
1332
		}
1333
1334
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1335
			$this->delete_secrets( $action, $user_id );
1336
			return self::SECRETS_EXPIRED;
1337
		}
1338
1339
		return $secrets[ $secret_name ];
1340
	}
1341
1342
	/**
1343
	 * Deletes secret tokens in case they, for example, have expired.
1344
	 *
1345
	 * @param String  $action  The action name.
1346
	 * @param Integer $user_id The user identifier.
1347
	 */
1348
	public function delete_secrets( $action, $user_id ) {
1349
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1350
		$secrets     = \Jetpack_Options::get_raw_option(
1351
			self::SECRETS_OPTION_NAME,
1352
			array()
1353
		);
1354
		if ( isset( $secrets[ $secret_name ] ) ) {
1355
			unset( $secrets[ $secret_name ] );
1356
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1357
		}
1358
	}
1359
1360
	/**
1361
	 * Deletes all connection tokens and transients from the local Jetpack site.
1362
	 * If the plugin object has been provided in the constructor, the function first checks
1363
	 * whether it's the only active connection.
1364
	 * If there are any other connections, the function will do nothing and return `false`
1365
	 * (unless `$ignore_connected_plugins` is set to `true`).
1366
	 *
1367
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1368
	 *
1369
	 * @return bool True if disconnected successfully, false otherwise.
1370
	 */
1371
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1372 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1373
			return false;
1374
		}
1375
1376
		/**
1377
		 * Fires upon the disconnect attempt.
1378
		 * Return `false` to prevent the disconnect.
1379
		 *
1380
		 * @since 8.7.0
1381
		 */
1382
		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...
1383
			return false;
1384
		}
1385
1386
		\Jetpack_Options::delete_option(
1387
			array(
1388
				'blog_token',
1389
				'user_token',
1390
				'user_tokens',
1391
				'master_user',
1392
				'time_diff',
1393
				'fallback_no_verify_ssl_certs',
1394
			)
1395
		);
1396
1397
		\Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
1398
1399
		// Delete cached connected user data.
1400
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1401
		delete_transient( $transient_key );
1402
1403
		// Delete all XML-RPC errors.
1404
		Error_Handler::get_instance()->delete_all_errors();
1405
1406
		return true;
1407
	}
1408
1409
	/**
1410
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1411
	 * If the plugin object has been provided in the constructor, the function first check
1412
	 * whether it's the only active connection.
1413
	 * If there are any other connections, the function will do nothing and return `false`
1414
	 * (unless `$ignore_connected_plugins` is set to `true`).
1415
	 *
1416
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1417
	 *
1418
	 * @return bool True if disconnected successfully, false otherwise.
1419
	 */
1420
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1421 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1422
			return false;
1423
		}
1424
1425
		/**
1426
		 * Fires upon the disconnect attempt.
1427
		 * Return `false` to prevent the disconnect.
1428
		 *
1429
		 * @since 8.7.0
1430
		 */
1431
		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...
1432
			return false;
1433
		}
1434
1435
		$xml = new \Jetpack_IXR_Client();
1436
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1437
1438
		return true;
1439
	}
1440
1441
	/**
1442
	 * Disconnect the plugin and remove the tokens.
1443
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1444
	 * This is a proxy method to simplify the Connection package API.
1445
	 *
1446
	 * @see Manager::disable_plugin()
1447
	 * @see Manager::disconnect_site_wpcom()
1448
	 * @see Manager::delete_all_connection_tokens()
1449
	 *
1450
	 * @return bool
1451
	 */
1452
	public function remove_connection() {
1453
		$this->disable_plugin();
1454
		$this->disconnect_site_wpcom();
1455
		$this->delete_all_connection_tokens();
1456
1457
		return true;
1458
	}
1459
1460
	/**
1461
	 * Responds to a WordPress.com call to register the current site.
1462
	 * Should be changed to protected.
1463
	 *
1464
	 * @param array $registration_data Array of [ secret_1, user_id ].
1465
	 */
1466
	public function handle_registration( array $registration_data ) {
1467
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1468
		if ( empty( $registration_user_id ) ) {
1469
			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...
1470
		}
1471
1472
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1473
	}
1474
1475
	/**
1476
	 * Verify a Previously Generated Secret.
1477
	 *
1478
	 * @param string $action   The type of secret to verify.
1479
	 * @param string $secret_1 The secret string to compare to what is stored.
1480
	 * @param int    $user_id  The user ID of the owner of the secret.
1481
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1482
	 */
1483
	public function verify_secrets( $action, $secret_1, $user_id ) {
1484
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1485
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1486
			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...
1487
		}
1488
1489
		$user = get_user_by( 'id', $user_id );
1490
1491
		/**
1492
		 * We've begun verifying the previously generated secret.
1493
		 *
1494
		 * @since 7.5.0
1495
		 *
1496
		 * @param string   $action The type of secret to verify.
1497
		 * @param \WP_User $user The user object.
1498
		 */
1499
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1500
1501
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1502
			/**
1503
			 * Verifying of the previously generated secret has failed.
1504
			 *
1505
			 * @since 7.5.0
1506
			 *
1507
			 * @param string    $action  The type of secret to verify.
1508
			 * @param \WP_User  $user The user object.
1509
			 * @param \WP_Error $error The error object.
1510
			 */
1511
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1512
1513
			return $error;
1514
		};
1515
1516
		$stored_secrets = $this->get_secrets( $action, $user_id );
1517
		$this->delete_secrets( $action, $user_id );
1518
1519
		$error = null;
1520
		if ( empty( $secret_1 ) ) {
1521
			$error = $return_error(
1522
				new \WP_Error(
1523
					'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...
1524
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1525
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1526
					400
1527
				)
1528
			);
1529
		} elseif ( ! is_string( $secret_1 ) ) {
1530
			$error = $return_error(
1531
				new \WP_Error(
1532
					'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...
1533
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1534
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1535
					400
1536
				)
1537
			);
1538
		} elseif ( empty( $user_id ) ) {
1539
			// $user_id is passed around during registration as "state".
1540
			$error = $return_error(
1541
				new \WP_Error(
1542
					'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...
1543
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1544
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1545
					400
1546
				)
1547
			);
1548
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1549
			$error = $return_error(
1550
				new \WP_Error(
1551
					'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...
1552
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1553
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1554
					400
1555
				)
1556
			);
1557
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1558
			$error = $return_error(
1559
				new \WP_Error(
1560
					'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...
1561
					__( 'Verification secrets not found', 'jetpack' ),
1562
					400
1563
				)
1564
			);
1565
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1566
			$error = $return_error(
1567
				new \WP_Error(
1568
					'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...
1569
					__( 'Verification took too long', 'jetpack' ),
1570
					400
1571
				)
1572
			);
1573
		} elseif ( ! $stored_secrets ) {
1574
			$error = $return_error(
1575
				new \WP_Error(
1576
					'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...
1577
					__( 'Verification secrets are empty', 'jetpack' ),
1578
					400
1579
				)
1580
			);
1581
		} elseif ( is_wp_error( $stored_secrets ) ) {
1582
			$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...
1583
			$error = $return_error( $stored_secrets );
1584
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1585
			$error = $return_error(
1586
				new \WP_Error(
1587
					'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...
1588
					__( 'Verification secrets are incomplete', 'jetpack' ),
1589
					400
1590
				)
1591
			);
1592
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1593
			$error = $return_error(
1594
				new \WP_Error(
1595
					'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...
1596
					__( 'Secret mismatch', 'jetpack' ),
1597
					400
1598
				)
1599
			);
1600
		}
1601
1602
		// Something went wrong during the checks, returning the error.
1603
		if ( ! empty( $error ) ) {
1604
			return $error;
1605
		}
1606
1607
		/**
1608
		 * We've succeeded at verifying the previously generated secret.
1609
		 *
1610
		 * @since 7.5.0
1611
		 *
1612
		 * @param string   $action The type of secret to verify.
1613
		 * @param \WP_User $user The user object.
1614
		 */
1615
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1616
1617
		return $stored_secrets['secret_2'];
1618
	}
1619
1620
	/**
1621
	 * Responds to a WordPress.com call to authorize the current user.
1622
	 * Should be changed to protected.
1623
	 */
1624
	public function handle_authorization() {
1625
1626
	}
1627
1628
	/**
1629
	 * Obtains the auth token.
1630
	 *
1631
	 * @param array $data The request data.
1632
	 * @return object|\WP_Error Returns the auth token on success.
1633
	 *                          Returns a \WP_Error on failure.
1634
	 */
1635
	public function get_token( $data ) {
1636
		$roles = new Roles();
1637
		$role  = $roles->translate_current_user_to_role();
1638
1639
		if ( ! $role ) {
1640
			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...
1641
		}
1642
1643
		$client_secret = $this->get_access_token();
1644
		if ( ! $client_secret ) {
1645
			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...
1646
		}
1647
1648
		/**
1649
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1650
		 * data processing.
1651
		 *
1652
		 * @since 8.0.0
1653
		 *
1654
		 * @param string $redirect_url Defaults to the site admin URL.
1655
		 */
1656
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1657
1658
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1659
1660
		/**
1661
		* Filter the URL to redirect the user back to when the authentication process
1662
		* is complete.
1663
		*
1664
		* @since 8.0.0
1665
		*
1666
		* @param string $redirect_url Defaults to the site URL.
1667
		*/
1668
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1669
1670
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1671
			? $data['redirect_uri']
1672
			: add_query_arg(
1673
				array(
1674
					'action'   => 'authorize',
1675
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1676
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1677
				),
1678
				esc_url( $processing_url )
1679
			);
1680
1681
		/**
1682
		 * Filters the token request data.
1683
		 *
1684
		 * @since 8.0.0
1685
		 *
1686
		 * @param array $request_data request data.
1687
		 */
1688
		$body = apply_filters(
1689
			'jetpack_token_request_body',
1690
			array(
1691
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1692
				'client_secret' => $client_secret->secret,
1693
				'grant_type'    => 'authorization_code',
1694
				'code'          => $data['code'],
1695
				'redirect_uri'  => $redirect_uri,
1696
			)
1697
		);
1698
1699
		$args = array(
1700
			'method'  => 'POST',
1701
			'body'    => $body,
1702
			'headers' => array(
1703
				'Accept' => 'application/json',
1704
			),
1705
		);
1706
1707
		add_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1708
		$response = Client::_wp_remote_request( Utils::fix_url_for_bad_hosts( $this->api_url( 'token' ) ), $args );
1709
		remove_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1710
1711
		if ( is_wp_error( $response ) ) {
1712
			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...
1713
		}
1714
1715
		$code   = wp_remote_retrieve_response_code( $response );
1716
		$entity = wp_remote_retrieve_body( $response );
1717
1718
		if ( $entity ) {
1719
			$json = json_decode( $entity );
1720
		} else {
1721
			$json = false;
1722
		}
1723
1724
		if ( 200 !== $code || ! empty( $json->error ) ) {
1725
			if ( empty( $json->error ) ) {
1726
				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...
1727
			}
1728
1729
			/* translators: Error description string. */
1730
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1731
1732
			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...
1733
		}
1734
1735
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1736
			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...
1737
		}
1738
1739
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1740
			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...
1741
		}
1742
1743
		if ( empty( $json->scope ) ) {
1744
			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...
1745
		}
1746
1747
		// TODO: get rid of the error silencer.
1748
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1749
		@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...
1750
		if ( empty( $role ) || empty( $hmac ) ) {
1751
			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...
1752
		}
1753
1754
		if ( $this->sign_role( $role ) !== $json->scope ) {
1755
			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...
1756
		}
1757
1758
		$cap = $roles->translate_role_to_cap( $role );
1759
		if ( ! $cap ) {
1760
			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...
1761
		}
1762
1763
		if ( ! current_user_can( $cap ) ) {
1764
			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...
1765
		}
1766
1767
		/**
1768
		 * Fires after user has successfully received an auth token.
1769
		 *
1770
		 * @since 3.9.0
1771
		 */
1772
		do_action( 'jetpack_user_authorized' );
1773
1774
		return (string) $json->access_token;
1775
	}
1776
1777
	/**
1778
	 * Increases the request timeout value to 30 seconds.
1779
	 *
1780
	 * @return int Returns 30.
1781
	 */
1782
	public function increase_timeout() {
1783
		return 30;
1784
	}
1785
1786
	/**
1787
	 * Builds a URL to the Jetpack connection auth page.
1788
	 *
1789
	 * @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...
1790
	 * @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...
1791
	 * @return string Connect URL.
1792
	 */
1793
	public function get_authorization_url( $user = null, $redirect = null ) {
1794
1795
		if ( empty( $user ) ) {
1796
			$user = wp_get_current_user();
1797
		}
1798
1799
		$roles       = new Roles();
1800
		$role        = $roles->translate_user_to_role( $user );
1801
		$signed_role = $this->sign_role( $role );
1802
1803
		/**
1804
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1805
		 * data processing.
1806
		 *
1807
		 * @since 8.0.0
1808
		 *
1809
		 * @param string $redirect_url Defaults to the site admin URL.
1810
		 */
1811
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1812
1813
		/**
1814
		 * Filter the URL to redirect the user back to when the authorization process
1815
		 * is complete.
1816
		 *
1817
		 * @since 8.0.0
1818
		 *
1819
		 * @param string $redirect_url Defaults to the site URL.
1820
		 */
1821
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1822
1823
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1824
1825
		/**
1826
		 * Filter the type of authorization.
1827
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1828
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1829
		 *
1830
		 * @since 4.3.3
1831
		 *
1832
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1833
		 */
1834
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1835
1836
		/**
1837
		 * Filters the user connection request data for additional property addition.
1838
		 *
1839
		 * @since 8.0.0
1840
		 *
1841
		 * @param array $request_data request data.
1842
		 */
1843
		$body = apply_filters(
1844
			'jetpack_connect_request_body',
1845
			array(
1846
				'response_type' => 'code',
1847
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1848
				'redirect_uri'  => add_query_arg(
1849
					array(
1850
						'action'   => 'authorize',
1851
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1852
						'redirect' => rawurlencode( $redirect ),
1853
					),
1854
					esc_url( $processing_url )
1855
				),
1856
				'state'         => $user->ID,
1857
				'scope'         => $signed_role,
1858
				'user_email'    => $user->user_email,
1859
				'user_login'    => $user->user_login,
1860
				'is_active'     => $this->is_active(),
1861
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1862
				'auth_type'     => $auth_type,
1863
				'secret'        => $secrets['secret_1'],
1864
				'blogname'      => get_option( 'blogname' ),
1865
				'site_url'      => site_url(),
1866
				'home_url'      => home_url(),
1867
				'site_icon'     => get_site_icon_url(),
1868
				'site_lang'     => get_locale(),
1869
				'site_created'  => $this->get_assumed_site_creation_date(),
1870
			)
1871
		);
1872
1873
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1874
1875
		$api_url = $this->api_url( 'authorize' );
1876
1877
		return add_query_arg( $body, $api_url );
1878
	}
1879
1880
	/**
1881
	 * Authorizes the user by obtaining and storing the user token.
1882
	 *
1883
	 * @param array $data The request data.
1884
	 * @return string|\WP_Error Returns a string on success.
1885
	 *                          Returns a \WP_Error on failure.
1886
	 */
1887
	public function authorize( $data = array() ) {
1888
		/**
1889
		 * Action fired when user authorization starts.
1890
		 *
1891
		 * @since 8.0.0
1892
		 */
1893
		do_action( 'jetpack_authorize_starting' );
1894
1895
		$roles = new Roles();
1896
		$role  = $roles->translate_current_user_to_role();
1897
1898
		if ( ! $role ) {
1899
			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...
1900
		}
1901
1902
		$cap = $roles->translate_role_to_cap( $role );
1903
		if ( ! $cap ) {
1904
			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...
1905
		}
1906
1907
		if ( ! empty( $data['error'] ) ) {
1908
			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...
1909
		}
1910
1911
		if ( ! isset( $data['state'] ) ) {
1912
			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...
1913
		}
1914
1915
		if ( ! ctype_digit( $data['state'] ) ) {
1916
			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...
1917
		}
1918
1919
		$current_user_id = get_current_user_id();
1920
		if ( $current_user_id !== (int) $data['state'] ) {
1921
			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...
1922
		}
1923
1924
		if ( empty( $data['code'] ) ) {
1925
			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...
1926
		}
1927
1928
		$token = $this->get_token( $data );
1929
1930 View Code Duplication
		if ( is_wp_error( $token ) ) {
1931
			$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...
1932
			if ( empty( $code ) ) {
1933
				$code = 'invalid_token';
1934
			}
1935
			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...
1936
		}
1937
1938
		if ( ! $token ) {
1939
			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...
1940
		}
1941
1942
		$is_master_user = ! $this->is_active();
1943
1944
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
1945
1946
		if ( ! $is_master_user ) {
1947
			/**
1948
			 * Action fired when a secondary user has been authorized.
1949
			 *
1950
			 * @since 8.0.0
1951
			 */
1952
			do_action( 'jetpack_authorize_ending_linked' );
1953
			return 'linked';
1954
		}
1955
1956
		/**
1957
		 * Action fired when the master user has been authorized.
1958
		 *
1959
		 * @since 8.0.0
1960
		 *
1961
		 * @param array $data The request data.
1962
		 */
1963
		do_action( 'jetpack_authorize_ending_authorized', $data );
1964
1965
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
1966
1967
		// Start nonce cleaner.
1968
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
1969
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
1970
1971
		return 'authorized';
1972
	}
1973
1974
	/**
1975
	 * Disconnects from the Jetpack servers.
1976
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1977
	 */
1978
	public function disconnect_site() {
1979
1980
	}
1981
1982
	/**
1983
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1984
	 *
1985
	 * @param string $text The string to hash.
1986
	 * @return string
1987
	 */
1988
	public function sha1_base64( $text ) {
1989
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1990
	}
1991
1992
	/**
1993
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1994
	 *
1995
	 * @param string $domain The domain to check.
1996
	 *
1997
	 * @return bool|WP_Error
1998
	 */
1999
	public function is_usable_domain( $domain ) {
2000
2001
		// If it's empty, just fail out.
2002
		if ( ! $domain ) {
2003
			return new \WP_Error(
2004
				'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...
2005
				/* translators: %1$s is a domain name. */
2006
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
2007
			);
2008
		}
2009
2010
		/**
2011
		 * Skips the usuable domain check when connecting a site.
2012
		 *
2013
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
2014
		 *
2015
		 * @since 4.1.0
2016
		 *
2017
		 * @param bool If the check should be skipped. Default false.
2018
		 */
2019
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
2020
			return true;
2021
		}
2022
2023
		// None of the explicit localhosts.
2024
		$forbidden_domains = array(
2025
			'wordpress.com',
2026
			'localhost',
2027
			'localhost.localdomain',
2028
			'127.0.0.1',
2029
			'local.wordpress.test',         // VVV pattern.
2030
			'local.wordpress-trunk.test',   // VVV pattern.
2031
			'src.wordpress-develop.test',   // VVV pattern.
2032
			'build.wordpress-develop.test', // VVV pattern.
2033
		);
2034 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
2035
			return new \WP_Error(
2036
				'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...
2037
				sprintf(
2038
					/* translators: %1$s is a domain name. */
2039
					__(
2040
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
2041
						'jetpack'
2042
					),
2043
					$domain
2044
				)
2045
			);
2046
		}
2047
2048
		// No .test or .local domains.
2049 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
2050
			return new \WP_Error(
2051
				'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...
2052
				sprintf(
2053
					/* translators: %1$s is a domain name. */
2054
					__(
2055
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
2056
						'jetpack'
2057
					),
2058
					$domain
2059
				)
2060
			);
2061
		}
2062
2063
		// No WPCOM subdomains.
2064 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
2065
			return new \WP_Error(
2066
				'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...
2067
				sprintf(
2068
					/* translators: %1$s is a domain name. */
2069
					__(
2070
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
2071
						'jetpack'
2072
					),
2073
					$domain
2074
				)
2075
			);
2076
		}
2077
2078
		// If PHP was compiled without support for the Filter module (very edge case).
2079
		if ( ! function_exists( 'filter_var' ) ) {
2080
			// Just pass back true for now, and let wpcom sort it out.
2081
			return true;
2082
		}
2083
2084
		return true;
2085
	}
2086
2087
	/**
2088
	 * Gets the requested token.
2089
	 *
2090
	 * Tokens are one of two types:
2091
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
2092
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
2093
	 *    are not associated with a user account. They represent the site's connection with
2094
	 *    the Jetpack servers.
2095
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
2096
	 *
2097
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
2098
	 * token, and $private is a secret that should never be displayed anywhere or sent
2099
	 * over the network; it's used only for signing things.
2100
	 *
2101
	 * Blog Tokens can be "Normal" or "Special".
2102
	 * * Normal: The result of a normal connection flow. They look like
2103
	 *   "{$random_string_1}.{$random_string_2}"
2104
	 *   That is, $token_key and $private are both random strings.
2105
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
2106
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
2107
	 *   constant (rare).
2108
	 * * Special: A connection token for sites that have gone through an alternative
2109
	 *   connection flow. They look like:
2110
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
2111
	 *   That is, $private is a random string and $token_key has a special structure with
2112
	 *   lots of semicolons.
2113
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
2114
	 *   JETPACK_BLOG_TOKEN constant.
2115
	 *
2116
	 * In particular, note that Normal Blog Tokens never start with ";" and that
2117
	 * Special Blog Tokens always do.
2118
	 *
2119
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
2120
	 * order:
2121
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
2122
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
2123
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
2124
	 *
2125
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
2126
	 * @param string|false $token_key If provided, check that the token matches the provided input.
2127
	 * @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.
2128
	 *
2129
	 * @return object|false
2130
	 */
2131
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
2132
		$possible_special_tokens = array();
2133
		$possible_normal_tokens  = array();
2134
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
2135
2136
		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...
2137
			if ( ! $user_tokens ) {
2138
				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...
2139
			}
2140
			if ( self::JETPACK_MASTER_USER === $user_id ) {
2141
				$user_id = \Jetpack_Options::get_option( 'master_user' );
2142
				if ( ! $user_id ) {
2143
					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...
2144
				}
2145
			}
2146
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
2147
				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...
2148
			}
2149
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
2150 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
2151
				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...
2152
			}
2153 View Code Duplication
			if ( $user_token_chunks[2] !== (string) $user_id ) {
2154
				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...
2155
			}
2156
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
2157
		} else {
2158
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
2159
			if ( $stored_blog_token ) {
2160
				$possible_normal_tokens[] = $stored_blog_token;
2161
			}
2162
2163
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
2164
2165
			if ( $defined_tokens_string ) {
2166
				$defined_tokens = explode( ',', $defined_tokens_string );
2167
				foreach ( $defined_tokens as $defined_token ) {
2168
					if ( ';' === $defined_token[0] ) {
2169
						$possible_special_tokens[] = $defined_token;
2170
					} else {
2171
						$possible_normal_tokens[] = $defined_token;
2172
					}
2173
				}
2174
			}
2175
		}
2176
2177
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2178
			$possible_tokens = $possible_normal_tokens;
2179
		} else {
2180
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
2181
		}
2182
2183
		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...
2184
			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...
2185
		}
2186
2187
		$valid_token = false;
2188
2189
		if ( false === $token_key ) {
2190
			// Use first token.
2191
			$valid_token = $possible_tokens[0];
2192
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2193
			// Use first normal token.
2194
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
2195
		} else {
2196
			// Use the token matching $token_key or false if none.
2197
			// Ensure we check the full key.
2198
			$token_check = rtrim( $token_key, '.' ) . '.';
2199
2200
			foreach ( $possible_tokens as $possible_token ) {
2201
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
2202
					$valid_token = $possible_token;
2203
					break;
2204
				}
2205
			}
2206
		}
2207
2208
		if ( ! $valid_token ) {
2209
			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...
2210
		}
2211
2212
		return (object) array(
2213
			'secret'           => $valid_token,
2214
			'external_user_id' => (int) $user_id,
2215
		);
2216
	}
2217
2218
	/**
2219
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2220
	 * since it is passed by reference to various methods.
2221
	 * Capture it here so we can verify the signature later.
2222
	 *
2223
	 * @param array $methods an array of available XMLRPC methods.
2224
	 * @return array the same array, since this method doesn't add or remove anything.
2225
	 */
2226
	public function xmlrpc_methods( $methods ) {
2227
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
2228
		return $methods;
2229
	}
2230
2231
	/**
2232
	 * Resets the raw post data parameter for testing purposes.
2233
	 */
2234
	public function reset_raw_post_data() {
2235
		$this->raw_post_data = null;
2236
	}
2237
2238
	/**
2239
	 * Registering an additional method.
2240
	 *
2241
	 * @param array $methods an array of available XMLRPC methods.
2242
	 * @return array the amended array in case the method is added.
2243
	 */
2244
	public function public_xmlrpc_methods( $methods ) {
2245
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2246
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2247
		}
2248
		return $methods;
2249
	}
2250
2251
	/**
2252
	 * Handles a getOptions XMLRPC method call.
2253
	 *
2254
	 * @param array $args method call arguments.
2255
	 * @return an amended XMLRPC server options array.
2256
	 */
2257
	public function jetpack_get_options( $args ) {
2258
		global $wp_xmlrpc_server;
2259
2260
		$wp_xmlrpc_server->escape( $args );
2261
2262
		$username = $args[1];
2263
		$password = $args[2];
2264
2265
		$user = $wp_xmlrpc_server->login( $username, $password );
2266
		if ( ! $user ) {
2267
			return $wp_xmlrpc_server->error;
2268
		}
2269
2270
		$options   = array();
2271
		$user_data = $this->get_connected_user_data();
2272
		if ( is_array( $user_data ) ) {
2273
			$options['jetpack_user_id']         = array(
2274
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2275
				'readonly' => true,
2276
				'value'    => $user_data['ID'],
2277
			);
2278
			$options['jetpack_user_login']      = array(
2279
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2280
				'readonly' => true,
2281
				'value'    => $user_data['login'],
2282
			);
2283
			$options['jetpack_user_email']      = array(
2284
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2285
				'readonly' => true,
2286
				'value'    => $user_data['email'],
2287
			);
2288
			$options['jetpack_user_site_count'] = array(
2289
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2290
				'readonly' => true,
2291
				'value'    => $user_data['site_count'],
2292
			);
2293
		}
2294
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2295
		$args                           = stripslashes_deep( $args );
2296
		return $wp_xmlrpc_server->wp_getOptions( $args );
2297
	}
2298
2299
	/**
2300
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2301
	 *
2302
	 * @param array $options standard Core options.
2303
	 * @return array amended options.
2304
	 */
2305
	public function xmlrpc_options( $options ) {
2306
		$jetpack_client_id = false;
2307
		if ( $this->is_active() ) {
2308
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2309
		}
2310
		$options['jetpack_version'] = array(
2311
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2312
			'readonly' => true,
2313
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2314
		);
2315
2316
		$options['jetpack_client_id'] = array(
2317
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2318
			'readonly' => true,
2319
			'value'    => $jetpack_client_id,
2320
		);
2321
		return $options;
2322
	}
2323
2324
	/**
2325
	 * Resets the saved authentication state in between testing requests.
2326
	 */
2327
	public function reset_saved_auth_state() {
2328
		$this->xmlrpc_verification = null;
2329
	}
2330
2331
	/**
2332
	 * Sign a user role with the master access token.
2333
	 * If not specified, will default to the current user.
2334
	 *
2335
	 * @access public
2336
	 *
2337
	 * @param string $role    User role.
2338
	 * @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...
2339
	 * @return string Signed user role.
2340
	 */
2341
	public function sign_role( $role, $user_id = null ) {
2342
		if ( empty( $user_id ) ) {
2343
			$user_id = (int) get_current_user_id();
2344
		}
2345
2346
		if ( ! $user_id ) {
2347
			return false;
2348
		}
2349
2350
		$token = $this->get_access_token();
2351
		if ( ! $token || is_wp_error( $token ) ) {
2352
			return false;
2353
		}
2354
2355
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2356
	}
2357
2358
	/**
2359
	 * Set the plugin instance.
2360
	 *
2361
	 * @param Plugin $plugin_instance The plugin instance.
2362
	 *
2363
	 * @return $this
2364
	 */
2365
	public function set_plugin_instance( Plugin $plugin_instance ) {
2366
		$this->plugin = $plugin_instance;
2367
2368
		return $this;
2369
	}
2370
2371
	/**
2372
	 * Retrieve the plugin management object.
2373
	 *
2374
	 * @return Plugin
2375
	 */
2376
	public function get_plugin() {
2377
		return $this->plugin;
2378
	}
2379
2380
	/**
2381
	 * Get all connected plugins information, excluding those disconnected by user.
2382
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2383
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2384
	 * so please make sure not to run the method too early in the code.
2385
	 *
2386
	 * @return array|WP_Error
2387
	 */
2388
	public function get_connected_plugins() {
2389
		$maybe_plugins = Plugin_Storage::get_all( true );
2390
2391
		if ( $maybe_plugins instanceof WP_Error ) {
2392
			return $maybe_plugins;
2393
		}
2394
2395
		return $maybe_plugins;
2396
	}
2397
2398
	/**
2399
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2400
	 * Note: this method does not remove any access tokens.
2401
	 *
2402
	 * @return bool
2403
	 */
2404
	public function disable_plugin() {
2405
		if ( ! $this->plugin ) {
2406
			return false;
2407
		}
2408
2409
		return $this->plugin->disable();
2410
	}
2411
2412
	/**
2413
	 * Force plugin reconnect after user-initiated disconnect.
2414
	 * After its called, the plugin will be allowed to use the connection again.
2415
	 * Note: this method does not initialize access tokens.
2416
	 *
2417
	 * @return bool
2418
	 */
2419
	public function enable_plugin() {
2420
		if ( ! $this->plugin ) {
2421
			return false;
2422
		}
2423
2424
		return $this->plugin->enable();
2425
	}
2426
2427
	/**
2428
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2429
	 * If no plugin slug was passed into the constructor, always returns true.
2430
	 *
2431
	 * @return bool
2432
	 */
2433
	public function is_plugin_enabled() {
2434
		if ( ! $this->plugin ) {
2435
			return true;
2436
		}
2437
2438
		return $this->plugin->is_enabled();
2439
	}
2440
2441
}
2442