Completed
Push — update/colors-studio ( cf5381...3e8e37 )
by Jeremy
65:33 queued 57:26
created

Manager::refresh_blog_token()   B

Complexity

Conditions 9
Paths 12

Size

Total Lines 51

Duplication

Lines 10
Ratio 19.61 %

Importance

Changes 0
Metric Value
cc 9
nc 12
nop 0
dl 10
loc 51
rs 7.5135
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * The Jetpack Connection manager class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Tracking;
14
use Jetpack_Options;
15
use WP_Error;
16
use WP_User;
17
use Automattic\Jetpack\Heartbeat;
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
	const JETPACK_MASTER_USER    = true;
30
31
	/**
32
	 * The procedure that should be run to generate secrets.
33
	 *
34
	 * @var Callable
35
	 */
36
	protected $secret_callable;
37
38
	/**
39
	 * A copy of the raw POST data for signature verification purposes.
40
	 *
41
	 * @var String
42
	 */
43
	protected $raw_post_data;
44
45
	/**
46
	 * Verification data needs to be stored to properly verify everything.
47
	 *
48
	 * @var Object
49
	 */
50
	private $xmlrpc_verification = null;
51
52
	/**
53
	 * Plugin management object.
54
	 *
55
	 * @var Plugin
56
	 */
57
	private $plugin = null;
58
59
	/**
60
	 * Initialize the object.
61
	 * Make sure to call the "Configure" first.
62
	 *
63
	 * @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...
64
	 *
65
	 * @see \Automattic\Jetpack\Config
66
	 */
67
	public function __construct( $plugin_slug = null ) {
68
		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...
69
			$this->set_plugin_instance( new Plugin( $plugin_slug ) );
70
		}
71
	}
72
73
	/**
74
	 * Initializes required listeners. This is done separately from the constructors
75
	 * because some objects sometimes need to instantiate separate objects of this class.
76
	 *
77
	 * @todo Implement a proper nonce verification.
78
	 */
79
	public static function configure() {
80
		$manager = new self();
81
82
		add_filter(
83
			'jetpack_constant_default_value',
84
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
85
			10,
86
			2
87
		);
88
89
		$manager->setup_xmlrpc_handlers(
90
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
91
			$manager->is_active(),
92
			$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...
93
		);
94
95
		$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...
96
97
		if ( $manager->is_active() ) {
98
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
99
		}
100
101
		add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
102
103
		add_action( 'jetpack_clean_nonces', array( $manager, 'clean_nonces' ) );
104
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
105
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
106
		}
107
108
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
109
110
		add_filter( 'map_meta_cap', array( $manager, 'jetpack_connection_custom_caps' ), 1, 4 );
111
112
		Heartbeat::init();
113
		add_filter( 'jetpack_heartbeat_stats_array', array( $manager, 'add_stats_to_heartbeat' ) );
114
115
	}
116
117
	/**
118
	 * Sets up the XMLRPC request handlers.
119
	 *
120
	 * @param array                  $request_params incoming request parameters.
121
	 * @param Boolean                $is_active whether the connection is currently active.
122
	 * @param Boolean                $is_signed whether the signature check has been successful.
123
	 * @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...
124
	 */
125
	public function setup_xmlrpc_handlers(
126
		$request_params,
127
		$is_active,
128
		$is_signed,
129
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
130
	) {
131
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
132
133
		if (
134
			! isset( $request_params['for'] )
135
			|| 'jetpack' !== $request_params['for']
136
		) {
137
			return false;
138
		}
139
140
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
141
		if (
142
			isset( $request_params['jetpack'] )
143
			&& 'comms' === $request_params['jetpack']
144
		) {
145
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
146
				// Use the real constant here for WordPress' sake.
147
				define( 'XMLRPC_REQUEST', true );
148
			}
149
150
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
151
152
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
153
		}
154
155
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
156
			return false;
157
		}
158
		// Display errors can cause the XML to be not well formed.
159
		@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...
160
161
		if ( $xmlrpc_server ) {
162
			$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...
163
		} else {
164
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
165
		}
166
167
		$this->require_jetpack_authentication();
168
169
		if ( $is_active ) {
170
			// Hack to preserve $HTTP_RAW_POST_DATA.
171
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
172
173
			if ( $is_signed ) {
174
				// The actual API methods.
175
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
176
			} else {
177
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
178
				// active Jetpack connection, so that additional users can link their account.
179
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
180
			}
181
		} else {
182
			// The bootstrap API methods.
183
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
184
185
			if ( $is_signed ) {
186
				// The jetpack Provision method is available for blog-token-signed requests.
187
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
188
			} else {
189
				new XMLRPC_Connector( $this );
190
			}
191
		}
192
193
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
194
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
195
		return true;
196
	}
197
198
	/**
199
	 * Initializes the REST API connector on the init hook.
200
	 */
201
	public function initialize_rest_api_registration_connector() {
202
		new REST_Connector( $this );
203
	}
204
205
	/**
206
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
207
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
208
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
209
	 * which is accessible via a different URI. Most of the below is copied directly
210
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
211
	 *
212
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
213
	 */
214
	public function alternate_xmlrpc() {
215
		// Some browser-embedded clients send cookies. We don't want them.
216
		$_COOKIE = array();
217
218
		include_once ABSPATH . 'wp-admin/includes/admin.php';
219
		include_once ABSPATH . WPINC . '/class-IXR.php';
220
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
221
222
		/**
223
		 * Filters the class used for handling XML-RPC requests.
224
		 *
225
		 * @since 3.1.0
226
		 *
227
		 * @param string $class The name of the XML-RPC server class.
228
		 */
229
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
230
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
231
232
		// Fire off the request.
233
		nocache_headers();
234
		$wp_xmlrpc_server->serve_request();
235
236
		exit;
237
	}
238
239
	/**
240
	 * Removes all XML-RPC methods that are not `jetpack.*`.
241
	 * Only used in our alternate XML-RPC endpoint, where we want to
242
	 * ensure that Core and other plugins' methods are not exposed.
243
	 *
244
	 * @param array $methods a list of registered WordPress XMLRPC methods.
245
	 * @return array filtered $methods
246
	 */
247
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
248
		$jetpack_methods = array();
249
250
		foreach ( $methods as $method => $callback ) {
251
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
252
				$jetpack_methods[ $method ] = $callback;
253
			}
254
		}
255
256
		return $jetpack_methods;
257
	}
258
259
	/**
260
	 * Removes all other authentication methods not to allow other
261
	 * methods to validate unauthenticated requests.
262
	 */
263
	public function require_jetpack_authentication() {
264
		// Don't let anyone authenticate.
265
		$_COOKIE = array();
266
		remove_all_filters( 'authenticate' );
267
		remove_all_actions( 'wp_login_failed' );
268
269
		if ( $this->is_active() ) {
270
			// Allow Jetpack authentication.
271
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
272
		}
273
	}
274
275
	/**
276
	 * Authenticates XML-RPC and other requests from the Jetpack Server
277
	 *
278
	 * @param WP_User|Mixed $user user object if authenticated.
279
	 * @param String        $username username.
280
	 * @param String        $password password string.
281
	 * @return WP_User|Mixed authenticated user or error.
282
	 */
283
	public function authenticate_jetpack( $user, $username, $password ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
284
		if ( is_a( $user, '\\WP_User' ) ) {
285
			return $user;
286
		}
287
288
		$token_details = $this->verify_xml_rpc_signature();
289
290
		if ( ! $token_details ) {
291
			return $user;
292
		}
293
294
		if ( 'user' !== $token_details['type'] ) {
295
			return $user;
296
		}
297
298
		if ( ! $token_details['user_id'] ) {
299
			return $user;
300
		}
301
302
		nocache_headers();
303
304
		return new \WP_User( $token_details['user_id'] );
305
	}
306
307
	/**
308
	 * Verifies the signature of the current request.
309
	 *
310
	 * @return false|array
311
	 */
312
	public function verify_xml_rpc_signature() {
313
		if ( is_null( $this->xmlrpc_verification ) ) {
314
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
315
316
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
317
				/**
318
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
319
				 *
320
				 * @since 7.5.0
321
				 *
322
				 * @param WP_Error $signature_verification_error The verification error
323
				 */
324
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
325
326
				Error_Handler::get_instance()->report_error( $this->xmlrpc_verification );
327
328
			}
329
		}
330
331
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
332
	}
333
334
	/**
335
	 * Verifies the signature of the current request.
336
	 *
337
	 * This function has side effects and should not be used. Instead,
338
	 * use the memoized version `->verify_xml_rpc_signature()`.
339
	 *
340
	 * @internal
341
	 * @todo Refactor to use proper nonce verification.
342
	 */
343
	private function internal_verify_xml_rpc_signature() {
344
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
345
		// It's not for us.
346
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
347
			return false;
348
		}
349
350
		$signature_details = array(
351
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
352
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
353
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
354
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
355
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
356
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
357
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
358
		);
359
360
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
361
		@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...
362
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
363
364
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
365
366
		if (
367
			empty( $token_key )
368
		||
369
			empty( $version ) || strval( $jetpack_api_version ) !== $version ) {
370
			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...
371
		}
372
373
		if ( '0' === $user_id ) {
374
			$token_type = 'blog';
375
			$user_id    = 0;
376
		} else {
377
			$token_type = 'user';
378
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
379
				return new \WP_Error(
380
					'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...
381
					'Malformed user_id in request',
382
					compact( 'signature_details' )
383
				);
384
			}
385
			$user_id = (int) $user_id;
386
387
			$user = new \WP_User( $user_id );
388
			if ( ! $user || ! $user->exists() ) {
389
				return new \WP_Error(
390
					'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...
391
					sprintf( 'User %d does not exist', $user_id ),
392
					compact( 'signature_details' )
393
				);
394
			}
395
		}
396
397
		$token = $this->get_access_token( $user_id, $token_key, false );
398
		if ( is_wp_error( $token ) ) {
399
			$token->add_data( compact( 'signature_details' ) );
400
			return $token;
401
		} elseif ( ! $token ) {
402
			return new \WP_Error(
403
				'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...
404
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
405
				compact( 'signature_details' )
406
			);
407
		}
408
409
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
410
		// phpcs:disable WordPress.Security.NonceVerification.Missing
411
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
412
			$post_data   = $_POST;
413
			$file_hashes = array();
414
			foreach ( $post_data as $post_data_key => $post_data_value ) {
415
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
416
					continue;
417
				}
418
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
419
				$file_hashes[ $post_data_key ] = $post_data_value;
420
			}
421
422
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
423
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
424
				$post_data[ $post_data_key ] = $post_data_value;
425
			}
426
427
			ksort( $post_data );
428
429
			$body = http_build_query( stripslashes_deep( $post_data ) );
430
		} elseif ( is_null( $this->raw_post_data ) ) {
431
			$body = file_get_contents( 'php://input' );
432
		} else {
433
			$body = null;
434
		}
435
		// phpcs:enable
436
437
		$signature = $jetpack_signature->sign_current_request(
438
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
439
		);
440
441
		$signature_details['url'] = $jetpack_signature->current_request_url;
442
443
		if ( ! $signature ) {
444
			return new \WP_Error(
445
				'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...
446
				'Unknown signature error',
447
				compact( 'signature_details' )
448
			);
449
		} elseif ( is_wp_error( $signature ) ) {
450
			return $signature;
451
		}
452
453
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
454
		$timestamp = (int) $_GET['timestamp'];
455
		$nonce     = stripslashes( (string) $_GET['nonce'] );
456
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
457
458
		// Use up the nonce regardless of whether the signature matches.
459
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
460
			return new \WP_Error(
461
				'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...
462
				'Could not add nonce',
463
				compact( 'signature_details' )
464
			);
465
		}
466
467
		// Be careful about what you do with this debugging data.
468
		// If a malicious requester has access to the expected signature,
469
		// bad things might be possible.
470
		$signature_details['expected'] = $signature;
471
472
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
473
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
474
			return new \WP_Error(
475
				'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...
476
				'Signature mismatch',
477
				compact( 'signature_details' )
478
			);
479
		}
480
481
		/**
482
		 * Action for additional token checking.
483
		 *
484
		 * @since 7.7.0
485
		 *
486
		 * @param array $post_data request data.
487
		 * @param array $token_data token data.
488
		 */
489
		return apply_filters(
490
			'jetpack_signature_check_token',
491
			array(
492
				'type'      => $token_type,
493
				'token_key' => $token_key,
494
				'user_id'   => $token->external_user_id,
495
			),
496
			$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...
497
			$this->raw_post_data
498
		);
499
	}
500
501
	/**
502
	 * Returns true if the current site is connected to WordPress.com.
503
	 *
504
	 * @return Boolean is the site connected?
505
	 */
506
	public function is_active() {
507
		return (bool) $this->get_access_token( self::JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
self::JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
508
	}
509
510
	/**
511
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
512
	 *
513
	 * @access public
514
	 *
515
	 * @return bool
516
	 */
517
	public function is_registered() {
518
		$has_blog_id    = (bool) \Jetpack_Options::get_option( 'id' );
519
		$has_blog_token = (bool) $this->get_access_token( false );
520
		return $has_blog_id && $has_blog_token;
521
	}
522
523
	/**
524
	 * Checks to see if the connection owner of the site is missing.
525
	 *
526
	 * @return bool
527
	 */
528
	public function is_missing_connection_owner() {
529
		$connection_owner = $this->get_connection_owner_id();
530
		if ( ! get_user_by( 'id', $connection_owner ) ) {
531
			return true;
532
		}
533
534
		return false;
535
	}
536
537
	/**
538
	 * Returns true if the user with the specified identifier is connected to
539
	 * WordPress.com.
540
	 *
541
	 * @param Integer|Boolean $user_id the user identifier.
542
	 * @return Boolean is the user connected?
543
	 */
544
	public function is_user_connected( $user_id = false ) {
545
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
546
		if ( ! $user_id ) {
547
			return false;
548
		}
549
550
		return (bool) $this->get_access_token( $user_id );
551
	}
552
553
	/**
554
	 * Returns the local user ID of the connection owner.
555
	 *
556
	 * @return string|int Returns the ID of the connection owner or False if no connection owner found.
557
	 */
558 View Code Duplication
	public function get_connection_owner_id() {
559
		$user_token       = $this->get_access_token( self::JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
self::JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
560
		$connection_owner = false;
561
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
562
			$connection_owner = $user_token->external_user_id;
563
		}
564
565
		return $connection_owner;
566
	}
567
568
	/**
569
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
570
	 * Able to select by specific capability.
571
	 *
572
	 * @param string $capability The capability of the user.
573
	 * @return array Array of WP_User objects if found.
574
	 */
575
	public function get_connected_users( $capability = 'any' ) {
576
		$connected_users    = array();
577
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
578
579
		if ( ! empty( $connected_user_ids ) ) {
580
			foreach ( $connected_user_ids as $id ) {
581
				// Check for capability.
582
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
583
					continue;
584
				}
585
586
				$connected_users[] = get_userdata( $id );
587
			}
588
		}
589
590
		return $connected_users;
591
	}
592
593
	/**
594
	 * Get the wpcom user data of the current|specified connected user.
595
	 *
596
	 * @todo Refactor to properly load the XMLRPC client independently.
597
	 *
598
	 * @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...
599
	 * @return Object the user object.
600
	 */
601 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
602
		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...
603
			$user_id = get_current_user_id();
604
		}
605
606
		$transient_key    = "jetpack_connected_user_data_$user_id";
607
		$cached_user_data = get_transient( $transient_key );
608
609
		if ( $cached_user_data ) {
610
			return $cached_user_data;
611
		}
612
613
		$xml = new \Jetpack_IXR_Client(
614
			array(
615
				'user_id' => $user_id,
616
			)
617
		);
618
		$xml->query( 'wpcom.getUser' );
619
		if ( ! $xml->isError() ) {
620
			$user_data = $xml->getResponse();
621
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
622
			return $user_data;
623
		}
624
625
		return false;
626
	}
627
628
	/**
629
	 * Returns a user object of the connection owner.
630
	 *
631
	 * @return object|false False if no connection owner found.
632
	 */
633 View Code Duplication
	public function get_connection_owner() {
634
		$user_token = $this->get_access_token( self::JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
self::JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
635
636
		$connection_owner = false;
637
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
638
			$connection_owner = get_userdata( $user_token->external_user_id );
639
		}
640
641
		return $connection_owner;
642
	}
643
644
	/**
645
	 * Returns true if the provided user is the Jetpack connection owner.
646
	 * If user ID is not specified, the current user will be used.
647
	 *
648
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
649
	 * @return Boolean True the user the connection owner, false otherwise.
650
	 */
651 View Code Duplication
	public function is_connection_owner( $user_id = false ) {
652
		if ( ! $user_id ) {
653
			$user_id = get_current_user_id();
654
		}
655
656
		$user_token = $this->get_access_token( self::JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
self::JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
657
658
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
659
	}
660
661
	/**
662
	 * Connects the user with a specified ID to a WordPress.com user using the
663
	 * remote login flow.
664
	 *
665
	 * @access public
666
	 *
667
	 * @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...
668
	 * @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...
669
	 *                              admin_url().
670
	 * @return WP_Error only in case of a failed user lookup.
671
	 */
672
	public function connect_user( $user_id = null, $redirect_url = null ) {
673
		$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...
674
		if ( null === $user_id ) {
675
			$user = wp_get_current_user();
676
		} else {
677
			$user = get_user_by( 'ID', $user_id );
678
		}
679
680
		if ( empty( $user ) ) {
681
			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...
682
		}
683
684
		if ( null === $redirect_url ) {
685
			$redirect_url = admin_url();
0 ignored issues
show
Unused Code introduced by
$redirect_url is not used, you could remove the assignment.

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

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

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

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

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

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

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

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

Loading history...
783
			$api_base,
784
			$api_version
785
		);
786
	}
787
788
	/**
789
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
790
	 *
791
	 * @return String XMLRPC API URL.
792
	 */
793
	public function xmlrpc_api_url() {
794
		$base = preg_replace(
795
			'#(https?://[^?/]+)(/?.*)?$#',
796
			'\\1',
797
			Constants::get_constant( 'JETPACK__API_BASE' )
798
		);
799
		return untrailingslashit( $base ) . '/xmlrpc.php';
800
	}
801
802
	/**
803
	 * Attempts Jetpack registration which sets up the site for connection. Should
804
	 * remain public because the call to action comes from the current site, not from
805
	 * WordPress.com.
806
	 *
807
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
808
	 * @return true|WP_Error The error object.
809
	 */
810
	public function register( $api_endpoint = 'register' ) {
811
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
812
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
813
814
		if (
815
			empty( $secrets['secret_1'] ) ||
816
			empty( $secrets['secret_2'] ) ||
817
			empty( $secrets['exp'] )
818
		) {
819
			return new \WP_Error( 'missing_secrets' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_secrets'.

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

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

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

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