Completed
Push — update/userless-non-admin-conn... ( 4916c7...94e8b8 )
by
unknown
09:52
created

Manager::current_user_can_connect_account()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 0
dl 0
loc 10
rs 9.9332
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\Heartbeat;
12
use Automattic\Jetpack\Roles;
13
use Automattic\Jetpack\Status;
14
use Automattic\Jetpack\Tracking;
15
use Jetpack_Options;
16
use WP_Error;
17
use WP_User;
18
19
/**
20
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
21
 * and Jetpack.
22
 */
23
class Manager {
24
25
	const SECRETS_MISSING        = 'secrets_missing';
26
	const SECRETS_EXPIRED        = 'secrets_expired';
27
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
28
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
29
30
	/**
31
	 * Constant used to fetch the master user token. Deprecated.
32
	 *
33
	 * @deprecated 9.0.0
34
	 * @see Manager::CONNECTION_OWNER
35
	 * @var boolean
36
	 */
37
	const JETPACK_MASTER_USER = true; //phpcs:ignore Jetpack.Constants.MasterUserConstant.ShouldNotBeUsed
38
39
	/**
40
	 * For internal use only. If you need to get the connection owner, use the provided methods
41
	 * get_connection_owner_id, get_connection_owner and is_connection_owner
42
	 *
43
	 * @todo Add private visibility once PHP 7.1 is the minimum supported verion.
44
	 *
45
	 * @var boolean
46
	 */
47
	const CONNECTION_OWNER = true;
48
49
	/**
50
	 * The procedure that should be run to generate secrets.
51
	 *
52
	 * @var Callable
53
	 */
54
	protected $secret_callable;
55
56
	/**
57
	 * A copy of the raw POST data for signature verification purposes.
58
	 *
59
	 * @var String
60
	 */
61
	protected $raw_post_data;
62
63
	/**
64
	 * Verification data needs to be stored to properly verify everything.
65
	 *
66
	 * @var Object
67
	 */
68
	private $xmlrpc_verification = null;
69
70
	/**
71
	 * Plugin management object.
72
	 *
73
	 * @var Plugin
74
	 */
75
	private $plugin = null;
76
77
	/**
78
	 * Initialize the object.
79
	 * Make sure to call the "Configure" first.
80
	 *
81
	 * @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...
82
	 *
83
	 * @see \Automattic\Jetpack\Config
84
	 */
85
	public function __construct( $plugin_slug = null ) {
86
		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...
87
			$this->set_plugin_instance( new Plugin( $plugin_slug ) );
88
		}
89
	}
90
91
	/**
92
	 * Initializes required listeners. This is done separately from the constructors
93
	 * because some objects sometimes need to instantiate separate objects of this class.
94
	 *
95
	 * @todo Implement a proper nonce verification.
96
	 */
97
	public static function configure() {
98
		$manager = new self();
99
100
		add_filter(
101
			'jetpack_constant_default_value',
102
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
103
			10,
104
			2
105
		);
106
107
		$manager->setup_xmlrpc_handlers(
108
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
109
			$manager->is_active(),
110
			$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...
111
		);
112
113
		$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...
114
115
		if ( $manager->is_active() ) {
116
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
117
		}
118
119
		add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
120
121
		add_action( 'jetpack_clean_nonces', array( $manager, 'clean_nonces' ) );
122
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
123
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
124
		}
125
126
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
127
128
		add_filter( 'map_meta_cap', array( $manager, 'jetpack_connection_custom_caps' ), 1, 4 );
129
130
		Heartbeat::init();
131
		add_filter( 'jetpack_heartbeat_stats_array', array( $manager, 'add_stats_to_heartbeat' ) );
132
133
		Webhooks::init( $manager );
134
	}
135
136
	/**
137
	 * Sets up the XMLRPC request handlers.
138
	 *
139
	 * @param array                  $request_params incoming request parameters.
140
	 * @param Boolean                $is_active whether the connection is currently active.
141
	 * @param Boolean                $is_signed whether the signature check has been successful.
142
	 * @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...
143
	 */
144
	public function setup_xmlrpc_handlers(
145
		$request_params,
146
		$is_active,
147
		$is_signed,
148
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
149
	) {
150
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
151
152
		if (
153
			! isset( $request_params['for'] )
154
			|| 'jetpack' !== $request_params['for']
155
		) {
156
			return false;
157
		}
158
159
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
160
		if (
161
			isset( $request_params['jetpack'] )
162
			&& 'comms' === $request_params['jetpack']
163
		) {
164
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
165
				// Use the real constant here for WordPress' sake.
166
				define( 'XMLRPC_REQUEST', true );
167
			}
168
169
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
170
171
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
172
		}
173
174
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
175
			return false;
176
		}
177
		// Display errors can cause the XML to be not well formed.
178
		@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...
179
180
		if ( $xmlrpc_server ) {
181
			$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...
182
		} else {
183
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
184
		}
185
186
		$this->require_jetpack_authentication();
187
188
		if ( $is_active ) {
189
			// Hack to preserve $HTTP_RAW_POST_DATA.
190
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
191
192
			if ( $is_signed ) {
193
				// The actual API methods.
194
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
195
			} else {
196
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
197
				// active Jetpack connection, so that additional users can link their account.
198
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
199
			}
200
		} else {
201
			// The bootstrap API methods.
202
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
203
204
			if ( $is_signed ) {
205
				// The jetpack Provision method is available for blog-token-signed requests.
206
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
207
			} else {
208
				new XMLRPC_Connector( $this );
209
			}
210
		}
211
212
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
213
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
214
		return true;
215
	}
216
217
	/**
218
	 * Initializes the REST API connector on the init hook.
219
	 */
220
	public function initialize_rest_api_registration_connector() {
221
		new REST_Connector( $this );
222
	}
223
224
	/**
225
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
226
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
227
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
228
	 * which is accessible via a different URI. Most of the below is copied directly
229
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
230
	 *
231
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
232
	 */
233
	public function alternate_xmlrpc() {
234
		// Some browser-embedded clients send cookies. We don't want them.
235
		$_COOKIE = array();
236
237
		include_once ABSPATH . 'wp-admin/includes/admin.php';
238
		include_once ABSPATH . WPINC . '/class-IXR.php';
239
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
240
241
		/**
242
		 * Filters the class used for handling XML-RPC requests.
243
		 *
244
		 * @since 3.1.0
245
		 *
246
		 * @param string $class The name of the XML-RPC server class.
247
		 */
248
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
249
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
250
251
		// Fire off the request.
252
		nocache_headers();
253
		$wp_xmlrpc_server->serve_request();
254
255
		exit;
256
	}
257
258
	/**
259
	 * Removes all XML-RPC methods that are not `jetpack.*`.
260
	 * Only used in our alternate XML-RPC endpoint, where we want to
261
	 * ensure that Core and other plugins' methods are not exposed.
262
	 *
263
	 * @param array $methods a list of registered WordPress XMLRPC methods.
264
	 * @return array filtered $methods
265
	 */
266
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
267
		$jetpack_methods = array();
268
269
		foreach ( $methods as $method => $callback ) {
270
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
271
				$jetpack_methods[ $method ] = $callback;
272
			}
273
		}
274
275
		return $jetpack_methods;
276
	}
277
278
	/**
279
	 * Removes all other authentication methods not to allow other
280
	 * methods to validate unauthenticated requests.
281
	 */
282
	public function require_jetpack_authentication() {
283
		// Don't let anyone authenticate.
284
		$_COOKIE = array();
285
		remove_all_filters( 'authenticate' );
286
		remove_all_actions( 'wp_login_failed' );
287
288
		if ( $this->is_active() ) {
289
			// Allow Jetpack authentication.
290
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
291
		}
292
	}
293
294
	/**
295
	 * Authenticates XML-RPC and other requests from the Jetpack Server
296
	 *
297
	 * @param WP_User|Mixed $user user object if authenticated.
298
	 * @param String        $username username.
299
	 * @param String        $password password string.
300
	 * @return WP_User|Mixed authenticated user or error.
301
	 */
302
	public function authenticate_jetpack( $user, $username, $password ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
303
		if ( is_a( $user, '\\WP_User' ) ) {
304
			return $user;
305
		}
306
307
		$token_details = $this->verify_xml_rpc_signature();
308
309
		if ( ! $token_details ) {
310
			return $user;
311
		}
312
313
		if ( 'user' !== $token_details['type'] ) {
314
			return $user;
315
		}
316
317
		if ( ! $token_details['user_id'] ) {
318
			return $user;
319
		}
320
321
		nocache_headers();
322
323
		return new \WP_User( $token_details['user_id'] );
324
	}
325
326
	/**
327
	 * Verifies the signature of the current request.
328
	 *
329
	 * @return false|array
330
	 */
331
	public function verify_xml_rpc_signature() {
332
		if ( is_null( $this->xmlrpc_verification ) ) {
333
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
334
335
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
336
				/**
337
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
338
				 *
339
				 * @since 7.5.0
340
				 *
341
				 * @param WP_Error $signature_verification_error The verification error
342
				 */
343
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
344
345
				Error_Handler::get_instance()->report_error( $this->xmlrpc_verification );
346
347
			}
348
		}
349
350
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
351
	}
352
353
	/**
354
	 * Verifies the signature of the current request.
355
	 *
356
	 * This function has side effects and should not be used. Instead,
357
	 * use the memoized version `->verify_xml_rpc_signature()`.
358
	 *
359
	 * @internal
360
	 * @todo Refactor to use proper nonce verification.
361
	 */
362
	private function internal_verify_xml_rpc_signature() {
363
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
364
		// It's not for us.
365
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
366
			return false;
367
		}
368
369
		$signature_details = array(
370
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
371
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
372
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
373
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
374
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
375
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
376
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
377
		);
378
379
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
380
		@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...
381
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
382
383
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
384
385
		if (
386
			empty( $token_key )
387
		||
388
			empty( $version ) || (string) $jetpack_api_version !== $version ) {
389
			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...
390
		}
391
392
		if ( '0' === $user_id ) {
393
			$token_type = 'blog';
394
			$user_id    = 0;
395
		} else {
396
			$token_type = 'user';
397
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
398
				return new \WP_Error(
399
					'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...
400
					'Malformed user_id in request',
401
					compact( 'signature_details' )
402
				);
403
			}
404
			$user_id = (int) $user_id;
405
406
			$user = new \WP_User( $user_id );
407
			if ( ! $user || ! $user->exists() ) {
408
				return new \WP_Error(
409
					'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...
410
					sprintf( 'User %d does not exist', $user_id ),
411
					compact( 'signature_details' )
412
				);
413
			}
414
		}
415
416
		$token = $this->get_access_token( $user_id, $token_key, false );
417
		if ( is_wp_error( $token ) ) {
418
			$token->add_data( compact( 'signature_details' ) );
419
			return $token;
420
		} elseif ( ! $token ) {
421
			return new \WP_Error(
422
				'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...
423
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
424
				compact( 'signature_details' )
425
			);
426
		}
427
428
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
429
		// phpcs:disable WordPress.Security.NonceVerification.Missing
430
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
431
			$post_data   = $_POST;
432
			$file_hashes = array();
433
			foreach ( $post_data as $post_data_key => $post_data_value ) {
434
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
435
					continue;
436
				}
437
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
438
				$file_hashes[ $post_data_key ] = $post_data_value;
439
			}
440
441
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
442
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
443
				$post_data[ $post_data_key ] = $post_data_value;
444
			}
445
446
			ksort( $post_data );
447
448
			$body = http_build_query( stripslashes_deep( $post_data ) );
449
		} elseif ( is_null( $this->raw_post_data ) ) {
450
			$body = file_get_contents( 'php://input' );
451
		} else {
452
			$body = null;
453
		}
454
		// phpcs:enable
455
456
		$signature = $jetpack_signature->sign_current_request(
457
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
458
		);
459
460
		$signature_details['url'] = $jetpack_signature->current_request_url;
461
462
		if ( ! $signature ) {
463
			return new \WP_Error(
464
				'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...
465
				'Unknown signature error',
466
				compact( 'signature_details' )
467
			);
468
		} elseif ( is_wp_error( $signature ) ) {
469
			return $signature;
470
		}
471
472
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
473
		$timestamp = (int) $_GET['timestamp'];
474
		$nonce     = stripslashes( (string) $_GET['nonce'] );
475
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
476
477
		// Use up the nonce regardless of whether the signature matches.
478
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
479
			return new \WP_Error(
480
				'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...
481
				'Could not add nonce',
482
				compact( 'signature_details' )
483
			);
484
		}
485
486
		// Be careful about what you do with this debugging data.
487
		// If a malicious requester has access to the expected signature,
488
		// bad things might be possible.
489
		$signature_details['expected'] = $signature;
490
491
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
492
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
493
			return new \WP_Error(
494
				'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...
495
				'Signature mismatch',
496
				compact( 'signature_details' )
497
			);
498
		}
499
500
		/**
501
		 * Action for additional token checking.
502
		 *
503
		 * @since 7.7.0
504
		 *
505
		 * @param array $post_data request data.
506
		 * @param array $token_data token data.
507
		 */
508
		return apply_filters(
509
			'jetpack_signature_check_token',
510
			array(
511
				'type'      => $token_type,
512
				'token_key' => $token_key,
513
				'user_id'   => $token->external_user_id,
514
			),
515
			$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...
516
			$this->raw_post_data
517
		);
518
	}
519
520
	/**
521
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI.
522
	 *
523
	 * @return Boolean is the site connected?
524
	 */
525
	public function is_active() {
526
		if ( ( new Status() )->is_no_user_testing_mode() ) {
527
			return $this->is_connected();
528
		}
529
		return (bool) $this->get_access_token( self::CONNECTION_OWNER );
0 ignored issues
show
Documentation introduced by
self::CONNECTION_OWNER 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...
530
	}
531
532
	/**
533
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
534
	 *
535
	 * @access public
536
	 * @deprecated 9.2.0 Use is_connected instead
537
	 * @see Manager::is_connected
538
	 *
539
	 * @return bool
540
	 */
541
	public function is_registered() {
542
		_deprecated_function( __METHOD__, 'jetpack-9.2' );
543
		return $this->is_connected();
544
	}
545
546
	/**
547
	 * Returns true if the site has both a token and a blog id, which indicates a site has been connected.
548
	 *
549
	 * @access public
550
	 * @since 9.2.0
551
	 *
552
	 * @return bool
553
	 */
554
	public function is_connected() {
555
		$has_blog_id    = (bool) \Jetpack_Options::get_option( 'id' );
556
		$has_blog_token = (bool) $this->get_access_token( false );
557
		return $has_blog_id && $has_blog_token;
558
	}
559
560
	/**
561
	 * Returns true if the site has at least one connected administrator.
562
	 *
563
	 * @access public
564
	 * @since 9.2.0
565
	 *
566
	 * @return bool
567
	 */
568
	public function has_connected_admin() {
569
		return (bool) count( $this->get_connected_users( 'manage_options' ) );
570
	}
571
572
	/**
573
	 * Returns true if the site has any connected user.
574
	 *
575
	 * @access public
576
	 * @since 9.2.0
577
	 *
578
	 * @return bool
579
	 */
580
	public function has_connected_user() {
581
		return (bool) count( $this->get_connected_users() );
582
	}
583
584
	/**
585
	 * Returns true if the site has a connected Blog owner (master_user).
586
	 *
587
	 * @access public
588
	 * @since 9.2.0
589
	 *
590
	 * @return bool
591
	 */
592
	public function has_connected_owner() {
593
		return (bool) $this->get_connection_owner_id();
594
	}
595
596
	/**
597
	 * Checks to see if the connection owner of the site is missing.
598
	 *
599
	 * @return bool
600
	 */
601
	public function is_missing_connection_owner() {
602
		$connection_owner = $this->get_connection_owner_id();
603
		if ( ! get_user_by( 'id', $connection_owner ) ) {
604
			return true;
605
		}
606
607
		return false;
608
	}
609
610
	/**
611
	 * Returns true if the user with the specified identifier is connected to
612
	 * WordPress.com.
613
	 *
614
	 * @param int $user_id the user identifier. Default is the current user.
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...
615
	 * @return bool Boolean is the user connected?
616
	 */
617
	public function is_user_connected( $user_id = false ) {
618
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
619
		if ( ! $user_id ) {
620
			return false;
621
		}
622
623
		return (bool) $this->get_access_token( $user_id );
624
	}
625
626
	/**
627
	 * Returns the local user ID of the connection owner.
628
	 *
629
	 * @return bool|int Returns the ID of the connection owner or False if no connection owner found.
630
	 */
631
	public function get_connection_owner_id() {
632
		$owner = $this->get_connection_owner();
633
		return $owner instanceof \WP_User ? $owner->ID : false;
0 ignored issues
show
Bug introduced by
The class WP_User does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
634
	}
635
636
	/**
637
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
638
	 * Able to select by specific capability.
639
	 *
640
	 * @param string $capability The capability of the user.
641
	 * @return array Array of WP_User objects if found.
642
	 */
643
	public function get_connected_users( $capability = 'any' ) {
644
		$connected_users = array();
645
		$user_tokens     = \Jetpack_Options::get_option( 'user_tokens' );
646
647
		if ( ! is_array( $user_tokens ) || empty( $user_tokens ) ) {
648
			return $connected_users;
649
		}
650
		$connected_user_ids = array_keys( $user_tokens );
651
652
		if ( ! empty( $connected_user_ids ) ) {
653
			foreach ( $connected_user_ids as $id ) {
654
				// Check for capability.
655
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
656
					continue;
657
				}
658
659
				$user_data = get_userdata( $id );
660
				if ( $user_data instanceof \WP_User ) {
0 ignored issues
show
Bug introduced by
The class WP_User does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
661
					$connected_users[] = $user_data;
662
				}
663
			}
664
		}
665
666
		return $connected_users;
667
	}
668
669
	/**
670
	 * Get the wpcom user data of the current|specified connected user.
671
	 *
672
	 * @todo Refactor to properly load the XMLRPC client independently.
673
	 *
674
	 * @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...
675
	 * @return Object the user object.
676
	 */
677
	public function get_connected_user_data( $user_id = null ) {
678
		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...
679
			$user_id = get_current_user_id();
680
		}
681
682
		$transient_key    = "jetpack_connected_user_data_$user_id";
683
		$cached_user_data = get_transient( $transient_key );
684
685
		if ( $cached_user_data ) {
686
			return $cached_user_data;
687
		}
688
689
		$xml = new \Jetpack_IXR_Client(
690
			array(
691
				'user_id' => $user_id,
692
			)
693
		);
694
		$xml->query( 'wpcom.getUser' );
695
		if ( ! $xml->isError() ) {
696
			$user_data = $xml->getResponse();
697
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
698
			return $user_data;
699
		}
700
701
		return false;
702
	}
703
704
	/**
705
	 * Returns a user object of the connection owner.
706
	 *
707
	 * @return WP_User|false False if no connection owner found.
708
	 */
709
	public function get_connection_owner() {
710
711
		$user_id = \Jetpack_Options::get_option( 'master_user' );
712
713
		if ( ! $user_id ) {
714
			return false;
715
		}
716
717
		// Make sure user is connected.
718
		$user_token = $this->get_access_token( $user_id );
719
720
		$connection_owner = false;
721
722
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
723
			$connection_owner = get_userdata( $user_token->external_user_id );
724
		}
725
726
		return $connection_owner;
727
	}
728
729
	/**
730
	 * Returns true if the provided user is the Jetpack connection owner.
731
	 * If user ID is not specified, the current user will be used.
732
	 *
733
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
734
	 * @return Boolean True the user the connection owner, false otherwise.
735
	 */
736
	public function is_connection_owner( $user_id = false ) {
737
		if ( ! $user_id ) {
738
			$user_id = get_current_user_id();
739
		}
740
741
		return ( (int) $user_id ) === $this->get_connection_owner_id();
742
	}
743
744
	/**
745
	 * Connects the user with a specified ID to a WordPress.com user using the
746
	 * remote login flow.
747
	 *
748
	 * @access public
749
	 *
750
	 * @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...
751
	 * @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...
752
	 *                              admin_url().
753
	 * @return WP_Error only in case of a failed user lookup.
754
	 */
755
	public function connect_user( $user_id = null, $redirect_url = null ) {
756
		$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...
757
		if ( null === $user_id ) {
758
			$user = wp_get_current_user();
759
		} else {
760
			$user = get_user_by( 'ID', $user_id );
761
		}
762
763
		if ( empty( $user ) ) {
764
			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...
765
		}
766
767
		if ( null === $redirect_url ) {
768
			$redirect_url = admin_url();
769
		}
770
771
		// Using wp_redirect intentionally because we're redirecting outside.
772
		wp_redirect( $this->get_authorization_url( $user, $redirect_url ) ); // phpcs:ignore WordPress.Security.SafeRedirect
773
		exit();
774
	}
775
776
	/**
777
	 * Unlinks the current user from the linked WordPress.com user.
778
	 *
779
	 * @access public
780
	 * @static
781
	 *
782
	 * @todo Refactor to properly load the XMLRPC client independently.
783
	 *
784
	 * @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...
785
	 * @param bool    $can_overwrite_primary_user Allow for the primary user to be disconnected.
786
	 * @return Boolean Whether the disconnection of the user was successful.
787
	 */
788
	public static function disconnect_user( $user_id = null, $can_overwrite_primary_user = false ) {
789
		$tokens = Jetpack_Options::get_option( 'user_tokens' );
790
		if ( ! $tokens ) {
791
			return false;
792
		}
793
794
		$user_id = empty( $user_id ) ? get_current_user_id() : (int) $user_id;
795
796
		if ( Jetpack_Options::get_option( 'master_user' ) === $user_id && ! $can_overwrite_primary_user ) {
797
			return false;
798
		}
799
800
		if ( ! isset( $tokens[ $user_id ] ) ) {
801
			return false;
802
		}
803
804
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
805
		$xml->query( 'jetpack.unlink_user', $user_id );
806
807
		unset( $tokens[ $user_id ] );
808
809
		Jetpack_Options::update_option( 'user_tokens', $tokens );
810
811
		// Delete cached connected user data.
812
		$transient_key = "jetpack_connected_user_data_$user_id";
813
		delete_transient( $transient_key );
814
815
		/**
816
		 * Fires after the current user has been unlinked from WordPress.com.
817
		 *
818
		 * @since 4.1.0
819
		 *
820
		 * @param int $user_id The current user's ID.
821
		 */
822
		do_action( 'jetpack_unlinked_user', $user_id );
823
824
		return true;
825
	}
826
827
	/**
828
	 * Returns the requested Jetpack API URL.
829
	 *
830
	 * @param String $relative_url the relative API path.
831
	 * @return String API URL.
832
	 */
833
	public function api_url( $relative_url ) {
834
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
835
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
836
837
		/**
838
		 * Filters whether the connection manager should use the iframe authorization
839
		 * flow instead of the regular redirect-based flow.
840
		 *
841
		 * @since 8.3.0
842
		 *
843
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
844
		 */
845
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
846
847
		// Do not modify anything that is not related to authorize requests.
848
		if ( 'authorize' === $relative_url && $iframe_flow ) {
849
			$relative_url = 'authorize_iframe';
850
		}
851
852
		/**
853
		 * Filters the API URL that Jetpack uses for server communication.
854
		 *
855
		 * @since 8.0.0
856
		 *
857
		 * @param String $url the generated URL.
858
		 * @param String $relative_url the relative URL that was passed as an argument.
859
		 * @param String $api_base the API base string that is being used.
860
		 * @param String $api_version the API version string that is being used.
861
		 */
862
		return apply_filters(
863
			'jetpack_api_url',
864
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
865
			$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...
866
			$api_base,
867
			$api_version
868
		);
869
	}
870
871
	/**
872
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
873
	 *
874
	 * @return String XMLRPC API URL.
875
	 */
876
	public function xmlrpc_api_url() {
877
		$base = preg_replace(
878
			'#(https?://[^?/]+)(/?.*)?$#',
879
			'\\1',
880
			Constants::get_constant( 'JETPACK__API_BASE' )
881
		);
882
		return untrailingslashit( $base ) . '/xmlrpc.php';
883
	}
884
885
	/**
886
	 * Attempts Jetpack registration which sets up the site for connection. Should
887
	 * remain public because the call to action comes from the current site, not from
888
	 * WordPress.com.
889
	 *
890
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
891
	 * @return true|WP_Error The error object.
892
	 */
893
	public function register( $api_endpoint = 'register' ) {
894
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
895
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
896
897
		if ( false === $secrets ) {
898
			return new WP_Error( 'cannot_save_secrets', __( 'Jetpack experienced an issue trying to save options (cannot_save_secrets). We suggest that you contact your hosting provider, and ask them for help checking that the options table is writable on your site.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_save_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...
899
		}
900
901
		if (
902
			empty( $secrets['secret_1'] ) ||
903
			empty( $secrets['secret_2'] ) ||
904
			empty( $secrets['exp'] )
905
		) {
906
			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...
907
		}
908
909
		// Better to try (and fail) to set a higher timeout than this system
910
		// supports than to have register fail for more users than it should.
911
		$timeout = $this->set_min_time_limit( 60 ) / 2;
912
913
		$gmt_offset = get_option( 'gmt_offset' );
914
		if ( ! $gmt_offset ) {
915
			$gmt_offset = 0;
916
		}
917
918
		$stats_options = get_option( 'stats_options' );
919
		$stats_id      = isset( $stats_options['blog_id'] )
920
			? $stats_options['blog_id']
921
			: null;
922
923
		/**
924
		 * Filters the request body for additional property addition.
925
		 *
926
		 * @since 7.7.0
927
		 *
928
		 * @param array $post_data request data.
929
		 * @param Array $token_data token data.
930
		 */
931
		$body = apply_filters(
932
			'jetpack_register_request_body',
933
			array(
934
				'siteurl'            => site_url(),
935
				'home'               => home_url(),
936
				'gmt_offset'         => $gmt_offset,
937
				'timezone_string'    => (string) get_option( 'timezone_string' ),
938
				'site_name'          => (string) get_option( 'blogname' ),
939
				'secret_1'           => $secrets['secret_1'],
940
				'secret_2'           => $secrets['secret_2'],
941
				'site_lang'          => get_locale(),
942
				'timeout'            => $timeout,
943
				'stats_id'           => $stats_id,
944
				'state'              => get_current_user_id(),
945
				'site_created'       => $this->get_assumed_site_creation_date(),
946
				'jetpack_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
947
				'ABSPATH'            => Constants::get_constant( 'ABSPATH' ),
948
				'current_user_email' => wp_get_current_user()->user_email,
949
				'connect_plugin'     => $this->get_plugin() ? $this->get_plugin()->get_slug() : null,
950
			)
951
		);
952
953
		$args = array(
954
			'method'  => 'POST',
955
			'body'    => $body,
956
			'headers' => array(
957
				'Accept' => 'application/json',
958
			),
959
			'timeout' => $timeout,
960
		);
961
962
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
963
964
		// TODO: fix URLs for bad hosts.
965
		$response = Client::_wp_remote_request(
966
			$this->api_url( $api_endpoint ),
967
			$args,
968
			true
969
		);
970
971
		// Make sure the response is valid and does not contain any Jetpack errors.
972
		$registration_details = $this->validate_remote_register_response( $response );
973
974
		if ( is_wp_error( $registration_details ) ) {
975
			return $registration_details;
976
		} elseif ( ! $registration_details ) {
977
			return new \WP_Error(
978
				'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...
979
				'Unknown error registering your Jetpack site.',
980
				wp_remote_retrieve_response_code( $response )
981
			);
982
		}
983
984
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
985
			return new \WP_Error(
986
				'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...
987
				'Unable to validate registration of your Jetpack site.',
988
				wp_remote_retrieve_response_code( $response )
989
			);
990
		}
991
992
		if ( isset( $registration_details->jetpack_public ) ) {
993
			$jetpack_public = (int) $registration_details->jetpack_public;
994
		} else {
995
			$jetpack_public = false;
996
		}
997
998
		\Jetpack_Options::update_options(
999
			array(
1000
				'id'         => (int) $registration_details->jetpack_id,
1001
				'blog_token' => (string) $registration_details->jetpack_secret,
1002
				'public'     => $jetpack_public,
1003
			)
1004
		);
1005
1006
		/**
1007
		 * Fires when a site is registered on WordPress.com.
1008
		 *
1009
		 * @since 3.7.0
1010
		 *
1011
		 * @param int $json->jetpack_id Jetpack Blog ID.
1012
		 * @param string $json->jetpack_secret Jetpack Blog Token.
1013
		 * @param int|bool $jetpack_public Is the site public.
1014
		 */
1015
		do_action(
1016
			'jetpack_site_registered',
1017
			$registration_details->jetpack_id,
1018
			$registration_details->jetpack_secret,
1019
			$jetpack_public
1020
		);
1021
1022
		if ( isset( $registration_details->token ) ) {
1023
			/**
1024
			 * Fires when a user token is sent along with the registration data.
1025
			 *
1026
			 * @since 7.6.0
1027
			 *
1028
			 * @param object $token the administrator token for the newly registered site.
1029
			 */
1030
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
1031
		}
1032
1033
		return true;
1034
	}
1035
1036
	/**
1037
	 * Takes the response from the Jetpack register new site endpoint and
1038
	 * verifies it worked properly.
1039
	 *
1040
	 * @since 2.6
1041
	 *
1042
	 * @param Mixed $response the response object, or the error object.
1043
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
1044
	 **/
1045
	protected function validate_remote_register_response( $response ) {
1046
		if ( is_wp_error( $response ) ) {
1047
			return new \WP_Error(
1048
				'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...
1049
				$response->get_error_message()
1050
			);
1051
		}
1052
1053
		$code   = wp_remote_retrieve_response_code( $response );
1054
		$entity = wp_remote_retrieve_body( $response );
1055
1056
		if ( $entity ) {
1057
			$registration_response = json_decode( $entity );
1058
		} else {
1059
			$registration_response = false;
1060
		}
1061
1062
		$code_type = (int) ( $code / 100 );
1063
		if ( 5 === $code_type ) {
1064
			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...
1065
		} elseif ( 408 === $code ) {
1066
			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...
1067
		} elseif ( ! empty( $registration_response->error ) ) {
1068
			if (
1069
				'xml_rpc-32700' === $registration_response->error
1070
				&& ! function_exists( 'xml_parser_create' )
1071
			) {
1072
				$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' );
1073
			} else {
1074
				$error_description = isset( $registration_response->error_description )
1075
					? (string) $registration_response->error_description
1076
					: '';
1077
			}
1078
1079
			return new \WP_Error(
1080
				(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...
1081
				$error_description,
1082
				$code
1083
			);
1084
		} elseif ( 200 !== $code ) {
1085
			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...
1086
		}
1087
1088
		// Jetpack ID error block.
1089
		if ( empty( $registration_response->jetpack_id ) ) {
1090
			return new \WP_Error(
1091
				'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...
1092
				/* translators: %s is an error message string */
1093
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1094
				$entity
1095
			);
1096
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1097
			return new \WP_Error(
1098
				'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...
1099
				/* translators: %s is an error message string */
1100
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1101
				$entity
1102
			);
1103 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1104
			return new \WP_Error(
1105
				'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...
1106
				/* translators: %s is an error message string */
1107
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1108
				$entity
1109
			);
1110
		}
1111
1112
		return $registration_response;
1113
	}
1114
1115
	/**
1116
	 * Adds a used nonce to a list of known nonces.
1117
	 *
1118
	 * @param int    $timestamp the current request timestamp.
1119
	 * @param string $nonce the nonce value.
1120
	 * @return bool whether the nonce is unique or not.
1121
	 */
1122
	public function add_nonce( $timestamp, $nonce ) {
1123
		global $wpdb;
1124
		static $nonces_used_this_request = array();
1125
1126
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
1127
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
1128
		}
1129
1130
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
1131
		$timestamp = (int) $timestamp;
1132
		$nonce     = esc_sql( $nonce );
1133
1134
		// Raw query so we can avoid races: add_option will also update.
1135
		$show_errors = $wpdb->show_errors( false );
1136
1137
		$old_nonce = $wpdb->get_row(
1138
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1139
		);
1140
1141
		if ( is_null( $old_nonce ) ) {
1142
			$return = $wpdb->query(
1143
				$wpdb->prepare(
1144
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1145
					"jetpack_nonce_{$timestamp}_{$nonce}",
1146
					time(),
1147
					'no'
1148
				)
1149
			);
1150
		} else {
1151
			$return = false;
1152
		}
1153
1154
		$wpdb->show_errors( $show_errors );
1155
1156
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1157
1158
		return $return;
1159
	}
1160
1161
	/**
1162
	 * Cleans nonces that were saved when calling ::add_nonce.
1163
	 *
1164
	 * @todo Properly prepare the query before executing it.
1165
	 *
1166
	 * @param bool $all whether to clean even non-expired nonces.
1167
	 */
1168
	public function clean_nonces( $all = false ) {
1169
		global $wpdb;
1170
1171
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1172
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1173
1174
		if ( true !== $all ) {
1175
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1176
			$sql_args[] = time() - 3600;
1177
		}
1178
1179
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1180
1181
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1182
1183
		for ( $i = 0; $i < 1000; $i++ ) {
1184
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1185
				break;
1186
			}
1187
		}
1188
	}
1189
1190
	/**
1191
	 * Sets the Connection custom capabilities.
1192
	 *
1193
	 * @param string[] $caps    Array of the user's capabilities.
1194
	 * @param string   $cap     Capability name.
1195
	 * @param int      $user_id The user ID.
1196
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1197
	 */
1198
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1199
		$is_offline_mode = ( new Status() )->is_offline_mode();
1200
		switch ( $cap ) {
1201
			case 'jetpack_connect':
1202
			case 'jetpack_reconnect':
1203
				if ( $is_offline_mode ) {
1204
					$caps = array( 'do_not_allow' );
1205
					break;
1206
				}
1207
				// Pass through. If it's not offline mode, these should match disconnect.
1208
				// Let users disconnect if it's offline mode, just in case things glitch.
1209
			case 'jetpack_disconnect':
1210
				/**
1211
				 * Filters the jetpack_disconnect capability.
1212
				 *
1213
				 * @since 8.7.0
1214
				 *
1215
				 * @param array An array containing the capability name.
1216
				 */
1217
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1218
				break;
1219
			case 'jetpack_connect_user':
1220
				if ( $is_offline_mode ) {
1221
					$caps = array( 'do_not_allow' );
1222
					break;
1223
				}
1224
				// With user-less connections in mind, non-admin users can connect their account only if a connection owner exists.
1225
				$caps = $this->has_connected_owner() ? array( 'read' ) : array( 'manage_options' );
1226
				break;
1227
		}
1228
		return $caps;
1229
	}
1230
1231
	/**
1232
	 * Builds the timeout limit for queries talking with the wpcom servers.
1233
	 *
1234
	 * Based on local php max_execution_time in php.ini
1235
	 *
1236
	 * @since 5.4
1237
	 * @return int
1238
	 **/
1239
	public function get_max_execution_time() {
1240
		$timeout = (int) ini_get( 'max_execution_time' );
1241
1242
		// Ensure exec time set in php.ini.
1243
		if ( ! $timeout ) {
1244
			$timeout = 30;
1245
		}
1246
		return $timeout;
1247
	}
1248
1249
	/**
1250
	 * Sets a minimum request timeout, and returns the current timeout
1251
	 *
1252
	 * @since 5.4
1253
	 * @param Integer $min_timeout the minimum timeout value.
1254
	 **/
1255 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1256
		$timeout = $this->get_max_execution_time();
1257
		if ( $timeout < $min_timeout ) {
1258
			$timeout = $min_timeout;
1259
			set_time_limit( $timeout );
1260
		}
1261
		return $timeout;
1262
	}
1263
1264
	/**
1265
	 * Get our assumed site creation date.
1266
	 * Calculated based on the earlier date of either:
1267
	 * - Earliest admin user registration date.
1268
	 * - Earliest date of post of any post type.
1269
	 *
1270
	 * @since 7.2.0
1271
	 *
1272
	 * @return string Assumed site creation date and time.
1273
	 */
1274
	public function get_assumed_site_creation_date() {
1275
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1276
		if ( ! empty( $cached_date ) ) {
1277
			return $cached_date;
1278
		}
1279
1280
		$earliest_registered_users  = get_users(
1281
			array(
1282
				'role'    => 'administrator',
1283
				'orderby' => 'user_registered',
1284
				'order'   => 'ASC',
1285
				'fields'  => array( 'user_registered' ),
1286
				'number'  => 1,
1287
			)
1288
		);
1289
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1290
1291
		$earliest_posts = get_posts(
1292
			array(
1293
				'posts_per_page' => 1,
1294
				'post_type'      => 'any',
1295
				'post_status'    => 'any',
1296
				'orderby'        => 'date',
1297
				'order'          => 'ASC',
1298
			)
1299
		);
1300
1301
		// If there are no posts at all, we'll count only on user registration date.
1302
		if ( $earliest_posts ) {
1303
			$earliest_post_date = $earliest_posts[0]->post_date;
1304
		} else {
1305
			$earliest_post_date = PHP_INT_MAX;
1306
		}
1307
1308
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1309
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1310
1311
		return $assumed_date;
1312
	}
1313
1314
	/**
1315
	 * Adds the activation source string as a parameter to passed arguments.
1316
	 *
1317
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1318
	 *
1319
	 * @param array $args arguments that need to have the source added.
1320
	 * @return array $amended arguments.
1321
	 */
1322 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1323
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1324
1325
		if ( $activation_source_name ) {
1326
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1327
			$args['_as'] = urlencode( $activation_source_name );
1328
		}
1329
1330
		if ( $activation_source_keyword ) {
1331
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1332
			$args['_ak'] = urlencode( $activation_source_keyword );
1333
		}
1334
1335
		return $args;
1336
	}
1337
1338
	/**
1339
	 * Returns the callable that would be used to generate secrets.
1340
	 *
1341
	 * @return Callable a function that returns a secure string to be used as a secret.
1342
	 */
1343
	protected function get_secret_callable() {
1344
		if ( ! isset( $this->secret_callable ) ) {
1345
			/**
1346
			 * Allows modification of the callable that is used to generate connection secrets.
1347
			 *
1348
			 * @param Callable a function or method that returns a secret string.
1349
			 */
1350
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', array( $this, 'secret_callable_method' ) );
1351
		}
1352
1353
		return $this->secret_callable;
1354
	}
1355
1356
	/**
1357
	 * Runs the wp_generate_password function with the required parameters. This is the
1358
	 * default implementation of the secret callable, can be overridden using the
1359
	 * jetpack_connection_secret_generator filter.
1360
	 *
1361
	 * @return String $secret value.
1362
	 */
1363
	private function secret_callable_method() {
1364
		return wp_generate_password( 32, false );
1365
	}
1366
1367
	/**
1368
	 * Generates two secret tokens and the end of life timestamp for them.
1369
	 *
1370
	 * @param String  $action  The action name.
1371
	 * @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...
1372
	 * @param Integer $exp     Expiration time in seconds.
1373
	 */
1374
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1375
		if ( false === $user_id ) {
1376
			$user_id = get_current_user_id();
1377
		}
1378
1379
		$callable = $this->get_secret_callable();
1380
1381
		$secrets = \Jetpack_Options::get_raw_option(
1382
			self::SECRETS_OPTION_NAME,
1383
			array()
1384
		);
1385
1386
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1387
1388
		if (
1389
			isset( $secrets[ $secret_name ] ) &&
1390
			$secrets[ $secret_name ]['exp'] > time()
1391
		) {
1392
			return $secrets[ $secret_name ];
1393
		}
1394
1395
		$secret_value = array(
1396
			'secret_1' => call_user_func( $callable ),
1397
			'secret_2' => call_user_func( $callable ),
1398
			'exp'      => time() + $exp,
1399
		);
1400
1401
		$secrets[ $secret_name ] = $secret_value;
1402
1403
		$res = Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1404
		return $res ? $secrets[ $secret_name ] : false;
1405
	}
1406
1407
	/**
1408
	 * Returns two secret tokens and the end of life timestamp for them.
1409
	 *
1410
	 * @param String  $action  The action name.
1411
	 * @param Integer $user_id The user identifier.
1412
	 * @return string|array an array of secrets or an error string.
1413
	 */
1414
	public function get_secrets( $action, $user_id ) {
1415
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1416
		$secrets     = \Jetpack_Options::get_raw_option(
1417
			self::SECRETS_OPTION_NAME,
1418
			array()
1419
		);
1420
1421
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1422
			return self::SECRETS_MISSING;
1423
		}
1424
1425
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1426
			$this->delete_secrets( $action, $user_id );
1427
			return self::SECRETS_EXPIRED;
1428
		}
1429
1430
		return $secrets[ $secret_name ];
1431
	}
1432
1433
	/**
1434
	 * Deletes secret tokens in case they, for example, have expired.
1435
	 *
1436
	 * @param String  $action  The action name.
1437
	 * @param Integer $user_id The user identifier.
1438
	 */
1439
	public function delete_secrets( $action, $user_id ) {
1440
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1441
		$secrets     = \Jetpack_Options::get_raw_option(
1442
			self::SECRETS_OPTION_NAME,
1443
			array()
1444
		);
1445
		if ( isset( $secrets[ $secret_name ] ) ) {
1446
			unset( $secrets[ $secret_name ] );
1447
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1448
		}
1449
	}
1450
1451
	/**
1452
	 * Deletes all connection tokens and transients from the local Jetpack site.
1453
	 * If the plugin object has been provided in the constructor, the function first checks
1454
	 * whether it's the only active connection.
1455
	 * If there are any other connections, the function will do nothing and return `false`
1456
	 * (unless `$ignore_connected_plugins` is set to `true`).
1457
	 *
1458
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1459
	 *
1460
	 * @return bool True if disconnected successfully, false otherwise.
1461
	 */
1462
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1463 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1464
			return false;
1465
		}
1466
1467
		/**
1468
		 * Fires upon the disconnect attempt.
1469
		 * Return `false` to prevent the disconnect.
1470
		 *
1471
		 * @since 8.7.0
1472
		 */
1473
		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...
1474
			return false;
1475
		}
1476
1477
		\Jetpack_Options::delete_option(
1478
			array(
1479
				'blog_token',
1480
				'user_token',
1481
				'user_tokens',
1482
				'master_user',
1483
				'time_diff',
1484
				'fallback_no_verify_ssl_certs',
1485
			)
1486
		);
1487
1488
		\Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
1489
1490
		// Delete cached connected user data.
1491
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1492
		delete_transient( $transient_key );
1493
1494
		// Delete all XML-RPC errors.
1495
		Error_Handler::get_instance()->delete_all_errors();
1496
1497
		return true;
1498
	}
1499
1500
	/**
1501
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1502
	 * If the plugin object has been provided in the constructor, the function first check
1503
	 * whether it's the only active connection.
1504
	 * If there are any other connections, the function will do nothing and return `false`
1505
	 * (unless `$ignore_connected_plugins` is set to `true`).
1506
	 *
1507
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1508
	 *
1509
	 * @return bool True if disconnected successfully, false otherwise.
1510
	 */
1511
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1512 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1513
			return false;
1514
		}
1515
1516
		/**
1517
		 * Fires upon the disconnect attempt.
1518
		 * Return `false` to prevent the disconnect.
1519
		 *
1520
		 * @since 8.7.0
1521
		 */
1522
		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...
1523
			return false;
1524
		}
1525
1526
		$xml = new \Jetpack_IXR_Client();
1527
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1528
1529
		return true;
1530
	}
1531
1532
	/**
1533
	 * Disconnect the plugin and remove the tokens.
1534
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1535
	 * This is a proxy method to simplify the Connection package API.
1536
	 *
1537
	 * @see Manager::disable_plugin()
1538
	 * @see Manager::disconnect_site_wpcom()
1539
	 * @see Manager::delete_all_connection_tokens()
1540
	 *
1541
	 * @return bool
1542
	 */
1543
	public function remove_connection() {
1544
		$this->disable_plugin();
1545
		$this->disconnect_site_wpcom();
1546
		$this->delete_all_connection_tokens();
1547
1548
		return true;
1549
	}
1550
1551
	/**
1552
	 * Completely clearing up the connection, and initiating reconnect.
1553
	 *
1554
	 * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
1555
	 */
1556
	public function reconnect() {
1557
		( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
1558
1559
		$this->disconnect_site_wpcom( true );
1560
		$this->delete_all_connection_tokens( true );
1561
1562
		return $this->register();
1563
	}
1564
1565
	/**
1566
	 * Validate the tokens, and refresh the invalid ones.
1567
	 *
1568
	 * @return string|true|WP_Error True if connection restored or string indicating what's to be done next. A `WP_Error` object otherwise.
1569
	 */
1570
	public function restore() {
1571
		$invalid_tokens = array();
1572
		$can_restore    = $this->can_restore( $invalid_tokens );
1573
1574
		// Tokens are valid. We can't fix the problem we don't see, so the full reconnection is needed.
1575
		if ( ! $can_restore ) {
1576
			$result = $this->reconnect();
1577
			return true === $result ? 'authorize' : $result;
1578
		}
1579
1580
		if ( in_array( 'blog', $invalid_tokens, true ) ) {
1581
			return self::refresh_blog_token();
1582
		}
1583
1584
		if ( in_array( 'user', $invalid_tokens, true ) ) {
1585
			return true === self::refresh_user_token() ? 'authorize' : false;
1586
		}
1587
1588
		return false;
1589
	}
1590
1591
	/**
1592
	 * Determine whether we can restore the connection, or the full reconnect is needed.
1593
	 *
1594
	 * @param array $invalid_tokens The array the invalid tokens are stored in, provided by reference.
1595
	 *
1596
	 * @return bool `True` if the connection can be restored, `false` otherwise.
1597
	 */
1598
	public function can_restore( &$invalid_tokens ) {
1599
		$invalid_tokens = array();
1600
1601
		$validated_tokens = $this->validate_tokens();
1602
1603
		if ( ! is_array( $validated_tokens ) || count( array_diff_key( array_flip( array( 'blog_token', 'user_token' ) ), $validated_tokens ) ) ) {
1604
			return false;
1605
		}
1606
1607
		if ( empty( $validated_tokens['blog_token']['is_healthy'] ) ) {
1608
			$invalid_tokens[] = 'blog';
1609
		}
1610
1611
		if ( empty( $validated_tokens['user_token']['is_healthy'] ) ) {
1612
			$invalid_tokens[] = 'user';
1613
		}
1614
1615
		// If both tokens are invalid, we can't restore the connection.
1616
		return 1 === count( $invalid_tokens );
1617
	}
1618
1619
	/**
1620
	 * Perform the API request to validate the blog and user tokens.
1621
	 *
1622
	 * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
1623
	 *
1624
	 * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
1625
	 */
1626
	public function validate_tokens( $user_id = null ) {
1627
		$blog_id = Jetpack_Options::get_option( 'id' );
1628
		if ( ! $blog_id ) {
1629
			return new WP_Error( 'site_not_registered', 'Site not registered.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'site_not_registered'.

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

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

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

Loading history...
1630
		}
1631
		$url = sprintf(
1632
			'%s/%s/v%s/%s',
1633
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
1634
			'wpcom',
1635
			'2',
1636
			'sites/' . $blog_id . '/jetpack-token-health'
1637
		);
1638
1639
		$user_token = $this->get_access_token( $user_id ? $user_id : get_current_user_id() );
1640
		$blog_token = $this->get_access_token();
1641
		$method     = 'POST';
1642
		$body       = array(
1643
			'user_token' => $this->get_signed_token( $user_token ),
0 ignored issues
show
Security Bug introduced by
It seems like $user_token defined by $this->get_access_token(... get_current_user_id()) on line 1639 can also be of type false; however, Automattic\Jetpack\Conne...ger::get_signed_token() does only seem to accept object, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
1644
			'blog_token' => $this->get_signed_token( $blog_token ),
0 ignored issues
show
Security Bug introduced by
It seems like $blog_token defined by $this->get_access_token() on line 1640 can also be of type false; however, Automattic\Jetpack\Conne...ger::get_signed_token() does only seem to accept object, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
1645
		);
1646
		$response   = Client::_wp_remote_request( $url, compact( 'body', 'method' ) );
1647
1648
		if ( is_wp_error( $response ) || ! wp_remote_retrieve_body( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
1649
			return false;
1650
		}
1651
1652
		$body = json_decode( wp_remote_retrieve_body( $response ), true );
1653
1654
		return $body ? $body : false;
1655
	}
1656
1657
	/**
1658
	 * Responds to a WordPress.com call to register the current site.
1659
	 * Should be changed to protected.
1660
	 *
1661
	 * @param array $registration_data Array of [ secret_1, user_id ].
1662
	 */
1663
	public function handle_registration( array $registration_data ) {
1664
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1665
		if ( empty( $registration_user_id ) ) {
1666
			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...
1667
		}
1668
1669
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1670
	}
1671
1672
	/**
1673
	 * Verify a Previously Generated Secret.
1674
	 *
1675
	 * @param string $action   The type of secret to verify.
1676
	 * @param string $secret_1 The secret string to compare to what is stored.
1677
	 * @param int    $user_id  The user ID of the owner of the secret.
1678
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1679
	 */
1680
	public function verify_secrets( $action, $secret_1, $user_id ) {
1681
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1682
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1683
			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...
1684
		}
1685
1686
		$user = get_user_by( 'id', $user_id );
1687
1688
		/**
1689
		 * We've begun verifying the previously generated secret.
1690
		 *
1691
		 * @since 7.5.0
1692
		 *
1693
		 * @param string   $action The type of secret to verify.
1694
		 * @param \WP_User $user The user object.
1695
		 */
1696
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1697
1698
		$return_error = function ( \WP_Error $error ) use ( $action, $user ) {
1699
			/**
1700
			 * Verifying of the previously generated secret has failed.
1701
			 *
1702
			 * @since 7.5.0
1703
			 *
1704
			 * @param string    $action  The type of secret to verify.
1705
			 * @param \WP_User  $user The user object.
1706
			 * @param \WP_Error $error The error object.
1707
			 */
1708
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1709
1710
			return $error;
1711
		};
1712
1713
		$stored_secrets = $this->get_secrets( $action, $user_id );
1714
		$this->delete_secrets( $action, $user_id );
1715
1716
		$error = null;
1717
		if ( empty( $secret_1 ) ) {
1718
			$error = $return_error(
1719
				new \WP_Error(
1720
					'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...
1721
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1722
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1723
					400
1724
				)
1725
			);
1726
		} elseif ( ! is_string( $secret_1 ) ) {
1727
			$error = $return_error(
1728
				new \WP_Error(
1729
					'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...
1730
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1731
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1732
					400
1733
				)
1734
			);
1735
		} elseif ( empty( $user_id ) ) {
1736
			// $user_id is passed around during registration as "state".
1737
			$error = $return_error(
1738
				new \WP_Error(
1739
					'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...
1740
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1741
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1742
					400
1743
				)
1744
			);
1745
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1746
			$error = $return_error(
1747
				new \WP_Error(
1748
					'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...
1749
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1750
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1751
					400
1752
				)
1753
			);
1754
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1755
			$error = $return_error(
1756
				new \WP_Error(
1757
					'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...
1758
					__( 'Verification secrets not found', 'jetpack' ),
1759
					400
1760
				)
1761
			);
1762
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1763
			$error = $return_error(
1764
				new \WP_Error(
1765
					'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...
1766
					__( 'Verification took too long', 'jetpack' ),
1767
					400
1768
				)
1769
			);
1770
		} elseif ( ! $stored_secrets ) {
1771
			$error = $return_error(
1772
				new \WP_Error(
1773
					'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...
1774
					__( 'Verification secrets are empty', 'jetpack' ),
1775
					400
1776
				)
1777
			);
1778
		} elseif ( is_wp_error( $stored_secrets ) ) {
1779
			$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...
1780
			$error = $return_error( $stored_secrets );
1781
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1782
			$error = $return_error(
1783
				new \WP_Error(
1784
					'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...
1785
					__( 'Verification secrets are incomplete', 'jetpack' ),
1786
					400
1787
				)
1788
			);
1789
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1790
			$error = $return_error(
1791
				new \WP_Error(
1792
					'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...
1793
					__( 'Secret mismatch', 'jetpack' ),
1794
					400
1795
				)
1796
			);
1797
		}
1798
1799
		// Something went wrong during the checks, returning the error.
1800
		if ( ! empty( $error ) ) {
1801
			return $error;
1802
		}
1803
1804
		/**
1805
		 * We've succeeded at verifying the previously generated secret.
1806
		 *
1807
		 * @since 7.5.0
1808
		 *
1809
		 * @param string   $action The type of secret to verify.
1810
		 * @param \WP_User $user The user object.
1811
		 */
1812
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1813
1814
		return $stored_secrets['secret_2'];
1815
	}
1816
1817
	/**
1818
	 * Responds to a WordPress.com call to authorize the current user.
1819
	 * Should be changed to protected.
1820
	 */
1821
	public function handle_authorization() {
1822
1823
	}
1824
1825
	/**
1826
	 * Obtains the auth token.
1827
	 *
1828
	 * @param array $data The request data.
1829
	 * @return object|\WP_Error Returns the auth token on success.
1830
	 *                          Returns a \WP_Error on failure.
1831
	 */
1832
	public function get_token( $data ) {
1833
		$roles = new Roles();
1834
		$role  = $roles->translate_current_user_to_role();
1835
1836
		if ( ! $role ) {
1837
			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...
1838
		}
1839
1840
		$client_secret = $this->get_access_token();
1841
		if ( ! $client_secret ) {
1842
			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...
1843
		}
1844
1845
		/**
1846
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1847
		 * data processing.
1848
		 *
1849
		 * @since 8.0.0
1850
		 *
1851
		 * @param string $redirect_url Defaults to the site admin URL.
1852
		 */
1853
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1854
1855
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1856
1857
		/**
1858
		* Filter the URL to redirect the user back to when the authentication process
1859
		* is complete.
1860
		*
1861
		* @since 8.0.0
1862
		*
1863
		* @param string $redirect_url Defaults to the site URL.
1864
		*/
1865
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1866
1867
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1868
			? $data['redirect_uri']
1869
			: add_query_arg(
1870
				array(
1871
					'handler'  => 'jetpack-connection-webhooks',
1872
					'action'   => 'authorize',
1873
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1874
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1875
				),
1876
				esc_url( $processing_url )
1877
			);
1878
1879
		/**
1880
		 * Filters the token request data.
1881
		 *
1882
		 * @since 8.0.0
1883
		 *
1884
		 * @param array $request_data request data.
1885
		 */
1886
		$body = apply_filters(
1887
			'jetpack_token_request_body',
1888
			array(
1889
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1890
				'client_secret' => $client_secret->secret,
1891
				'grant_type'    => 'authorization_code',
1892
				'code'          => $data['code'],
1893
				'redirect_uri'  => $redirect_uri,
1894
			)
1895
		);
1896
1897
		$args = array(
1898
			'method'  => 'POST',
1899
			'body'    => $body,
1900
			'headers' => array(
1901
				'Accept' => 'application/json',
1902
			),
1903
		);
1904
		add_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1905
		$response = Client::_wp_remote_request( $this->api_url( 'token' ), $args );
1906
		remove_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1907
1908
		if ( is_wp_error( $response ) ) {
1909
			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...
1910
		}
1911
1912
		$code   = wp_remote_retrieve_response_code( $response );
1913
		$entity = wp_remote_retrieve_body( $response );
1914
1915
		if ( $entity ) {
1916
			$json = json_decode( $entity );
1917
		} else {
1918
			$json = false;
1919
		}
1920
1921 View Code Duplication
		if ( 200 !== $code || ! empty( $json->error ) ) {
1922
			if ( empty( $json->error ) ) {
1923
				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...
1924
			}
1925
1926
			/* translators: Error description string. */
1927
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1928
1929
			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...
1930
		}
1931
1932
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1933
			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...
1934
		}
1935
1936
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1937
			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...
1938
		}
1939
1940
		if ( empty( $json->scope ) ) {
1941
			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...
1942
		}
1943
1944
		// TODO: get rid of the error silencer.
1945
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1946
		@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...
1947
		if ( empty( $role ) || empty( $hmac ) ) {
1948
			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...
1949
		}
1950
1951
		if ( $this->sign_role( $role ) !== $json->scope ) {
1952
			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...
1953
		}
1954
1955
		$cap = $roles->translate_role_to_cap( $role );
1956
		if ( ! $cap ) {
1957
			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...
1958
		}
1959
1960
		if ( ! current_user_can( $cap ) ) {
1961
			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...
1962
		}
1963
1964
		return (string) $json->access_token;
1965
	}
1966
1967
	/**
1968
	 * Increases the request timeout value to 30 seconds.
1969
	 *
1970
	 * @return int Returns 30.
1971
	 */
1972
	public function increase_timeout() {
1973
		return 30;
1974
	}
1975
1976
	/**
1977
	 * Builds a URL to the Jetpack connection auth page.
1978
	 *
1979
	 * @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...
1980
	 * @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...
1981
	 * @return string Connect URL.
1982
	 */
1983
	public function get_authorization_url( $user = null, $redirect = null ) {
1984
1985
		if ( empty( $user ) ) {
1986
			$user = wp_get_current_user();
1987
		}
1988
1989
		$roles       = new Roles();
1990
		$role        = $roles->translate_user_to_role( $user );
1991
		$signed_role = $this->sign_role( $role );
1992
1993
		/**
1994
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1995
		 * data processing.
1996
		 *
1997
		 * @since 8.0.0
1998
		 *
1999
		 * @param string $redirect_url Defaults to the site admin URL.
2000
		 */
2001
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
2002
2003
		/**
2004
		 * Filter the URL to redirect the user back to when the authorization process
2005
		 * is complete.
2006
		 *
2007
		 * @since 8.0.0
2008
		 *
2009
		 * @param string $redirect_url Defaults to the site URL.
2010
		 */
2011
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
2012
2013
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
2014
2015
		/**
2016
		 * Filter the type of authorization.
2017
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
2018
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
2019
		 *
2020
		 * @since 4.3.3
2021
		 *
2022
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
2023
		 */
2024
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
2025
2026
		/**
2027
		 * Filters the user connection request data for additional property addition.
2028
		 *
2029
		 * @since 8.0.0
2030
		 *
2031
		 * @param array $request_data request data.
2032
		 */
2033
		$body = apply_filters(
2034
			'jetpack_connect_request_body',
2035
			array(
2036
				'response_type' => 'code',
2037
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
2038
				'redirect_uri'  => add_query_arg(
2039
					array(
2040
						'handler'  => 'jetpack-connection-webhooks',
2041
						'action'   => 'authorize',
2042
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
2043
						'redirect' => $redirect ? rawurlencode( $redirect ) : false,
2044
					),
2045
					esc_url( $processing_url )
2046
				),
2047
				'state'         => $user->ID,
2048
				'scope'         => $signed_role,
2049
				'user_email'    => $user->user_email,
2050
				'user_login'    => $user->user_login,
2051
				'is_active'     => $this->is_active(),
2052
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
2053
				'auth_type'     => $auth_type,
2054
				'secret'        => $secrets['secret_1'],
2055
				'blogname'      => get_option( 'blogname' ),
2056
				'site_url'      => site_url(),
2057
				'home_url'      => home_url(),
2058
				'site_icon'     => get_site_icon_url(),
2059
				'site_lang'     => get_locale(),
2060
				'site_created'  => $this->get_assumed_site_creation_date(),
2061
			)
2062
		);
2063
2064
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
2065
2066
		$api_url = $this->api_url( 'authorize' );
2067
2068
		return add_query_arg( $body, $api_url );
2069
	}
2070
2071
	/**
2072
	 * Authorizes the user by obtaining and storing the user token.
2073
	 *
2074
	 * @param array $data The request data.
2075
	 * @return string|\WP_Error Returns a string on success.
2076
	 *                          Returns a \WP_Error on failure.
2077
	 */
2078
	public function authorize( $data = array() ) {
2079
		/**
2080
		 * Action fired when user authorization starts.
2081
		 *
2082
		 * @since 8.0.0
2083
		 */
2084
		do_action( 'jetpack_authorize_starting' );
2085
2086
		$roles = new Roles();
2087
		$role  = $roles->translate_current_user_to_role();
2088
2089
		if ( ! $role ) {
2090
			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...
2091
		}
2092
2093
		$cap = $roles->translate_role_to_cap( $role );
2094
		if ( ! $cap ) {
2095
			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...
2096
		}
2097
2098
		if ( ! empty( $data['error'] ) ) {
2099
			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...
2100
		}
2101
2102
		if ( ! isset( $data['state'] ) ) {
2103
			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...
2104
		}
2105
2106
		if ( ! ctype_digit( $data['state'] ) ) {
2107
			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...
2108
		}
2109
2110
		$current_user_id = get_current_user_id();
2111
		if ( $current_user_id !== (int) $data['state'] ) {
2112
			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...
2113
		}
2114
2115
		if ( empty( $data['code'] ) ) {
2116
			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...
2117
		}
2118
2119
		$token = $this->get_token( $data );
2120
2121 View Code Duplication
		if ( is_wp_error( $token ) ) {
2122
			$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...
2123
			if ( empty( $code ) ) {
2124
				$code = 'invalid_token';
2125
			}
2126
			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...
2127
		}
2128
2129
		if ( ! $token ) {
2130
			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...
2131
		}
2132
2133
		$is_connection_owner = ! $this->has_connected_owner();
2134
2135
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_connection_owner );
2136
2137
		/**
2138
		 * Fires after user has successfully received an auth token.
2139
		 *
2140
		 * @since 3.9.0
2141
		 */
2142
		do_action( 'jetpack_user_authorized' );
2143
2144
		if ( ! $is_connection_owner ) {
2145
			/**
2146
			 * Action fired when a secondary user has been authorized.
2147
			 *
2148
			 * @since 8.0.0
2149
			 */
2150
			do_action( 'jetpack_authorize_ending_linked' );
2151
			return 'linked';
2152
		}
2153
2154
		/**
2155
		 * Action fired when the master user has been authorized.
2156
		 *
2157
		 * @since 8.0.0
2158
		 *
2159
		 * @param array $data The request data.
2160
		 */
2161
		do_action( 'jetpack_authorize_ending_authorized', $data );
2162
2163
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
2164
2165
		// Start nonce cleaner.
2166
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2167
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
2168
2169
		return 'authorized';
2170
	}
2171
2172
	/**
2173
	 * Disconnects from the Jetpack servers.
2174
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2175
	 */
2176
	public function disconnect_site() {
2177
2178
	}
2179
2180
	/**
2181
	 * The Base64 Encoding of the SHA1 Hash of the Input.
2182
	 *
2183
	 * @param string $text The string to hash.
2184
	 * @return string
2185
	 */
2186
	public function sha1_base64( $text ) {
2187
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2188
	}
2189
2190
	/**
2191
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
2192
	 *
2193
	 * @param string $domain The domain to check.
2194
	 *
2195
	 * @return bool|WP_Error
2196
	 */
2197
	public function is_usable_domain( $domain ) {
2198
2199
		// If it's empty, just fail out.
2200
		if ( ! $domain ) {
2201
			return new \WP_Error(
2202
				'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...
2203
				/* translators: %1$s is a domain name. */
2204
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
2205
			);
2206
		}
2207
2208
		/**
2209
		 * Skips the usuable domain check when connecting a site.
2210
		 *
2211
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
2212
		 *
2213
		 * @since 4.1.0
2214
		 *
2215
		 * @param bool If the check should be skipped. Default false.
2216
		 */
2217
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
2218
			return true;
2219
		}
2220
2221
		// None of the explicit localhosts.
2222
		$forbidden_domains = array(
2223
			'wordpress.com',
2224
			'localhost',
2225
			'localhost.localdomain',
2226
			'127.0.0.1',
2227
			'local.wordpress.test',         // VVV pattern.
2228
			'local.wordpress-trunk.test',   // VVV pattern.
2229
			'src.wordpress-develop.test',   // VVV pattern.
2230
			'build.wordpress-develop.test', // VVV pattern.
2231
		);
2232 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
2233
			return new \WP_Error(
2234
				'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...
2235
				sprintf(
2236
					/* translators: %1$s is a domain name. */
2237
					__(
2238
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
2239
						'jetpack'
2240
					),
2241
					$domain
2242
				)
2243
			);
2244
		}
2245
2246
		// No .test or .local domains.
2247 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
2248
			return new \WP_Error(
2249
				'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...
2250
				sprintf(
2251
					/* translators: %1$s is a domain name. */
2252
					__(
2253
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
2254
						'jetpack'
2255
					),
2256
					$domain
2257
				)
2258
			);
2259
		}
2260
2261
		// No WPCOM subdomains.
2262 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
2263
			return new \WP_Error(
2264
				'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...
2265
				sprintf(
2266
					/* translators: %1$s is a domain name. */
2267
					__(
2268
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
2269
						'jetpack'
2270
					),
2271
					$domain
2272
				)
2273
			);
2274
		}
2275
2276
		// If PHP was compiled without support for the Filter module (very edge case).
2277
		if ( ! function_exists( 'filter_var' ) ) {
2278
			// Just pass back true for now, and let wpcom sort it out.
2279
			return true;
2280
		}
2281
2282
		return true;
2283
	}
2284
2285
	/**
2286
	 * Gets the requested token.
2287
	 *
2288
	 * Tokens are one of two types:
2289
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
2290
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
2291
	 *    are not associated with a user account. They represent the site's connection with
2292
	 *    the Jetpack servers.
2293
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
2294
	 *
2295
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
2296
	 * token, and $private is a secret that should never be displayed anywhere or sent
2297
	 * over the network; it's used only for signing things.
2298
	 *
2299
	 * Blog Tokens can be "Normal" or "Special".
2300
	 * * Normal: The result of a normal connection flow. They look like
2301
	 *   "{$random_string_1}.{$random_string_2}"
2302
	 *   That is, $token_key and $private are both random strings.
2303
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
2304
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
2305
	 *   constant (rare).
2306
	 * * Special: A connection token for sites that have gone through an alternative
2307
	 *   connection flow. They look like:
2308
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
2309
	 *   That is, $private is a random string and $token_key has a special structure with
2310
	 *   lots of semicolons.
2311
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
2312
	 *   JETPACK_BLOG_TOKEN constant.
2313
	 *
2314
	 * In particular, note that Normal Blog Tokens never start with ";" and that
2315
	 * Special Blog Tokens always do.
2316
	 *
2317
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
2318
	 * order:
2319
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
2320
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
2321
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
2322
	 *
2323
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
2324
	 * @param string|false $token_key If provided, check that the token matches the provided input.
2325
	 * @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.
2326
	 *
2327
	 * @return object|false
2328
	 */
2329
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
2330
		$possible_special_tokens = array();
2331
		$possible_normal_tokens  = array();
2332
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
2333
2334
		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...
2335
			if ( ! $user_tokens ) {
2336
				return $suppress_errors ? false : new \WP_Error( 'no_user_tokens', __( 'No user tokens found', 'jetpack' ) );
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...
2337
			}
2338
			if ( self::CONNECTION_OWNER === $user_id ) {
2339
				$user_id = \Jetpack_Options::get_option( 'master_user' );
2340
				if ( ! $user_id ) {
2341
					return $suppress_errors ? false : new \WP_Error( 'empty_master_user_option', __( 'No primary user defined', 'jetpack' ) );
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...
2342
				}
2343
			}
2344
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
2345
				// translators: %s is the user ID.
2346
				return $suppress_errors ? false : new \WP_Error( 'no_token_for_user', sprintf( __( 'No token for user %d', 'jetpack' ), $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...
2347
			}
2348
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
2349 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
2350
				// translators: %s is the user ID.
2351
				return $suppress_errors ? false : new \WP_Error( 'token_malformed', sprintf( __( 'Token for user %d is malformed', 'jetpack' ), $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...
2352
			}
2353
			if ( $user_token_chunks[2] !== (string) $user_id ) {
2354
				// translators: %1$d is the ID of the requested user. %2$d is the user ID found in the token.
2355
				return $suppress_errors ? false : new \WP_Error( 'user_id_mismatch', sprintf( __( 'Requesting user_id %1$d does not match token user_id %2$d', 'jetpack' ), $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...
2356
			}
2357
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
2358
		} else {
2359
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
2360
			if ( $stored_blog_token ) {
2361
				$possible_normal_tokens[] = $stored_blog_token;
2362
			}
2363
2364
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
2365
2366
			if ( $defined_tokens_string ) {
2367
				$defined_tokens = explode( ',', $defined_tokens_string );
2368
				foreach ( $defined_tokens as $defined_token ) {
2369
					if ( ';' === $defined_token[0] ) {
2370
						$possible_special_tokens[] = $defined_token;
2371
					} else {
2372
						$possible_normal_tokens[] = $defined_token;
2373
					}
2374
				}
2375
			}
2376
		}
2377
2378
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2379
			$possible_tokens = $possible_normal_tokens;
2380
		} else {
2381
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
2382
		}
2383
2384
		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...
2385
			// If no user tokens were found, it would have failed earlier, so this is about blog token.
2386
			return $suppress_errors ? false : new \WP_Error( 'no_possible_tokens', __( 'No blog token found', 'jetpack' ) );
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...
2387
		}
2388
2389
		$valid_token = false;
2390
2391
		if ( false === $token_key ) {
2392
			// Use first token.
2393
			$valid_token = $possible_tokens[0];
2394
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2395
			// Use first normal token.
2396
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
2397
		} else {
2398
			// Use the token matching $token_key or false if none.
2399
			// Ensure we check the full key.
2400
			$token_check = rtrim( $token_key, '.' ) . '.';
2401
2402
			foreach ( $possible_tokens as $possible_token ) {
2403
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
2404
					$valid_token = $possible_token;
2405
					break;
2406
				}
2407
			}
2408
		}
2409
2410
		if ( ! $valid_token ) {
2411
			if ( $user_id ) {
2412
				// translators: %d is the user ID.
2413
				return $suppress_errors ? false : new \WP_Error( 'no_valid_user_token', sprintf( __( 'Invalid token for user %d', 'jetpack' ), $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_valid_user_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...
2414
			} else {
2415
				return $suppress_errors ? false : new \WP_Error( 'no_valid_blog_token', __( 'Invalid blog token', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_valid_blog_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...
2416
			}
2417
		}
2418
2419
		return (object) array(
2420
			'secret'           => $valid_token,
2421
			'external_user_id' => (int) $user_id,
2422
		);
2423
	}
2424
2425
	/**
2426
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2427
	 * since it is passed by reference to various methods.
2428
	 * Capture it here so we can verify the signature later.
2429
	 *
2430
	 * @param array $methods an array of available XMLRPC methods.
2431
	 * @return array the same array, since this method doesn't add or remove anything.
2432
	 */
2433
	public function xmlrpc_methods( $methods ) {
2434
		$this->raw_post_data = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
2435
		return $methods;
2436
	}
2437
2438
	/**
2439
	 * Resets the raw post data parameter for testing purposes.
2440
	 */
2441
	public function reset_raw_post_data() {
2442
		$this->raw_post_data = null;
2443
	}
2444
2445
	/**
2446
	 * Registering an additional method.
2447
	 *
2448
	 * @param array $methods an array of available XMLRPC methods.
2449
	 * @return array the amended array in case the method is added.
2450
	 */
2451
	public function public_xmlrpc_methods( $methods ) {
2452
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2453
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2454
		}
2455
		return $methods;
2456
	}
2457
2458
	/**
2459
	 * Handles a getOptions XMLRPC method call.
2460
	 *
2461
	 * @param array $args method call arguments.
2462
	 * @return an amended XMLRPC server options array.
2463
	 */
2464
	public function jetpack_get_options( $args ) {
2465
		global $wp_xmlrpc_server;
2466
2467
		$wp_xmlrpc_server->escape( $args );
2468
2469
		$username = $args[1];
2470
		$password = $args[2];
2471
2472
		$user = $wp_xmlrpc_server->login( $username, $password );
2473
		if ( ! $user ) {
2474
			return $wp_xmlrpc_server->error;
2475
		}
2476
2477
		$options   = array();
2478
		$user_data = $this->get_connected_user_data();
2479
		if ( is_array( $user_data ) ) {
2480
			$options['jetpack_user_id']         = array(
2481
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2482
				'readonly' => true,
2483
				'value'    => $user_data['ID'],
2484
			);
2485
			$options['jetpack_user_login']      = array(
2486
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2487
				'readonly' => true,
2488
				'value'    => $user_data['login'],
2489
			);
2490
			$options['jetpack_user_email']      = array(
2491
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2492
				'readonly' => true,
2493
				'value'    => $user_data['email'],
2494
			);
2495
			$options['jetpack_user_site_count'] = array(
2496
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2497
				'readonly' => true,
2498
				'value'    => $user_data['site_count'],
2499
			);
2500
		}
2501
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2502
		$args                           = stripslashes_deep( $args );
2503
		return $wp_xmlrpc_server->wp_getOptions( $args );
2504
	}
2505
2506
	/**
2507
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2508
	 *
2509
	 * @param array $options standard Core options.
2510
	 * @return array amended options.
2511
	 */
2512
	public function xmlrpc_options( $options ) {
2513
		$jetpack_client_id = false;
2514
		if ( $this->is_active() ) {
2515
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2516
		}
2517
		$options['jetpack_version'] = array(
2518
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2519
			'readonly' => true,
2520
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2521
		);
2522
2523
		$options['jetpack_client_id'] = array(
2524
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2525
			'readonly' => true,
2526
			'value'    => $jetpack_client_id,
2527
		);
2528
		return $options;
2529
	}
2530
2531
	/**
2532
	 * Resets the saved authentication state in between testing requests.
2533
	 */
2534
	public function reset_saved_auth_state() {
2535
		$this->xmlrpc_verification = null;
2536
	}
2537
2538
	/**
2539
	 * Sign a user role with the master access token.
2540
	 * If not specified, will default to the current user.
2541
	 *
2542
	 * @access public
2543
	 *
2544
	 * @param string $role    User role.
2545
	 * @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...
2546
	 * @return string Signed user role.
2547
	 */
2548
	public function sign_role( $role, $user_id = null ) {
2549
		if ( empty( $user_id ) ) {
2550
			$user_id = (int) get_current_user_id();
2551
		}
2552
2553
		if ( ! $user_id ) {
2554
			return false;
2555
		}
2556
2557
		$token = $this->get_access_token();
2558
		if ( ! $token || is_wp_error( $token ) ) {
2559
			return false;
2560
		}
2561
2562
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2563
	}
2564
2565
	/**
2566
	 * Set the plugin instance.
2567
	 *
2568
	 * @param Plugin $plugin_instance The plugin instance.
2569
	 *
2570
	 * @return $this
2571
	 */
2572
	public function set_plugin_instance( Plugin $plugin_instance ) {
2573
		$this->plugin = $plugin_instance;
2574
2575
		return $this;
2576
	}
2577
2578
	/**
2579
	 * Retrieve the plugin management object.
2580
	 *
2581
	 * @return Plugin
2582
	 */
2583
	public function get_plugin() {
2584
		return $this->plugin;
2585
	}
2586
2587
	/**
2588
	 * Get all connected plugins information, excluding those disconnected by user.
2589
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2590
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2591
	 * so please make sure not to run the method too early in the code.
2592
	 *
2593
	 * @return array|WP_Error
2594
	 */
2595
	public function get_connected_plugins() {
2596
		$maybe_plugins = Plugin_Storage::get_all( true );
2597
2598
		if ( $maybe_plugins instanceof WP_Error ) {
2599
			return $maybe_plugins;
2600
		}
2601
2602
		return $maybe_plugins;
2603
	}
2604
2605
	/**
2606
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2607
	 * Note: this method does not remove any access tokens.
2608
	 *
2609
	 * @return bool
2610
	 */
2611
	public function disable_plugin() {
2612
		if ( ! $this->plugin ) {
2613
			return false;
2614
		}
2615
2616
		return $this->plugin->disable();
2617
	}
2618
2619
	/**
2620
	 * Force plugin reconnect after user-initiated disconnect.
2621
	 * After its called, the plugin will be allowed to use the connection again.
2622
	 * Note: this method does not initialize access tokens.
2623
	 *
2624
	 * @return bool
2625
	 */
2626
	public function enable_plugin() {
2627
		if ( ! $this->plugin ) {
2628
			return false;
2629
		}
2630
2631
		return $this->plugin->enable();
2632
	}
2633
2634
	/**
2635
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2636
	 * If no plugin slug was passed into the constructor, always returns true.
2637
	 *
2638
	 * @return bool
2639
	 */
2640
	public function is_plugin_enabled() {
2641
		if ( ! $this->plugin ) {
2642
			return true;
2643
		}
2644
2645
		return $this->plugin->is_enabled();
2646
	}
2647
2648
	/**
2649
	 * Perform the API request to refresh the blog token.
2650
	 * Note that we are making this request on behalf of the Jetpack master user,
2651
	 * given they were (most probably) the ones that registered the site at the first place.
2652
	 *
2653
	 * @return WP_Error|bool The result of updating the blog_token option.
2654
	 */
2655
	public static function refresh_blog_token() {
2656
		( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
2657
2658
		$blog_id = Jetpack_Options::get_option( 'id' );
2659
		if ( ! $blog_id ) {
2660
			return new WP_Error( 'site_not_registered', 'Site not registered.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'site_not_registered'.

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

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

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

Loading history...
2661
		}
2662
2663
		$url     = sprintf(
2664
			'%s/%s/v%s/%s',
2665
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
2666
			'wpcom',
2667
			'2',
2668
			'sites/' . $blog_id . '/jetpack-refresh-blog-token'
2669
		);
2670
		$method  = 'POST';
2671
		$user_id = get_current_user_id();
2672
2673
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2674
2675
		if ( is_wp_error( $response ) ) {
2676
			return new WP_Error( 'refresh_blog_token_http_request_failed', $response->get_error_message() );
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 'refresh_blog_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...
2677
		}
2678
2679
		$code   = wp_remote_retrieve_response_code( $response );
2680
		$entity = wp_remote_retrieve_body( $response );
2681
2682
		if ( $entity ) {
2683
			$json = json_decode( $entity );
2684
		} else {
2685
			$json = false;
2686
		}
2687
2688 View Code Duplication
		if ( 200 !== $code ) {
2689
			if ( empty( $json->code ) ) {
2690
				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...
2691
			}
2692
2693
			/* translators: Error description string. */
2694
			$error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->message ) : '';
2695
2696
			return new WP_Error( (string) $json->code, $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->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...
2697
		}
2698
2699
		if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
2700
			return new WP_Error( 'jetpack_secret', '', $code );
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...
2701
		}
2702
2703
		return Jetpack_Options::update_option( 'blog_token', (string) $json->jetpack_secret );
2704
	}
2705
2706
	/**
2707
	 * Disconnect the user from WP.com, and initiate the reconnect process.
2708
	 *
2709
	 * @return bool
2710
	 */
2711
	public static function refresh_user_token() {
2712
		( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2713
2714
		self::disconnect_user( null, true );
2715
2716
		return true;
2717
	}
2718
2719
	/**
2720
	 * Fetches a signed token.
2721
	 *
2722
	 * @param object $token the token.
2723
	 * @return WP_Error|string a signed token
2724
	 */
2725
	public function get_signed_token( $token ) {
2726
		if ( ! isset( $token->secret ) || empty( $token->secret ) ) {
2727
			return new WP_Error( 'invalid_token' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_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...
2728
		}
2729
2730
		list( $token_key, $token_secret ) = explode( '.', $token->secret );
2731
2732
		$token_key = sprintf(
2733
			'%s:%d:%d',
2734
			$token_key,
2735
			Constants::get_constant( 'JETPACK__API_VERSION' ),
2736
			$token->external_user_id
2737
		);
2738
2739
		$timestamp = time();
2740
2741 View Code Duplication
		if ( function_exists( 'wp_generate_password' ) ) {
2742
			$nonce = wp_generate_password( 10, false );
2743
		} else {
2744
			$nonce = substr( sha1( wp_rand( 0, 1000000 ) ), 0, 10 );
2745
		}
2746
2747
		$normalized_request_string = join(
2748
			"\n",
2749
			array(
2750
				$token_key,
2751
				$timestamp,
2752
				$nonce,
2753
			)
2754
		) . "\n";
2755
2756
		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2757
		$signature = base64_encode( hash_hmac( 'sha1', $normalized_request_string, $token_secret, true ) );
2758
2759
		$auth = array(
2760
			'token'     => $token_key,
2761
			'timestamp' => $timestamp,
2762
			'nonce'     => $nonce,
2763
			'signature' => $signature,
2764
		);
2765
2766
		$header_pieces = array();
2767
		foreach ( $auth as $key => $value ) {
2768
			$header_pieces[] = sprintf( '%s="%s"', $key, $value );
2769
		}
2770
2771
		return join( ' ', $header_pieces );
2772
	}
2773
2774
	/**
2775
	 * If connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2776
	 *
2777
	 * @param array $stats The Heartbeat stats array.
2778
	 * @return array $stats
2779
	 */
2780
	public function add_stats_to_heartbeat( $stats ) {
2781
2782
		if ( ! $this->is_active() ) {
2783
			return $stats;
2784
		}
2785
2786
		$active_plugins_using_connection = Plugin_Storage::get_all();
2787
		foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
2788
			if ( 'jetpack' !== $plugin_slug ) {
2789
				$stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2790
				$stats[ $stats_group ][] = $plugin_slug;
2791
			}
2792
		}
2793
		return $stats;
2794
	}
2795
}
2796