Completed
Push — update/readme-contributors ( d0ad08...a4dd26 )
by
unknown
23:17 queued 14:53
created

Manager::add_stats_to_heartbeat()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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