Completed
Push — update/userless-non-admin-conn... ( c7b0e5 )
by
unknown
46:32 queued 36:48
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
	 * Whether the logged-in user can connect their WordPress.com account.
778
	 * With user-less connections in mind, we need to verify whether the current user
779
	 * can connect their account.
780
	 * Non-admin users can connect their account only if a connection owner exists.
781
	 *
782
	 * @access public
783
	 *
784
	 * @return boolean|WP_Error True if the current user is an administrator or a connected owner already exists, WP_Error if no current user exists.
785
	 */
786
	public function current_user_can_connect_account() {
787
		if ( 0 === get_current_user_id() ) {
788
			return new WP_Error( 'user_not_logged_in' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_not_logged_in'.

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

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

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

Loading history...
789
		}
790
791
		$roles = new Roles();
792
		$role  = $roles->translate_current_user_to_role();
793
794
		return 'administrator' === $role || $this->has_connected_owner();
795
	}
796
797
	/**
798
	 * Unlinks the current user from the linked WordPress.com user.
799
	 *
800
	 * @access public
801
	 * @static
802
	 *
803
	 * @todo Refactor to properly load the XMLRPC client independently.
804
	 *
805
	 * @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...
806
	 * @param bool    $can_overwrite_primary_user Allow for the primary user to be disconnected.
807
	 * @return Boolean Whether the disconnection of the user was successful.
808
	 */
809
	public static function disconnect_user( $user_id = null, $can_overwrite_primary_user = false ) {
810
		$tokens = Jetpack_Options::get_option( 'user_tokens' );
811
		if ( ! $tokens ) {
812
			return false;
813
		}
814
815
		$user_id = empty( $user_id ) ? get_current_user_id() : (int) $user_id;
816
817
		if ( Jetpack_Options::get_option( 'master_user' ) === $user_id && ! $can_overwrite_primary_user ) {
818
			return false;
819
		}
820
821
		if ( ! isset( $tokens[ $user_id ] ) ) {
822
			return false;
823
		}
824
825
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
826
		$xml->query( 'jetpack.unlink_user', $user_id );
827
828
		unset( $tokens[ $user_id ] );
829
830
		Jetpack_Options::update_option( 'user_tokens', $tokens );
831
832
		// Delete cached connected user data.
833
		$transient_key = "jetpack_connected_user_data_$user_id";
834
		delete_transient( $transient_key );
835
836
		/**
837
		 * Fires after the current user has been unlinked from WordPress.com.
838
		 *
839
		 * @since 4.1.0
840
		 *
841
		 * @param int $user_id The current user's ID.
842
		 */
843
		do_action( 'jetpack_unlinked_user', $user_id );
844
845
		return true;
846
	}
847
848
	/**
849
	 * Returns the requested Jetpack API URL.
850
	 *
851
	 * @param String $relative_url the relative API path.
852
	 * @return String API URL.
853
	 */
854
	public function api_url( $relative_url ) {
855
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
856
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
857
858
		/**
859
		 * Filters whether the connection manager should use the iframe authorization
860
		 * flow instead of the regular redirect-based flow.
861
		 *
862
		 * @since 8.3.0
863
		 *
864
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
865
		 */
866
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
867
868
		// Do not modify anything that is not related to authorize requests.
869
		if ( 'authorize' === $relative_url && $iframe_flow ) {
870
			$relative_url = 'authorize_iframe';
871
		}
872
873
		/**
874
		 * Filters the API URL that Jetpack uses for server communication.
875
		 *
876
		 * @since 8.0.0
877
		 *
878
		 * @param String $url the generated URL.
879
		 * @param String $relative_url the relative URL that was passed as an argument.
880
		 * @param String $api_base the API base string that is being used.
881
		 * @param String $api_version the API version string that is being used.
882
		 */
883
		return apply_filters(
884
			'jetpack_api_url',
885
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
886
			$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...
887
			$api_base,
888
			$api_version
889
		);
890
	}
891
892
	/**
893
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
894
	 *
895
	 * @return String XMLRPC API URL.
896
	 */
897
	public function xmlrpc_api_url() {
898
		$base = preg_replace(
899
			'#(https?://[^?/]+)(/?.*)?$#',
900
			'\\1',
901
			Constants::get_constant( 'JETPACK__API_BASE' )
902
		);
903
		return untrailingslashit( $base ) . '/xmlrpc.php';
904
	}
905
906
	/**
907
	 * Attempts Jetpack registration which sets up the site for connection. Should
908
	 * remain public because the call to action comes from the current site, not from
909
	 * WordPress.com.
910
	 *
911
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
912
	 * @return true|WP_Error The error object.
913
	 */
914
	public function register( $api_endpoint = 'register' ) {
915
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
916
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
917
918
		if ( false === $secrets ) {
919
			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...
920
		}
921
922
		if (
923
			empty( $secrets['secret_1'] ) ||
924
			empty( $secrets['secret_2'] ) ||
925
			empty( $secrets['exp'] )
926
		) {
927
			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...
928
		}
929
930
		// Better to try (and fail) to set a higher timeout than this system
931
		// supports than to have register fail for more users than it should.
932
		$timeout = $this->set_min_time_limit( 60 ) / 2;
933
934
		$gmt_offset = get_option( 'gmt_offset' );
935
		if ( ! $gmt_offset ) {
936
			$gmt_offset = 0;
937
		}
938
939
		$stats_options = get_option( 'stats_options' );
940
		$stats_id      = isset( $stats_options['blog_id'] )
941
			? $stats_options['blog_id']
942
			: null;
943
944
		/**
945
		 * Filters the request body for additional property addition.
946
		 *
947
		 * @since 7.7.0
948
		 *
949
		 * @param array $post_data request data.
950
		 * @param Array $token_data token data.
951
		 */
952
		$body = apply_filters(
953
			'jetpack_register_request_body',
954
			array(
955
				'siteurl'            => site_url(),
956
				'home'               => home_url(),
957
				'gmt_offset'         => $gmt_offset,
958
				'timezone_string'    => (string) get_option( 'timezone_string' ),
959
				'site_name'          => (string) get_option( 'blogname' ),
960
				'secret_1'           => $secrets['secret_1'],
961
				'secret_2'           => $secrets['secret_2'],
962
				'site_lang'          => get_locale(),
963
				'timeout'            => $timeout,
964
				'stats_id'           => $stats_id,
965
				'state'              => get_current_user_id(),
966
				'site_created'       => $this->get_assumed_site_creation_date(),
967
				'jetpack_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
968
				'ABSPATH'            => Constants::get_constant( 'ABSPATH' ),
969
				'current_user_email' => wp_get_current_user()->user_email,
970
				'connect_plugin'     => $this->get_plugin() ? $this->get_plugin()->get_slug() : null,
971
			)
972
		);
973
974
		$args = array(
975
			'method'  => 'POST',
976
			'body'    => $body,
977
			'headers' => array(
978
				'Accept' => 'application/json',
979
			),
980
			'timeout' => $timeout,
981
		);
982
983
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
984
985
		// TODO: fix URLs for bad hosts.
986
		$response = Client::_wp_remote_request(
987
			$this->api_url( $api_endpoint ),
988
			$args,
989
			true
990
		);
991
992
		// Make sure the response is valid and does not contain any Jetpack errors.
993
		$registration_details = $this->validate_remote_register_response( $response );
994
995
		if ( is_wp_error( $registration_details ) ) {
996
			return $registration_details;
997
		} elseif ( ! $registration_details ) {
998
			return new \WP_Error(
999
				'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...
1000
				'Unknown error registering your Jetpack site.',
1001
				wp_remote_retrieve_response_code( $response )
1002
			);
1003
		}
1004
1005
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
1006
			return new \WP_Error(
1007
				'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...
1008
				'Unable to validate registration of your Jetpack site.',
1009
				wp_remote_retrieve_response_code( $response )
1010
			);
1011
		}
1012
1013
		if ( isset( $registration_details->jetpack_public ) ) {
1014
			$jetpack_public = (int) $registration_details->jetpack_public;
1015
		} else {
1016
			$jetpack_public = false;
1017
		}
1018
1019
		\Jetpack_Options::update_options(
1020
			array(
1021
				'id'         => (int) $registration_details->jetpack_id,
1022
				'blog_token' => (string) $registration_details->jetpack_secret,
1023
				'public'     => $jetpack_public,
1024
			)
1025
		);
1026
1027
		/**
1028
		 * Fires when a site is registered on WordPress.com.
1029
		 *
1030
		 * @since 3.7.0
1031
		 *
1032
		 * @param int $json->jetpack_id Jetpack Blog ID.
1033
		 * @param string $json->jetpack_secret Jetpack Blog Token.
1034
		 * @param int|bool $jetpack_public Is the site public.
1035
		 */
1036
		do_action(
1037
			'jetpack_site_registered',
1038
			$registration_details->jetpack_id,
1039
			$registration_details->jetpack_secret,
1040
			$jetpack_public
1041
		);
1042
1043
		if ( isset( $registration_details->token ) ) {
1044
			/**
1045
			 * Fires when a user token is sent along with the registration data.
1046
			 *
1047
			 * @since 7.6.0
1048
			 *
1049
			 * @param object $token the administrator token for the newly registered site.
1050
			 */
1051
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
1052
		}
1053
1054
		return true;
1055
	}
1056
1057
	/**
1058
	 * Takes the response from the Jetpack register new site endpoint and
1059
	 * verifies it worked properly.
1060
	 *
1061
	 * @since 2.6
1062
	 *
1063
	 * @param Mixed $response the response object, or the error object.
1064
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
1065
	 **/
1066
	protected function validate_remote_register_response( $response ) {
1067
		if ( is_wp_error( $response ) ) {
1068
			return new \WP_Error(
1069
				'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...
1070
				$response->get_error_message()
1071
			);
1072
		}
1073
1074
		$code   = wp_remote_retrieve_response_code( $response );
1075
		$entity = wp_remote_retrieve_body( $response );
1076
1077
		if ( $entity ) {
1078
			$registration_response = json_decode( $entity );
1079
		} else {
1080
			$registration_response = false;
1081
		}
1082
1083
		$code_type = (int) ( $code / 100 );
1084
		if ( 5 === $code_type ) {
1085
			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...
1086
		} elseif ( 408 === $code ) {
1087
			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...
1088
		} elseif ( ! empty( $registration_response->error ) ) {
1089
			if (
1090
				'xml_rpc-32700' === $registration_response->error
1091
				&& ! function_exists( 'xml_parser_create' )
1092
			) {
1093
				$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' );
1094
			} else {
1095
				$error_description = isset( $registration_response->error_description )
1096
					? (string) $registration_response->error_description
1097
					: '';
1098
			}
1099
1100
			return new \WP_Error(
1101
				(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...
1102
				$error_description,
1103
				$code
1104
			);
1105
		} elseif ( 200 !== $code ) {
1106
			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...
1107
		}
1108
1109
		// Jetpack ID error block.
1110
		if ( empty( $registration_response->jetpack_id ) ) {
1111
			return new \WP_Error(
1112
				'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...
1113
				/* translators: %s is an error message string */
1114
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1115
				$entity
1116
			);
1117
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1118
			return new \WP_Error(
1119
				'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...
1120
				/* translators: %s is an error message string */
1121
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1122
				$entity
1123
			);
1124 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1125
			return new \WP_Error(
1126
				'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...
1127
				/* translators: %s is an error message string */
1128
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1129
				$entity
1130
			);
1131
		}
1132
1133
		return $registration_response;
1134
	}
1135
1136
	/**
1137
	 * Adds a used nonce to a list of known nonces.
1138
	 *
1139
	 * @param int    $timestamp the current request timestamp.
1140
	 * @param string $nonce the nonce value.
1141
	 * @return bool whether the nonce is unique or not.
1142
	 */
1143
	public function add_nonce( $timestamp, $nonce ) {
1144
		global $wpdb;
1145
		static $nonces_used_this_request = array();
1146
1147
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
1148
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
1149
		}
1150
1151
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
1152
		$timestamp = (int) $timestamp;
1153
		$nonce     = esc_sql( $nonce );
1154
1155
		// Raw query so we can avoid races: add_option will also update.
1156
		$show_errors = $wpdb->show_errors( false );
1157
1158
		$old_nonce = $wpdb->get_row(
1159
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1160
		);
1161
1162
		if ( is_null( $old_nonce ) ) {
1163
			$return = $wpdb->query(
1164
				$wpdb->prepare(
1165
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1166
					"jetpack_nonce_{$timestamp}_{$nonce}",
1167
					time(),
1168
					'no'
1169
				)
1170
			);
1171
		} else {
1172
			$return = false;
1173
		}
1174
1175
		$wpdb->show_errors( $show_errors );
1176
1177
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1178
1179
		return $return;
1180
	}
1181
1182
	/**
1183
	 * Cleans nonces that were saved when calling ::add_nonce.
1184
	 *
1185
	 * @todo Properly prepare the query before executing it.
1186
	 *
1187
	 * @param bool $all whether to clean even non-expired nonces.
1188
	 */
1189
	public function clean_nonces( $all = false ) {
1190
		global $wpdb;
1191
1192
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1193
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1194
1195
		if ( true !== $all ) {
1196
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1197
			$sql_args[] = time() - 3600;
1198
		}
1199
1200
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1201
1202
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1203
1204
		for ( $i = 0; $i < 1000; $i++ ) {
1205
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1206
				break;
1207
			}
1208
		}
1209
	}
1210
1211
	/**
1212
	 * Sets the Connection custom capabilities.
1213
	 *
1214
	 * @param string[] $caps    Array of the user's capabilities.
1215
	 * @param string   $cap     Capability name.
1216
	 * @param int      $user_id The user ID.
1217
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1218
	 */
1219
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1220
		$is_offline_mode = ( new Status() )->is_offline_mode();
1221
		switch ( $cap ) {
1222
			case 'jetpack_connect':
1223
			case 'jetpack_reconnect':
1224
				if ( $is_offline_mode ) {
1225
					$caps = array( 'do_not_allow' );
1226
					break;
1227
				}
1228
				// Pass through. If it's not offline mode, these should match disconnect.
1229
				// Let users disconnect if it's offline mode, just in case things glitch.
1230
			case 'jetpack_disconnect':
1231
				/**
1232
				 * Filters the jetpack_disconnect capability.
1233
				 *
1234
				 * @since 8.7.0
1235
				 *
1236
				 * @param array An array containing the capability name.
1237
				 */
1238
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1239
				break;
1240
			case 'jetpack_connect_user':
1241
				if ( $is_offline_mode ) {
1242
					$caps = array( 'do_not_allow' );
1243
					break;
1244
				}
1245
				$caps = array( 'read' );
1246
				break;
1247
		}
1248
		return $caps;
1249
	}
1250
1251
	/**
1252
	 * Builds the timeout limit for queries talking with the wpcom servers.
1253
	 *
1254
	 * Based on local php max_execution_time in php.ini
1255
	 *
1256
	 * @since 5.4
1257
	 * @return int
1258
	 **/
1259
	public function get_max_execution_time() {
1260
		$timeout = (int) ini_get( 'max_execution_time' );
1261
1262
		// Ensure exec time set in php.ini.
1263
		if ( ! $timeout ) {
1264
			$timeout = 30;
1265
		}
1266
		return $timeout;
1267
	}
1268
1269
	/**
1270
	 * Sets a minimum request timeout, and returns the current timeout
1271
	 *
1272
	 * @since 5.4
1273
	 * @param Integer $min_timeout the minimum timeout value.
1274
	 **/
1275 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1276
		$timeout = $this->get_max_execution_time();
1277
		if ( $timeout < $min_timeout ) {
1278
			$timeout = $min_timeout;
1279
			set_time_limit( $timeout );
1280
		}
1281
		return $timeout;
1282
	}
1283
1284
	/**
1285
	 * Get our assumed site creation date.
1286
	 * Calculated based on the earlier date of either:
1287
	 * - Earliest admin user registration date.
1288
	 * - Earliest date of post of any post type.
1289
	 *
1290
	 * @since 7.2.0
1291
	 *
1292
	 * @return string Assumed site creation date and time.
1293
	 */
1294
	public function get_assumed_site_creation_date() {
1295
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1296
		if ( ! empty( $cached_date ) ) {
1297
			return $cached_date;
1298
		}
1299
1300
		$earliest_registered_users  = get_users(
1301
			array(
1302
				'role'    => 'administrator',
1303
				'orderby' => 'user_registered',
1304
				'order'   => 'ASC',
1305
				'fields'  => array( 'user_registered' ),
1306
				'number'  => 1,
1307
			)
1308
		);
1309
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1310
1311
		$earliest_posts = get_posts(
1312
			array(
1313
				'posts_per_page' => 1,
1314
				'post_type'      => 'any',
1315
				'post_status'    => 'any',
1316
				'orderby'        => 'date',
1317
				'order'          => 'ASC',
1318
			)
1319
		);
1320
1321
		// If there are no posts at all, we'll count only on user registration date.
1322
		if ( $earliest_posts ) {
1323
			$earliest_post_date = $earliest_posts[0]->post_date;
1324
		} else {
1325
			$earliest_post_date = PHP_INT_MAX;
1326
		}
1327
1328
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1329
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1330
1331
		return $assumed_date;
1332
	}
1333
1334
	/**
1335
	 * Adds the activation source string as a parameter to passed arguments.
1336
	 *
1337
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1338
	 *
1339
	 * @param array $args arguments that need to have the source added.
1340
	 * @return array $amended arguments.
1341
	 */
1342 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1343
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1344
1345
		if ( $activation_source_name ) {
1346
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1347
			$args['_as'] = urlencode( $activation_source_name );
1348
		}
1349
1350
		if ( $activation_source_keyword ) {
1351
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1352
			$args['_ak'] = urlencode( $activation_source_keyword );
1353
		}
1354
1355
		return $args;
1356
	}
1357
1358
	/**
1359
	 * Returns the callable that would be used to generate secrets.
1360
	 *
1361
	 * @return Callable a function that returns a secure string to be used as a secret.
1362
	 */
1363
	protected function get_secret_callable() {
1364
		if ( ! isset( $this->secret_callable ) ) {
1365
			/**
1366
			 * Allows modification of the callable that is used to generate connection secrets.
1367
			 *
1368
			 * @param Callable a function or method that returns a secret string.
1369
			 */
1370
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', array( $this, 'secret_callable_method' ) );
1371
		}
1372
1373
		return $this->secret_callable;
1374
	}
1375
1376
	/**
1377
	 * Runs the wp_generate_password function with the required parameters. This is the
1378
	 * default implementation of the secret callable, can be overridden using the
1379
	 * jetpack_connection_secret_generator filter.
1380
	 *
1381
	 * @return String $secret value.
1382
	 */
1383
	private function secret_callable_method() {
1384
		return wp_generate_password( 32, false );
1385
	}
1386
1387
	/**
1388
	 * Generates two secret tokens and the end of life timestamp for them.
1389
	 *
1390
	 * @param String  $action  The action name.
1391
	 * @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...
1392
	 * @param Integer $exp     Expiration time in seconds.
1393
	 */
1394
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1395
		if ( false === $user_id ) {
1396
			$user_id = get_current_user_id();
1397
		}
1398
1399
		$callable = $this->get_secret_callable();
1400
1401
		$secrets = \Jetpack_Options::get_raw_option(
1402
			self::SECRETS_OPTION_NAME,
1403
			array()
1404
		);
1405
1406
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1407
1408
		if (
1409
			isset( $secrets[ $secret_name ] ) &&
1410
			$secrets[ $secret_name ]['exp'] > time()
1411
		) {
1412
			return $secrets[ $secret_name ];
1413
		}
1414
1415
		$secret_value = array(
1416
			'secret_1' => call_user_func( $callable ),
1417
			'secret_2' => call_user_func( $callable ),
1418
			'exp'      => time() + $exp,
1419
		);
1420
1421
		$secrets[ $secret_name ] = $secret_value;
1422
1423
		$res = Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1424
		return $res ? $secrets[ $secret_name ] : false;
1425
	}
1426
1427
	/**
1428
	 * Returns two secret tokens and the end of life timestamp for them.
1429
	 *
1430
	 * @param String  $action  The action name.
1431
	 * @param Integer $user_id The user identifier.
1432
	 * @return string|array an array of secrets or an error string.
1433
	 */
1434
	public function get_secrets( $action, $user_id ) {
1435
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1436
		$secrets     = \Jetpack_Options::get_raw_option(
1437
			self::SECRETS_OPTION_NAME,
1438
			array()
1439
		);
1440
1441
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1442
			return self::SECRETS_MISSING;
1443
		}
1444
1445
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1446
			$this->delete_secrets( $action, $user_id );
1447
			return self::SECRETS_EXPIRED;
1448
		}
1449
1450
		return $secrets[ $secret_name ];
1451
	}
1452
1453
	/**
1454
	 * Deletes secret tokens in case they, for example, have expired.
1455
	 *
1456
	 * @param String  $action  The action name.
1457
	 * @param Integer $user_id The user identifier.
1458
	 */
1459
	public function delete_secrets( $action, $user_id ) {
1460
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1461
		$secrets     = \Jetpack_Options::get_raw_option(
1462
			self::SECRETS_OPTION_NAME,
1463
			array()
1464
		);
1465
		if ( isset( $secrets[ $secret_name ] ) ) {
1466
			unset( $secrets[ $secret_name ] );
1467
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1468
		}
1469
	}
1470
1471
	/**
1472
	 * Deletes all connection tokens and transients from the local Jetpack site.
1473
	 * If the plugin object has been provided in the constructor, the function first checks
1474
	 * whether it's the only active connection.
1475
	 * If there are any other connections, the function will do nothing and return `false`
1476
	 * (unless `$ignore_connected_plugins` is set to `true`).
1477
	 *
1478
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1479
	 *
1480
	 * @return bool True if disconnected successfully, false otherwise.
1481
	 */
1482
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1483 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1484
			return false;
1485
		}
1486
1487
		/**
1488
		 * Fires upon the disconnect attempt.
1489
		 * Return `false` to prevent the disconnect.
1490
		 *
1491
		 * @since 8.7.0
1492
		 */
1493
		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...
1494
			return false;
1495
		}
1496
1497
		\Jetpack_Options::delete_option(
1498
			array(
1499
				'blog_token',
1500
				'user_token',
1501
				'user_tokens',
1502
				'master_user',
1503
				'time_diff',
1504
				'fallback_no_verify_ssl_certs',
1505
			)
1506
		);
1507
1508
		\Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
1509
1510
		// Delete cached connected user data.
1511
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1512
		delete_transient( $transient_key );
1513
1514
		// Delete all XML-RPC errors.
1515
		Error_Handler::get_instance()->delete_all_errors();
1516
1517
		return true;
1518
	}
1519
1520
	/**
1521
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1522
	 * If the plugin object has been provided in the constructor, the function first check
1523
	 * whether it's the only active connection.
1524
	 * If there are any other connections, the function will do nothing and return `false`
1525
	 * (unless `$ignore_connected_plugins` is set to `true`).
1526
	 *
1527
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1528
	 *
1529
	 * @return bool True if disconnected successfully, false otherwise.
1530
	 */
1531
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1532 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1533
			return false;
1534
		}
1535
1536
		/**
1537
		 * Fires upon the disconnect attempt.
1538
		 * Return `false` to prevent the disconnect.
1539
		 *
1540
		 * @since 8.7.0
1541
		 */
1542
		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...
1543
			return false;
1544
		}
1545
1546
		$xml = new \Jetpack_IXR_Client();
1547
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1548
1549
		return true;
1550
	}
1551
1552
	/**
1553
	 * Disconnect the plugin and remove the tokens.
1554
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1555
	 * This is a proxy method to simplify the Connection package API.
1556
	 *
1557
	 * @see Manager::disable_plugin()
1558
	 * @see Manager::disconnect_site_wpcom()
1559
	 * @see Manager::delete_all_connection_tokens()
1560
	 *
1561
	 * @return bool
1562
	 */
1563
	public function remove_connection() {
1564
		$this->disable_plugin();
1565
		$this->disconnect_site_wpcom();
1566
		$this->delete_all_connection_tokens();
1567
1568
		return true;
1569
	}
1570
1571
	/**
1572
	 * Completely clearing up the connection, and initiating reconnect.
1573
	 *
1574
	 * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
1575
	 */
1576
	public function reconnect() {
1577
		( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
1578
1579
		$this->disconnect_site_wpcom( true );
1580
		$this->delete_all_connection_tokens( true );
1581
1582
		return $this->register();
1583
	}
1584
1585
	/**
1586
	 * Validate the tokens, and refresh the invalid ones.
1587
	 *
1588
	 * @return string|true|WP_Error True if connection restored or string indicating what's to be done next. A `WP_Error` object otherwise.
1589
	 */
1590
	public function restore() {
1591
		$invalid_tokens = array();
1592
		$can_restore    = $this->can_restore( $invalid_tokens );
1593
1594
		// Tokens are valid. We can't fix the problem we don't see, so the full reconnection is needed.
1595
		if ( ! $can_restore ) {
1596
			$result = $this->reconnect();
1597
			return true === $result ? 'authorize' : $result;
1598
		}
1599
1600
		if ( in_array( 'blog', $invalid_tokens, true ) ) {
1601
			return self::refresh_blog_token();
1602
		}
1603
1604
		if ( in_array( 'user', $invalid_tokens, true ) ) {
1605
			return true === self::refresh_user_token() ? 'authorize' : false;
1606
		}
1607
1608
		return false;
1609
	}
1610
1611
	/**
1612
	 * Determine whether we can restore the connection, or the full reconnect is needed.
1613
	 *
1614
	 * @param array $invalid_tokens The array the invalid tokens are stored in, provided by reference.
1615
	 *
1616
	 * @return bool `True` if the connection can be restored, `false` otherwise.
1617
	 */
1618
	public function can_restore( &$invalid_tokens ) {
1619
		$invalid_tokens = array();
1620
1621
		$validated_tokens = $this->validate_tokens();
1622
1623
		if ( ! is_array( $validated_tokens ) || count( array_diff_key( array_flip( array( 'blog_token', 'user_token' ) ), $validated_tokens ) ) ) {
1624
			return false;
1625
		}
1626
1627
		if ( empty( $validated_tokens['blog_token']['is_healthy'] ) ) {
1628
			$invalid_tokens[] = 'blog';
1629
		}
1630
1631
		if ( empty( $validated_tokens['user_token']['is_healthy'] ) ) {
1632
			$invalid_tokens[] = 'user';
1633
		}
1634
1635
		// If both tokens are invalid, we can't restore the connection.
1636
		return 1 === count( $invalid_tokens );
1637
	}
1638
1639
	/**
1640
	 * Perform the API request to validate the blog and user tokens.
1641
	 *
1642
	 * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
1643
	 *
1644
	 * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
1645
	 */
1646
	public function validate_tokens( $user_id = null ) {
1647
		$blog_id = Jetpack_Options::get_option( 'id' );
1648
		if ( ! $blog_id ) {
1649
			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...
1650
		}
1651
		$url = sprintf(
1652
			'%s/%s/v%s/%s',
1653
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
1654
			'wpcom',
1655
			'2',
1656
			'sites/' . $blog_id . '/jetpack-token-health'
1657
		);
1658
1659
		$user_token = $this->get_access_token( $user_id ? $user_id : get_current_user_id() );
1660
		$blog_token = $this->get_access_token();
1661
		$method     = 'POST';
1662
		$body       = array(
1663
			'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 1659 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...
1664
			'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 1660 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...
1665
		);
1666
		$response   = Client::_wp_remote_request( $url, compact( 'body', 'method' ) );
1667
1668
		if ( is_wp_error( $response ) || ! wp_remote_retrieve_body( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
1669
			return false;
1670
		}
1671
1672
		$body = json_decode( wp_remote_retrieve_body( $response ), true );
1673
1674
		return $body ? $body : false;
1675
	}
1676
1677
	/**
1678
	 * Responds to a WordPress.com call to register the current site.
1679
	 * Should be changed to protected.
1680
	 *
1681
	 * @param array $registration_data Array of [ secret_1, user_id ].
1682
	 */
1683
	public function handle_registration( array $registration_data ) {
1684
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1685
		if ( empty( $registration_user_id ) ) {
1686
			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...
1687
		}
1688
1689
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1690
	}
1691
1692
	/**
1693
	 * Verify a Previously Generated Secret.
1694
	 *
1695
	 * @param string $action   The type of secret to verify.
1696
	 * @param string $secret_1 The secret string to compare to what is stored.
1697
	 * @param int    $user_id  The user ID of the owner of the secret.
1698
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1699
	 */
1700
	public function verify_secrets( $action, $secret_1, $user_id ) {
1701
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1702
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1703
			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...
1704
		}
1705
1706
		$user = get_user_by( 'id', $user_id );
1707
1708
		/**
1709
		 * We've begun verifying the previously generated secret.
1710
		 *
1711
		 * @since 7.5.0
1712
		 *
1713
		 * @param string   $action The type of secret to verify.
1714
		 * @param \WP_User $user The user object.
1715
		 */
1716
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1717
1718
		$return_error = function ( \WP_Error $error ) use ( $action, $user ) {
1719
			/**
1720
			 * Verifying of the previously generated secret has failed.
1721
			 *
1722
			 * @since 7.5.0
1723
			 *
1724
			 * @param string    $action  The type of secret to verify.
1725
			 * @param \WP_User  $user The user object.
1726
			 * @param \WP_Error $error The error object.
1727
			 */
1728
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1729
1730
			return $error;
1731
		};
1732
1733
		$stored_secrets = $this->get_secrets( $action, $user_id );
1734
		$this->delete_secrets( $action, $user_id );
1735
1736
		$error = null;
1737
		if ( empty( $secret_1 ) ) {
1738
			$error = $return_error(
1739
				new \WP_Error(
1740
					'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...
1741
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1742
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1743
					400
1744
				)
1745
			);
1746
		} elseif ( ! is_string( $secret_1 ) ) {
1747
			$error = $return_error(
1748
				new \WP_Error(
1749
					'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...
1750
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1751
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1752
					400
1753
				)
1754
			);
1755
		} elseif ( empty( $user_id ) ) {
1756
			// $user_id is passed around during registration as "state".
1757
			$error = $return_error(
1758
				new \WP_Error(
1759
					'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...
1760
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1761
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1762
					400
1763
				)
1764
			);
1765
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1766
			$error = $return_error(
1767
				new \WP_Error(
1768
					'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...
1769
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1770
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1771
					400
1772
				)
1773
			);
1774
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1775
			$error = $return_error(
1776
				new \WP_Error(
1777
					'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...
1778
					__( 'Verification secrets not found', 'jetpack' ),
1779
					400
1780
				)
1781
			);
1782
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1783
			$error = $return_error(
1784
				new \WP_Error(
1785
					'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...
1786
					__( 'Verification took too long', 'jetpack' ),
1787
					400
1788
				)
1789
			);
1790
		} elseif ( ! $stored_secrets ) {
1791
			$error = $return_error(
1792
				new \WP_Error(
1793
					'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...
1794
					__( 'Verification secrets are empty', 'jetpack' ),
1795
					400
1796
				)
1797
			);
1798
		} elseif ( is_wp_error( $stored_secrets ) ) {
1799
			$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...
1800
			$error = $return_error( $stored_secrets );
1801
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1802
			$error = $return_error(
1803
				new \WP_Error(
1804
					'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...
1805
					__( 'Verification secrets are incomplete', 'jetpack' ),
1806
					400
1807
				)
1808
			);
1809
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1810
			$error = $return_error(
1811
				new \WP_Error(
1812
					'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...
1813
					__( 'Secret mismatch', 'jetpack' ),
1814
					400
1815
				)
1816
			);
1817
		}
1818
1819
		// Something went wrong during the checks, returning the error.
1820
		if ( ! empty( $error ) ) {
1821
			return $error;
1822
		}
1823
1824
		/**
1825
		 * We've succeeded at verifying the previously generated secret.
1826
		 *
1827
		 * @since 7.5.0
1828
		 *
1829
		 * @param string   $action The type of secret to verify.
1830
		 * @param \WP_User $user The user object.
1831
		 */
1832
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1833
1834
		return $stored_secrets['secret_2'];
1835
	}
1836
1837
	/**
1838
	 * Responds to a WordPress.com call to authorize the current user.
1839
	 * Should be changed to protected.
1840
	 */
1841
	public function handle_authorization() {
1842
1843
	}
1844
1845
	/**
1846
	 * Obtains the auth token.
1847
	 *
1848
	 * @param array $data The request data.
1849
	 * @return object|\WP_Error Returns the auth token on success.
1850
	 *                          Returns a \WP_Error on failure.
1851
	 */
1852
	public function get_token( $data ) {
1853
		$roles = new Roles();
1854
		$role  = $roles->translate_current_user_to_role();
1855
1856
		if ( ! $role ) {
1857
			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...
1858
		}
1859
1860
		$client_secret = $this->get_access_token();
1861
		if ( ! $client_secret ) {
1862
			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...
1863
		}
1864
1865
		/**
1866
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1867
		 * data processing.
1868
		 *
1869
		 * @since 8.0.0
1870
		 *
1871
		 * @param string $redirect_url Defaults to the site admin URL.
1872
		 */
1873
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1874
1875
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1876
1877
		/**
1878
		* Filter the URL to redirect the user back to when the authentication process
1879
		* is complete.
1880
		*
1881
		* @since 8.0.0
1882
		*
1883
		* @param string $redirect_url Defaults to the site URL.
1884
		*/
1885
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1886
1887
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1888
			? $data['redirect_uri']
1889
			: add_query_arg(
1890
				array(
1891
					'handler'  => 'jetpack-connection-webhooks',
1892
					'action'   => 'authorize',
1893
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1894
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1895
				),
1896
				esc_url( $processing_url )
1897
			);
1898
1899
		/**
1900
		 * Filters the token request data.
1901
		 *
1902
		 * @since 8.0.0
1903
		 *
1904
		 * @param array $request_data request data.
1905
		 */
1906
		$body = apply_filters(
1907
			'jetpack_token_request_body',
1908
			array(
1909
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1910
				'client_secret' => $client_secret->secret,
1911
				'grant_type'    => 'authorization_code',
1912
				'code'          => $data['code'],
1913
				'redirect_uri'  => $redirect_uri,
1914
			)
1915
		);
1916
1917
		$args = array(
1918
			'method'  => 'POST',
1919
			'body'    => $body,
1920
			'headers' => array(
1921
				'Accept' => 'application/json',
1922
			),
1923
		);
1924
		add_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1925
		$response = Client::_wp_remote_request( $this->api_url( 'token' ), $args );
1926
		remove_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1927
1928
		if ( is_wp_error( $response ) ) {
1929
			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...
1930
		}
1931
1932
		$code   = wp_remote_retrieve_response_code( $response );
1933
		$entity = wp_remote_retrieve_body( $response );
1934
1935
		if ( $entity ) {
1936
			$json = json_decode( $entity );
1937
		} else {
1938
			$json = false;
1939
		}
1940
1941 View Code Duplication
		if ( 200 !== $code || ! empty( $json->error ) ) {
1942
			if ( empty( $json->error ) ) {
1943
				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...
1944
			}
1945
1946
			/* translators: Error description string. */
1947
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1948
1949
			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...
1950
		}
1951
1952
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1953
			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...
1954
		}
1955
1956
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1957
			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...
1958
		}
1959
1960
		if ( empty( $json->scope ) ) {
1961
			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...
1962
		}
1963
1964
		// TODO: get rid of the error silencer.
1965
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1966
		@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...
1967
		if ( empty( $role ) || empty( $hmac ) ) {
1968
			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...
1969
		}
1970
1971
		if ( $this->sign_role( $role ) !== $json->scope ) {
1972
			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...
1973
		}
1974
1975
		$cap = $roles->translate_role_to_cap( $role );
1976
		if ( ! $cap ) {
1977
			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...
1978
		}
1979
1980
		if ( ! current_user_can( $cap ) ) {
1981
			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...
1982
		}
1983
1984
		return (string) $json->access_token;
1985
	}
1986
1987
	/**
1988
	 * Increases the request timeout value to 30 seconds.
1989
	 *
1990
	 * @return int Returns 30.
1991
	 */
1992
	public function increase_timeout() {
1993
		return 30;
1994
	}
1995
1996
	/**
1997
	 * Builds a URL to the Jetpack connection auth page.
1998
	 *
1999
	 * @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...
2000
	 * @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...
2001
	 * @return string Connect URL.
2002
	 */
2003
	public function get_authorization_url( $user = null, $redirect = null ) {
2004
2005
		if ( empty( $user ) ) {
2006
			$user = wp_get_current_user();
2007
		}
2008
2009
		$roles       = new Roles();
2010
		$role        = $roles->translate_user_to_role( $user );
2011
		$signed_role = $this->sign_role( $role );
2012
2013
		/**
2014
		 * Filter the URL of the first time the user gets redirected back to your site for connection
2015
		 * data processing.
2016
		 *
2017
		 * @since 8.0.0
2018
		 *
2019
		 * @param string $redirect_url Defaults to the site admin URL.
2020
		 */
2021
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
2022
2023
		/**
2024
		 * Filter the URL to redirect the user back to when the authorization process
2025
		 * is complete.
2026
		 *
2027
		 * @since 8.0.0
2028
		 *
2029
		 * @param string $redirect_url Defaults to the site URL.
2030
		 */
2031
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
2032
2033
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
2034
2035
		/**
2036
		 * Filter the type of authorization.
2037
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
2038
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
2039
		 *
2040
		 * @since 4.3.3
2041
		 *
2042
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
2043
		 */
2044
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
2045
2046
		/**
2047
		 * Filters the user connection request data for additional property addition.
2048
		 *
2049
		 * @since 8.0.0
2050
		 *
2051
		 * @param array $request_data request data.
2052
		 */
2053
		$body = apply_filters(
2054
			'jetpack_connect_request_body',
2055
			array(
2056
				'response_type' => 'code',
2057
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
2058
				'redirect_uri'  => add_query_arg(
2059
					array(
2060
						'handler'  => 'jetpack-connection-webhooks',
2061
						'action'   => 'authorize',
2062
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
2063
						'redirect' => $redirect ? rawurlencode( $redirect ) : false,
2064
					),
2065
					esc_url( $processing_url )
2066
				),
2067
				'state'         => $user->ID,
2068
				'scope'         => $signed_role,
2069
				'user_email'    => $user->user_email,
2070
				'user_login'    => $user->user_login,
2071
				'is_active'     => $this->is_active(),
2072
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
2073
				'auth_type'     => $auth_type,
2074
				'secret'        => $secrets['secret_1'],
2075
				'blogname'      => get_option( 'blogname' ),
2076
				'site_url'      => site_url(),
2077
				'home_url'      => home_url(),
2078
				'site_icon'     => get_site_icon_url(),
2079
				'site_lang'     => get_locale(),
2080
				'site_created'  => $this->get_assumed_site_creation_date(),
2081
			)
2082
		);
2083
2084
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
2085
2086
		$api_url = $this->api_url( 'authorize' );
2087
2088
		return add_query_arg( $body, $api_url );
2089
	}
2090
2091
	/**
2092
	 * Authorizes the user by obtaining and storing the user token.
2093
	 *
2094
	 * @param array $data The request data.
2095
	 * @return string|\WP_Error Returns a string on success.
2096
	 *                          Returns a \WP_Error on failure.
2097
	 */
2098
	public function authorize( $data = array() ) {
2099
		/**
2100
		 * Action fired when user authorization starts.
2101
		 *
2102
		 * @since 8.0.0
2103
		 */
2104
		do_action( 'jetpack_authorize_starting' );
2105
2106
		$roles = new Roles();
2107
		$role  = $roles->translate_current_user_to_role();
2108
2109
		if ( ! $role ) {
2110
			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...
2111
		}
2112
2113
		$cap = $roles->translate_role_to_cap( $role );
2114
		if ( ! $cap ) {
2115
			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...
2116
		}
2117
2118
		if ( ! empty( $data['error'] ) ) {
2119
			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...
2120
		}
2121
2122
		if ( ! isset( $data['state'] ) ) {
2123
			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...
2124
		}
2125
2126
		if ( ! ctype_digit( $data['state'] ) ) {
2127
			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...
2128
		}
2129
2130
		$current_user_id = get_current_user_id();
2131
		if ( $current_user_id !== (int) $data['state'] ) {
2132
			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...
2133
		}
2134
2135
		if ( empty( $data['code'] ) ) {
2136
			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...
2137
		}
2138
2139
		$token = $this->get_token( $data );
2140
2141 View Code Duplication
		if ( is_wp_error( $token ) ) {
2142
			$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...
2143
			if ( empty( $code ) ) {
2144
				$code = 'invalid_token';
2145
			}
2146
			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...
2147
		}
2148
2149
		if ( ! $token ) {
2150
			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...
2151
		}
2152
2153
		$is_connection_owner = ! $this->has_connected_owner();
2154
2155
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_connection_owner );
2156
2157
		/**
2158
		 * Fires after user has successfully received an auth token.
2159
		 *
2160
		 * @since 3.9.0
2161
		 */
2162
		do_action( 'jetpack_user_authorized' );
2163
2164
		if ( ! $is_connection_owner ) {
2165
			/**
2166
			 * Action fired when a secondary user has been authorized.
2167
			 *
2168
			 * @since 8.0.0
2169
			 */
2170
			do_action( 'jetpack_authorize_ending_linked' );
2171
			return 'linked';
2172
		}
2173
2174
		/**
2175
		 * Action fired when the master user has been authorized.
2176
		 *
2177
		 * @since 8.0.0
2178
		 *
2179
		 * @param array $data The request data.
2180
		 */
2181
		do_action( 'jetpack_authorize_ending_authorized', $data );
2182
2183
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
2184
2185
		// Start nonce cleaner.
2186
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2187
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
2188
2189
		return 'authorized';
2190
	}
2191
2192
	/**
2193
	 * Disconnects from the Jetpack servers.
2194
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2195
	 */
2196
	public function disconnect_site() {
2197
2198
	}
2199
2200
	/**
2201
	 * The Base64 Encoding of the SHA1 Hash of the Input.
2202
	 *
2203
	 * @param string $text The string to hash.
2204
	 * @return string
2205
	 */
2206
	public function sha1_base64( $text ) {
2207
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2208
	}
2209
2210
	/**
2211
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
2212
	 *
2213
	 * @param string $domain The domain to check.
2214
	 *
2215
	 * @return bool|WP_Error
2216
	 */
2217
	public function is_usable_domain( $domain ) {
2218
2219
		// If it's empty, just fail out.
2220
		if ( ! $domain ) {
2221
			return new \WP_Error(
2222
				'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...
2223
				/* translators: %1$s is a domain name. */
2224
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
2225
			);
2226
		}
2227
2228
		/**
2229
		 * Skips the usuable domain check when connecting a site.
2230
		 *
2231
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
2232
		 *
2233
		 * @since 4.1.0
2234
		 *
2235
		 * @param bool If the check should be skipped. Default false.
2236
		 */
2237
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
2238
			return true;
2239
		}
2240
2241
		// None of the explicit localhosts.
2242
		$forbidden_domains = array(
2243
			'wordpress.com',
2244
			'localhost',
2245
			'localhost.localdomain',
2246
			'127.0.0.1',
2247
			'local.wordpress.test',         // VVV pattern.
2248
			'local.wordpress-trunk.test',   // VVV pattern.
2249
			'src.wordpress-develop.test',   // VVV pattern.
2250
			'build.wordpress-develop.test', // VVV pattern.
2251
		);
2252 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
2253
			return new \WP_Error(
2254
				'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...
2255
				sprintf(
2256
					/* translators: %1$s is a domain name. */
2257
					__(
2258
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
2259
						'jetpack'
2260
					),
2261
					$domain
2262
				)
2263
			);
2264
		}
2265
2266
		// No .test or .local domains.
2267 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
2268
			return new \WP_Error(
2269
				'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...
2270
				sprintf(
2271
					/* translators: %1$s is a domain name. */
2272
					__(
2273
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
2274
						'jetpack'
2275
					),
2276
					$domain
2277
				)
2278
			);
2279
		}
2280
2281
		// No WPCOM subdomains.
2282 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
2283
			return new \WP_Error(
2284
				'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...
2285
				sprintf(
2286
					/* translators: %1$s is a domain name. */
2287
					__(
2288
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
2289
						'jetpack'
2290
					),
2291
					$domain
2292
				)
2293
			);
2294
		}
2295
2296
		// If PHP was compiled without support for the Filter module (very edge case).
2297
		if ( ! function_exists( 'filter_var' ) ) {
2298
			// Just pass back true for now, and let wpcom sort it out.
2299
			return true;
2300
		}
2301
2302
		return true;
2303
	}
2304
2305
	/**
2306
	 * Gets the requested token.
2307
	 *
2308
	 * Tokens are one of two types:
2309
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
2310
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
2311
	 *    are not associated with a user account. They represent the site's connection with
2312
	 *    the Jetpack servers.
2313
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
2314
	 *
2315
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
2316
	 * token, and $private is a secret that should never be displayed anywhere or sent
2317
	 * over the network; it's used only for signing things.
2318
	 *
2319
	 * Blog Tokens can be "Normal" or "Special".
2320
	 * * Normal: The result of a normal connection flow. They look like
2321
	 *   "{$random_string_1}.{$random_string_2}"
2322
	 *   That is, $token_key and $private are both random strings.
2323
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
2324
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
2325
	 *   constant (rare).
2326
	 * * Special: A connection token for sites that have gone through an alternative
2327
	 *   connection flow. They look like:
2328
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
2329
	 *   That is, $private is a random string and $token_key has a special structure with
2330
	 *   lots of semicolons.
2331
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
2332
	 *   JETPACK_BLOG_TOKEN constant.
2333
	 *
2334
	 * In particular, note that Normal Blog Tokens never start with ";" and that
2335
	 * Special Blog Tokens always do.
2336
	 *
2337
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
2338
	 * order:
2339
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
2340
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
2341
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
2342
	 *
2343
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
2344
	 * @param string|false $token_key If provided, check that the token matches the provided input.
2345
	 * @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.
2346
	 *
2347
	 * @return object|false
2348
	 */
2349
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
2350
		$possible_special_tokens = array();
2351
		$possible_normal_tokens  = array();
2352
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
2353
2354
		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...
2355
			if ( ! $user_tokens ) {
2356
				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...
2357
			}
2358
			if ( self::CONNECTION_OWNER === $user_id ) {
2359
				$user_id = \Jetpack_Options::get_option( 'master_user' );
2360
				if ( ! $user_id ) {
2361
					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...
2362
				}
2363
			}
2364
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
2365
				// translators: %s is the user ID.
2366
				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...
2367
			}
2368
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
2369 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
2370
				// translators: %s is the user ID.
2371
				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...
2372
			}
2373
			if ( $user_token_chunks[2] !== (string) $user_id ) {
2374
				// translators: %1$d is the ID of the requested user. %2$d is the user ID found in the token.
2375
				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...
2376
			}
2377
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
2378
		} else {
2379
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
2380
			if ( $stored_blog_token ) {
2381
				$possible_normal_tokens[] = $stored_blog_token;
2382
			}
2383
2384
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
2385
2386
			if ( $defined_tokens_string ) {
2387
				$defined_tokens = explode( ',', $defined_tokens_string );
2388
				foreach ( $defined_tokens as $defined_token ) {
2389
					if ( ';' === $defined_token[0] ) {
2390
						$possible_special_tokens[] = $defined_token;
2391
					} else {
2392
						$possible_normal_tokens[] = $defined_token;
2393
					}
2394
				}
2395
			}
2396
		}
2397
2398
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2399
			$possible_tokens = $possible_normal_tokens;
2400
		} else {
2401
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
2402
		}
2403
2404
		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...
2405
			// If no user tokens were found, it would have failed earlier, so this is about blog token.
2406
			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...
2407
		}
2408
2409
		$valid_token = false;
2410
2411
		if ( false === $token_key ) {
2412
			// Use first token.
2413
			$valid_token = $possible_tokens[0];
2414
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2415
			// Use first normal token.
2416
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
2417
		} else {
2418
			// Use the token matching $token_key or false if none.
2419
			// Ensure we check the full key.
2420
			$token_check = rtrim( $token_key, '.' ) . '.';
2421
2422
			foreach ( $possible_tokens as $possible_token ) {
2423
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
2424
					$valid_token = $possible_token;
2425
					break;
2426
				}
2427
			}
2428
		}
2429
2430
		if ( ! $valid_token ) {
2431
			if ( $user_id ) {
2432
				// translators: %d is the user ID.
2433
				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...
2434
			} else {
2435
				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...
2436
			}
2437
		}
2438
2439
		return (object) array(
2440
			'secret'           => $valid_token,
2441
			'external_user_id' => (int) $user_id,
2442
		);
2443
	}
2444
2445
	/**
2446
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2447
	 * since it is passed by reference to various methods.
2448
	 * Capture it here so we can verify the signature later.
2449
	 *
2450
	 * @param array $methods an array of available XMLRPC methods.
2451
	 * @return array the same array, since this method doesn't add or remove anything.
2452
	 */
2453
	public function xmlrpc_methods( $methods ) {
2454
		$this->raw_post_data = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
2455
		return $methods;
2456
	}
2457
2458
	/**
2459
	 * Resets the raw post data parameter for testing purposes.
2460
	 */
2461
	public function reset_raw_post_data() {
2462
		$this->raw_post_data = null;
2463
	}
2464
2465
	/**
2466
	 * Registering an additional method.
2467
	 *
2468
	 * @param array $methods an array of available XMLRPC methods.
2469
	 * @return array the amended array in case the method is added.
2470
	 */
2471
	public function public_xmlrpc_methods( $methods ) {
2472
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2473
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2474
		}
2475
		return $methods;
2476
	}
2477
2478
	/**
2479
	 * Handles a getOptions XMLRPC method call.
2480
	 *
2481
	 * @param array $args method call arguments.
2482
	 * @return an amended XMLRPC server options array.
2483
	 */
2484
	public function jetpack_get_options( $args ) {
2485
		global $wp_xmlrpc_server;
2486
2487
		$wp_xmlrpc_server->escape( $args );
2488
2489
		$username = $args[1];
2490
		$password = $args[2];
2491
2492
		$user = $wp_xmlrpc_server->login( $username, $password );
2493
		if ( ! $user ) {
2494
			return $wp_xmlrpc_server->error;
2495
		}
2496
2497
		$options   = array();
2498
		$user_data = $this->get_connected_user_data();
2499
		if ( is_array( $user_data ) ) {
2500
			$options['jetpack_user_id']         = array(
2501
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2502
				'readonly' => true,
2503
				'value'    => $user_data['ID'],
2504
			);
2505
			$options['jetpack_user_login']      = array(
2506
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2507
				'readonly' => true,
2508
				'value'    => $user_data['login'],
2509
			);
2510
			$options['jetpack_user_email']      = array(
2511
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2512
				'readonly' => true,
2513
				'value'    => $user_data['email'],
2514
			);
2515
			$options['jetpack_user_site_count'] = array(
2516
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2517
				'readonly' => true,
2518
				'value'    => $user_data['site_count'],
2519
			);
2520
		}
2521
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2522
		$args                           = stripslashes_deep( $args );
2523
		return $wp_xmlrpc_server->wp_getOptions( $args );
2524
	}
2525
2526
	/**
2527
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2528
	 *
2529
	 * @param array $options standard Core options.
2530
	 * @return array amended options.
2531
	 */
2532
	public function xmlrpc_options( $options ) {
2533
		$jetpack_client_id = false;
2534
		if ( $this->is_active() ) {
2535
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2536
		}
2537
		$options['jetpack_version'] = array(
2538
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2539
			'readonly' => true,
2540
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2541
		);
2542
2543
		$options['jetpack_client_id'] = array(
2544
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2545
			'readonly' => true,
2546
			'value'    => $jetpack_client_id,
2547
		);
2548
		return $options;
2549
	}
2550
2551
	/**
2552
	 * Resets the saved authentication state in between testing requests.
2553
	 */
2554
	public function reset_saved_auth_state() {
2555
		$this->xmlrpc_verification = null;
2556
	}
2557
2558
	/**
2559
	 * Sign a user role with the master access token.
2560
	 * If not specified, will default to the current user.
2561
	 *
2562
	 * @access public
2563
	 *
2564
	 * @param string $role    User role.
2565
	 * @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...
2566
	 * @return string Signed user role.
2567
	 */
2568
	public function sign_role( $role, $user_id = null ) {
2569
		if ( empty( $user_id ) ) {
2570
			$user_id = (int) get_current_user_id();
2571
		}
2572
2573
		if ( ! $user_id ) {
2574
			return false;
2575
		}
2576
2577
		$token = $this->get_access_token();
2578
		if ( ! $token || is_wp_error( $token ) ) {
2579
			return false;
2580
		}
2581
2582
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2583
	}
2584
2585
	/**
2586
	 * Set the plugin instance.
2587
	 *
2588
	 * @param Plugin $plugin_instance The plugin instance.
2589
	 *
2590
	 * @return $this
2591
	 */
2592
	public function set_plugin_instance( Plugin $plugin_instance ) {
2593
		$this->plugin = $plugin_instance;
2594
2595
		return $this;
2596
	}
2597
2598
	/**
2599
	 * Retrieve the plugin management object.
2600
	 *
2601
	 * @return Plugin
2602
	 */
2603
	public function get_plugin() {
2604
		return $this->plugin;
2605
	}
2606
2607
	/**
2608
	 * Get all connected plugins information, excluding those disconnected by user.
2609
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2610
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2611
	 * so please make sure not to run the method too early in the code.
2612
	 *
2613
	 * @return array|WP_Error
2614
	 */
2615
	public function get_connected_plugins() {
2616
		$maybe_plugins = Plugin_Storage::get_all( true );
2617
2618
		if ( $maybe_plugins instanceof WP_Error ) {
2619
			return $maybe_plugins;
2620
		}
2621
2622
		return $maybe_plugins;
2623
	}
2624
2625
	/**
2626
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2627
	 * Note: this method does not remove any access tokens.
2628
	 *
2629
	 * @return bool
2630
	 */
2631
	public function disable_plugin() {
2632
		if ( ! $this->plugin ) {
2633
			return false;
2634
		}
2635
2636
		return $this->plugin->disable();
2637
	}
2638
2639
	/**
2640
	 * Force plugin reconnect after user-initiated disconnect.
2641
	 * After its called, the plugin will be allowed to use the connection again.
2642
	 * Note: this method does not initialize access tokens.
2643
	 *
2644
	 * @return bool
2645
	 */
2646
	public function enable_plugin() {
2647
		if ( ! $this->plugin ) {
2648
			return false;
2649
		}
2650
2651
		return $this->plugin->enable();
2652
	}
2653
2654
	/**
2655
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2656
	 * If no plugin slug was passed into the constructor, always returns true.
2657
	 *
2658
	 * @return bool
2659
	 */
2660
	public function is_plugin_enabled() {
2661
		if ( ! $this->plugin ) {
2662
			return true;
2663
		}
2664
2665
		return $this->plugin->is_enabled();
2666
	}
2667
2668
	/**
2669
	 * Perform the API request to refresh the blog token.
2670
	 * Note that we are making this request on behalf of the Jetpack master user,
2671
	 * given they were (most probably) the ones that registered the site at the first place.
2672
	 *
2673
	 * @return WP_Error|bool The result of updating the blog_token option.
2674
	 */
2675
	public static function refresh_blog_token() {
2676
		( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
2677
2678
		$blog_id = Jetpack_Options::get_option( 'id' );
2679
		if ( ! $blog_id ) {
2680
			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...
2681
		}
2682
2683
		$url     = sprintf(
2684
			'%s/%s/v%s/%s',
2685
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
2686
			'wpcom',
2687
			'2',
2688
			'sites/' . $blog_id . '/jetpack-refresh-blog-token'
2689
		);
2690
		$method  = 'POST';
2691
		$user_id = get_current_user_id();
2692
2693
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2694
2695
		if ( is_wp_error( $response ) ) {
2696
			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...
2697
		}
2698
2699
		$code   = wp_remote_retrieve_response_code( $response );
2700
		$entity = wp_remote_retrieve_body( $response );
2701
2702
		if ( $entity ) {
2703
			$json = json_decode( $entity );
2704
		} else {
2705
			$json = false;
2706
		}
2707
2708 View Code Duplication
		if ( 200 !== $code ) {
2709
			if ( empty( $json->code ) ) {
2710
				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...
2711
			}
2712
2713
			/* translators: Error description string. */
2714
			$error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->message ) : '';
2715
2716
			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...
2717
		}
2718
2719
		if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
2720
			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...
2721
		}
2722
2723
		return Jetpack_Options::update_option( 'blog_token', (string) $json->jetpack_secret );
2724
	}
2725
2726
	/**
2727
	 * Disconnect the user from WP.com, and initiate the reconnect process.
2728
	 *
2729
	 * @return bool
2730
	 */
2731
	public static function refresh_user_token() {
2732
		( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2733
2734
		self::disconnect_user( null, true );
2735
2736
		return true;
2737
	}
2738
2739
	/**
2740
	 * Fetches a signed token.
2741
	 *
2742
	 * @param object $token the token.
2743
	 * @return WP_Error|string a signed token
2744
	 */
2745
	public function get_signed_token( $token ) {
2746
		if ( ! isset( $token->secret ) || empty( $token->secret ) ) {
2747
			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...
2748
		}
2749
2750
		list( $token_key, $token_secret ) = explode( '.', $token->secret );
2751
2752
		$token_key = sprintf(
2753
			'%s:%d:%d',
2754
			$token_key,
2755
			Constants::get_constant( 'JETPACK__API_VERSION' ),
2756
			$token->external_user_id
2757
		);
2758
2759
		$timestamp = time();
2760
2761 View Code Duplication
		if ( function_exists( 'wp_generate_password' ) ) {
2762
			$nonce = wp_generate_password( 10, false );
2763
		} else {
2764
			$nonce = substr( sha1( wp_rand( 0, 1000000 ) ), 0, 10 );
2765
		}
2766
2767
		$normalized_request_string = join(
2768
			"\n",
2769
			array(
2770
				$token_key,
2771
				$timestamp,
2772
				$nonce,
2773
			)
2774
		) . "\n";
2775
2776
		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2777
		$signature = base64_encode( hash_hmac( 'sha1', $normalized_request_string, $token_secret, true ) );
2778
2779
		$auth = array(
2780
			'token'     => $token_key,
2781
			'timestamp' => $timestamp,
2782
			'nonce'     => $nonce,
2783
			'signature' => $signature,
2784
		);
2785
2786
		$header_pieces = array();
2787
		foreach ( $auth as $key => $value ) {
2788
			$header_pieces[] = sprintf( '%s="%s"', $key, $value );
2789
		}
2790
2791
		return join( ' ', $header_pieces );
2792
	}
2793
2794
	/**
2795
	 * If connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2796
	 *
2797
	 * @param array $stats The Heartbeat stats array.
2798
	 * @return array $stats
2799
	 */
2800
	public function add_stats_to_heartbeat( $stats ) {
2801
2802
		if ( ! $this->is_active() ) {
2803
			return $stats;
2804
		}
2805
2806
		$active_plugins_using_connection = Plugin_Storage::get_all();
2807
		foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
2808
			if ( 'jetpack' !== $plugin_slug ) {
2809
				$stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2810
				$stats[ $stats_group ][] = $plugin_slug;
2811
			}
2812
		}
2813
		return $stats;
2814
	}
2815
}
2816