Completed
Push — add/partial-reconnect ( 6f9062...c5b963 )
by
unknown
32:35 queued 22:16
created

Manager::get_plugin()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
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
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
211
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
212
		global $HTTP_RAW_POST_DATA;
213
214
		// Some browser-embedded clients send cookies. We don't want them.
215
		$_COOKIE = array();
216
217
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
218
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
219
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
220
		}
221
222
		// phpcs:enable
223
224
		include_once ABSPATH . 'wp-admin/includes/admin.php';
225
		include_once ABSPATH . WPINC . '/class-IXR.php';
226
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
227
228
		/**
229
		 * Filters the class used for handling XML-RPC requests.
230
		 *
231
		 * @since 3.1.0
232
		 *
233
		 * @param string $class The name of the XML-RPC server class.
234
		 */
235
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
236
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
237
238
		// Fire off the request.
239
		nocache_headers();
240
		$wp_xmlrpc_server->serve_request();
241
242
		exit;
243
	}
244
245
	/**
246
	 * Removes all XML-RPC methods that are not `jetpack.*`.
247
	 * Only used in our alternate XML-RPC endpoint, where we want to
248
	 * ensure that Core and other plugins' methods are not exposed.
249
	 *
250
	 * @param array $methods a list of registered WordPress XMLRPC methods.
251
	 * @return array filtered $methods
252
	 */
253
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
254
		$jetpack_methods = array();
255
256
		foreach ( $methods as $method => $callback ) {
257
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
258
				$jetpack_methods[ $method ] = $callback;
259
			}
260
		}
261
262
		return $jetpack_methods;
263
	}
264
265
	/**
266
	 * Removes all other authentication methods not to allow other
267
	 * methods to validate unauthenticated requests.
268
	 */
269
	public function require_jetpack_authentication() {
270
		// Don't let anyone authenticate.
271
		$_COOKIE = array();
272
		remove_all_filters( 'authenticate' );
273
		remove_all_actions( 'wp_login_failed' );
274
275
		if ( $this->is_active() ) {
276
			// Allow Jetpack authentication.
277
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
278
		}
279
	}
280
281
	/**
282
	 * Authenticates XML-RPC and other requests from the Jetpack Server
283
	 *
284
	 * @param WP_User|Mixed $user user object if authenticated.
285
	 * @param String        $username username.
286
	 * @param String        $password password string.
287
	 * @return WP_User|Mixed authenticated user or error.
288
	 */
289
	public function authenticate_jetpack( $user, $username, $password ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
290
		if ( is_a( $user, '\\WP_User' ) ) {
291
			return $user;
292
		}
293
294
		$token_details = $this->verify_xml_rpc_signature();
295
296
		if ( ! $token_details ) {
297
			return $user;
298
		}
299
300
		if ( 'user' !== $token_details['type'] ) {
301
			return $user;
302
		}
303
304
		if ( ! $token_details['user_id'] ) {
305
			return $user;
306
		}
307
308
		nocache_headers();
309
310
		return new \WP_User( $token_details['user_id'] );
311
	}
312
313
	/**
314
	 * Verifies the signature of the current request.
315
	 *
316
	 * @return false|array
317
	 */
318
	public function verify_xml_rpc_signature() {
319
		if ( is_null( $this->xmlrpc_verification ) ) {
320
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
321
322
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
323
				/**
324
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
325
				 *
326
				 * @since 7.5.0
327
				 *
328
				 * @param WP_Error $signature_verification_error The verification error
329
				 */
330
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
331
332
				Error_Handler::get_instance()->report_error( $this->xmlrpc_verification );
333
334
			}
335
		}
336
337
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
338
	}
339
340
	/**
341
	 * Verifies the signature of the current request.
342
	 *
343
	 * This function has side effects and should not be used. Instead,
344
	 * use the memoized version `->verify_xml_rpc_signature()`.
345
	 *
346
	 * @internal
347
	 * @todo Refactor to use proper nonce verification.
348
	 */
349
	private function internal_verify_xml_rpc_signature() {
350
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
351
		// It's not for us.
352
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
353
			return false;
354
		}
355
356
		$signature_details = array(
357
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
358
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
359
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
360
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
361
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
362
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
363
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
364
		);
365
366
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
367
		@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...
368
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
369
370
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
371
372
		if (
373
			empty( $token_key )
374
		||
375
			empty( $version ) || strval( $jetpack_api_version ) !== $version ) {
376
			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...
377
		}
378
379
		if ( '0' === $user_id ) {
380
			$token_type = 'blog';
381
			$user_id    = 0;
382
		} else {
383
			$token_type = 'user';
384
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
385
				return new \WP_Error(
386
					'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...
387
					'Malformed user_id in request',
388
					compact( 'signature_details' )
389
				);
390
			}
391
			$user_id = (int) $user_id;
392
393
			$user = new \WP_User( $user_id );
394
			if ( ! $user || ! $user->exists() ) {
395
				return new \WP_Error(
396
					'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...
397
					sprintf( 'User %d does not exist', $user_id ),
398
					compact( 'signature_details' )
399
				);
400
			}
401
		}
402
403
		$token = $this->get_access_token( $user_id, $token_key, false );
404
		if ( is_wp_error( $token ) ) {
405
			$token->add_data( compact( 'signature_details' ) );
406
			return $token;
407
		} elseif ( ! $token ) {
408
			return new \WP_Error(
409
				'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...
410
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
411
				compact( 'signature_details' )
412
			);
413
		}
414
415
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
416
		// phpcs:disable WordPress.Security.NonceVerification.Missing
417
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
418
			$post_data   = $_POST;
419
			$file_hashes = array();
420
			foreach ( $post_data as $post_data_key => $post_data_value ) {
421
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
422
					continue;
423
				}
424
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
425
				$file_hashes[ $post_data_key ] = $post_data_value;
426
			}
427
428
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
429
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
430
				$post_data[ $post_data_key ] = $post_data_value;
431
			}
432
433
			ksort( $post_data );
434
435
			$body = http_build_query( stripslashes_deep( $post_data ) );
436
		} elseif ( is_null( $this->raw_post_data ) ) {
437
			$body = file_get_contents( 'php://input' );
438
		} else {
439
			$body = null;
440
		}
441
		// phpcs:enable
442
443
		$signature = $jetpack_signature->sign_current_request(
444
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
445
		);
446
447
		$signature_details['url'] = $jetpack_signature->current_request_url;
448
449
		if ( ! $signature ) {
450
			return new \WP_Error(
451
				'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...
452
				'Unknown signature error',
453
				compact( 'signature_details' )
454
			);
455
		} elseif ( is_wp_error( $signature ) ) {
456
			return $signature;
457
		}
458
459
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
460
		$timestamp = (int) $_GET['timestamp'];
461
		$nonce     = stripslashes( (string) $_GET['nonce'] );
462
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
463
464
		// Use up the nonce regardless of whether the signature matches.
465
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
466
			return new \WP_Error(
467
				'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...
468
				'Could not add nonce',
469
				compact( 'signature_details' )
470
			);
471
		}
472
473
		// Be careful about what you do with this debugging data.
474
		// If a malicious requester has access to the expected signature,
475
		// bad things might be possible.
476
		$signature_details['expected'] = $signature;
477
478
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
479
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
480
			return new \WP_Error(
481
				'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...
482
				'Signature mismatch',
483
				compact( 'signature_details' )
484
			);
485
		}
486
487
		/**
488
		 * Action for additional token checking.
489
		 *
490
		 * @since 7.7.0
491
		 *
492
		 * @param array $post_data request data.
493
		 * @param array $token_data token data.
494
		 */
495
		return apply_filters(
496
			'jetpack_signature_check_token',
497
			array(
498
				'type'      => $token_type,
499
				'token_key' => $token_key,
500
				'user_id'   => $token->external_user_id,
501
			),
502
			$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...
503
			$this->raw_post_data
504
		);
505
	}
506
507
	/**
508
	 * Returns true if the current site is connected to WordPress.com.
509
	 *
510
	 * @return Boolean is the site connected?
511
	 */
512
	public function is_active() {
513
		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...
514
	}
515
516
	/**
517
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
518
	 *
519
	 * @access public
520
	 *
521
	 * @return bool
522
	 */
523
	public function is_registered() {
524
		$has_blog_id    = (bool) \Jetpack_Options::get_option( 'id' );
525
		$has_blog_token = (bool) $this->get_access_token( false );
526
		return $has_blog_id && $has_blog_token;
527
	}
528
529
	/**
530
	 * Checks to see if the connection owner of the site is missing.
531
	 *
532
	 * @return bool
533
	 */
534
	public function is_missing_connection_owner() {
535
		$connection_owner = $this->get_connection_owner_id();
536
		if ( ! get_user_by( 'id', $connection_owner ) ) {
537
			return true;
538
		}
539
540
		return false;
541
	}
542
543
	/**
544
	 * Returns true if the user with the specified identifier is connected to
545
	 * WordPress.com.
546
	 *
547
	 * @param Integer|Boolean $user_id the user identifier.
548
	 * @return Boolean is the user connected?
549
	 */
550
	public function is_user_connected( $user_id = false ) {
551
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
552
		if ( ! $user_id ) {
553
			return false;
554
		}
555
556
		return (bool) $this->get_access_token( $user_id );
557
	}
558
559
	/**
560
	 * Returns the local user ID of the connection owner.
561
	 *
562
	 * @return string|int Returns the ID of the connection owner or False if no connection owner found.
563
	 */
564 View Code Duplication
	public function get_connection_owner_id() {
565
		$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...
566
		$connection_owner = false;
567
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
568
			$connection_owner = $user_token->external_user_id;
569
		}
570
571
		return $connection_owner;
572
	}
573
574
	/**
575
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
576
	 * Able to select by specific capability.
577
	 *
578
	 * @param string $capability The capability of the user.
579
	 * @return array Array of WP_User objects if found.
580
	 */
581
	public function get_connected_users( $capability = 'any' ) {
582
		$connected_users    = array();
583
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
584
585
		if ( ! empty( $connected_user_ids ) ) {
586
			foreach ( $connected_user_ids as $id ) {
587
				// Check for capability.
588
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
589
					continue;
590
				}
591
592
				$connected_users[] = get_userdata( $id );
593
			}
594
		}
595
596
		return $connected_users;
597
	}
598
599
	/**
600
	 * Get the wpcom user data of the current|specified connected user.
601
	 *
602
	 * @todo Refactor to properly load the XMLRPC client independently.
603
	 *
604
	 * @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...
605
	 * @return Object the user object.
606
	 */
607 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
608
		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...
609
			$user_id = get_current_user_id();
610
		}
611
612
		$transient_key    = "jetpack_connected_user_data_$user_id";
613
		$cached_user_data = get_transient( $transient_key );
614
615
		if ( $cached_user_data ) {
616
			return $cached_user_data;
617
		}
618
619
		$xml = new \Jetpack_IXR_Client(
620
			array(
621
				'user_id' => $user_id,
622
			)
623
		);
624
		$xml->query( 'wpcom.getUser' );
625
		if ( ! $xml->isError() ) {
626
			$user_data = $xml->getResponse();
627
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
628
			return $user_data;
629
		}
630
631
		return false;
632
	}
633
634
	/**
635
	 * Returns a user object of the connection owner.
636
	 *
637
	 * @return object|false False if no connection owner found.
638
	 */
639 View Code Duplication
	public function get_connection_owner() {
640
		$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...
641
642
		$connection_owner = false;
643
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
644
			$connection_owner = get_userdata( $user_token->external_user_id );
645
		}
646
647
		return $connection_owner;
648
	}
649
650
	/**
651
	 * Returns true if the provided user is the Jetpack connection owner.
652
	 * If user ID is not specified, the current user will be used.
653
	 *
654
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
655
	 * @return Boolean True the user the connection owner, false otherwise.
656
	 */
657 View Code Duplication
	public function is_connection_owner( $user_id = false ) {
658
		if ( ! $user_id ) {
659
			$user_id = get_current_user_id();
660
		}
661
662
		$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...
663
664
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
665
	}
666
667
	/**
668
	 * Connects the user with a specified ID to a WordPress.com user using the
669
	 * remote login flow.
670
	 *
671
	 * @access public
672
	 *
673
	 * @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...
674
	 * @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...
675
	 *                              admin_url().
676
	 * @return WP_Error only in case of a failed user lookup.
677
	 */
678
	public function connect_user( $user_id = null, $redirect_url = null ) {
679
		$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...
680
		if ( null === $user_id ) {
681
			$user = wp_get_current_user();
682
		} else {
683
			$user = get_user_by( 'ID', $user_id );
684
		}
685
686
		if ( empty( $user ) ) {
687
			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...
688
		}
689
690
		if ( null === $redirect_url ) {
691
			$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...
692
		}
693
694
		// Using wp_redirect intentionally because we're redirecting outside.
695
		wp_redirect( $this->get_authorization_url( $user ) ); // phpcs:ignore WordPress.Security.SafeRedirect
696
		exit();
697
	}
698
699
	/**
700
	 * Unlinks the current user from the linked WordPress.com user.
701
	 *
702
	 * @access public
703
	 * @static
704
	 *
705
	 * @todo Refactor to properly load the XMLRPC client independently.
706
	 *
707
	 * @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...
708
	 * @param bool    $can_overwrite_primary_user Allow for the primary user to be disconnected.
709
	 * @return Boolean Whether the disconnection of the user was successful.
710
	 */
711
	public static function disconnect_user( $user_id = null, $can_overwrite_primary_user = false ) {
712
		$tokens = Jetpack_Options::get_option( 'user_tokens' );
713
		if ( ! $tokens ) {
714
			return false;
715
		}
716
717
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
718
719
		if ( Jetpack_Options::get_option( 'master_user' ) === $user_id && ! $can_overwrite_primary_user ) {
720
			return false;
721
		}
722
723
		if ( ! isset( $tokens[ $user_id ] ) ) {
724
			return false;
725
		}
726
727
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
728
		$xml->query( 'jetpack.unlink_user', $user_id );
729
730
		unset( $tokens[ $user_id ] );
731
732
		Jetpack_Options::update_option( 'user_tokens', $tokens );
733
734
		// Delete cached connected user data.
735
		$transient_key = "jetpack_connected_user_data_$user_id";
736
		delete_transient( $transient_key );
737
738
		/**
739
		 * Fires after the current user has been unlinked from WordPress.com.
740
		 *
741
		 * @since 4.1.0
742
		 *
743
		 * @param int $user_id The current user's ID.
744
		 */
745
		do_action( 'jetpack_unlinked_user', $user_id );
746
747
		return true;
748
	}
749
750
	/**
751
	 * Returns the requested Jetpack API URL.
752
	 *
753
	 * @param String $relative_url the relative API path.
754
	 * @return String API URL.
755
	 */
756
	public function api_url( $relative_url ) {
757
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
758
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
759
760
		/**
761
		 * Filters whether the connection manager should use the iframe authorization
762
		 * flow instead of the regular redirect-based flow.
763
		 *
764
		 * @since 8.3.0
765
		 *
766
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
767
		 */
768
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
769
770
		// Do not modify anything that is not related to authorize requests.
771
		if ( 'authorize' === $relative_url && $iframe_flow ) {
772
			$relative_url = 'authorize_iframe';
773
		}
774
775
		/**
776
		 * Filters the API URL that Jetpack uses for server communication.
777
		 *
778
		 * @since 8.0.0
779
		 *
780
		 * @param String $url the generated URL.
781
		 * @param String $relative_url the relative URL that was passed as an argument.
782
		 * @param String $api_base the API base string that is being used.
783
		 * @param String $api_version the API version string that is being used.
784
		 */
785
		return apply_filters(
786
			'jetpack_api_url',
787
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
788
			$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...
789
			$api_base,
790
			$api_version
791
		);
792
	}
793
794
	/**
795
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
796
	 *
797
	 * @return String XMLRPC API URL.
798
	 */
799
	public function xmlrpc_api_url() {
800
		$base = preg_replace(
801
			'#(https?://[^?/]+)(/?.*)?$#',
802
			'\\1',
803
			Constants::get_constant( 'JETPACK__API_BASE' )
804
		);
805
		return untrailingslashit( $base ) . '/xmlrpc.php';
806
	}
807
808
	/**
809
	 * Attempts Jetpack registration which sets up the site for connection. Should
810
	 * remain public because the call to action comes from the current site, not from
811
	 * WordPress.com.
812
	 *
813
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
814
	 * @return true|WP_Error The error object.
815
	 */
816
	public function register( $api_endpoint = 'register' ) {
817
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
818
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
819
820
		if (
821
			empty( $secrets['secret_1'] ) ||
822
			empty( $secrets['secret_2'] ) ||
823
			empty( $secrets['exp'] )
824
		) {
825
			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...
826
		}
827
828
		// Better to try (and fail) to set a higher timeout than this system
829
		// supports than to have register fail for more users than it should.
830
		$timeout = $this->set_min_time_limit( 60 ) / 2;
831
832
		$gmt_offset = get_option( 'gmt_offset' );
833
		if ( ! $gmt_offset ) {
834
			$gmt_offset = 0;
835
		}
836
837
		$stats_options = get_option( 'stats_options' );
838
		$stats_id      = isset( $stats_options['blog_id'] )
839
			? $stats_options['blog_id']
840
			: null;
841
842
		/**
843
		 * Filters the request body for additional property addition.
844
		 *
845
		 * @since 7.7.0
846
		 *
847
		 * @param array $post_data request data.
848
		 * @param Array $token_data token data.
849
		 */
850
		$body = apply_filters(
851
			'jetpack_register_request_body',
852
			array(
853
				'siteurl'         => site_url(),
854
				'home'            => home_url(),
855
				'gmt_offset'      => $gmt_offset,
856
				'timezone_string' => (string) get_option( 'timezone_string' ),
857
				'site_name'       => (string) get_option( 'blogname' ),
858
				'secret_1'        => $secrets['secret_1'],
859
				'secret_2'        => $secrets['secret_2'],
860
				'site_lang'       => get_locale(),
861
				'timeout'         => $timeout,
862
				'stats_id'        => $stats_id,
863
				'state'           => get_current_user_id(),
864
				'site_created'    => $this->get_assumed_site_creation_date(),
865
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
866
				'ABSPATH'         => Constants::get_constant( 'ABSPATH' ),
867
			)
868
		);
869
870
		$args = array(
871
			'method'  => 'POST',
872
			'body'    => $body,
873
			'headers' => array(
874
				'Accept' => 'application/json',
875
			),
876
			'timeout' => $timeout,
877
		);
878
879
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
880
881
		// TODO: fix URLs for bad hosts.
882
		$response = Client::_wp_remote_request(
883
			$this->api_url( $api_endpoint ),
884
			$args,
885
			true
886
		);
887
888
		// Make sure the response is valid and does not contain any Jetpack errors.
889
		$registration_details = $this->validate_remote_register_response( $response );
890
891
		if ( is_wp_error( $registration_details ) ) {
892
			return $registration_details;
893
		} elseif ( ! $registration_details ) {
894
			return new \WP_Error(
895
				'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...
896
				'Unknown error registering your Jetpack site.',
897
				wp_remote_retrieve_response_code( $response )
898
			);
899
		}
900
901
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
902
			return new \WP_Error(
903
				'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...
904
				'Unable to validate registration of your Jetpack site.',
905
				wp_remote_retrieve_response_code( $response )
906
			);
907
		}
908
909
		if ( isset( $registration_details->jetpack_public ) ) {
910
			$jetpack_public = (int) $registration_details->jetpack_public;
911
		} else {
912
			$jetpack_public = false;
913
		}
914
915
		\Jetpack_Options::update_options(
916
			array(
917
				'id'         => (int) $registration_details->jetpack_id,
918
				'blog_token' => (string) $registration_details->jetpack_secret,
919
				'public'     => $jetpack_public,
920
			)
921
		);
922
923
		/**
924
		 * Fires when a site is registered on WordPress.com.
925
		 *
926
		 * @since 3.7.0
927
		 *
928
		 * @param int $json->jetpack_id Jetpack Blog ID.
929
		 * @param string $json->jetpack_secret Jetpack Blog Token.
930
		 * @param int|bool $jetpack_public Is the site public.
931
		 */
932
		do_action(
933
			'jetpack_site_registered',
934
			$registration_details->jetpack_id,
935
			$registration_details->jetpack_secret,
936
			$jetpack_public
937
		);
938
939
		if ( isset( $registration_details->token ) ) {
940
			/**
941
			 * Fires when a user token is sent along with the registration data.
942
			 *
943
			 * @since 7.6.0
944
			 *
945
			 * @param object $token the administrator token for the newly registered site.
946
			 */
947
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
948
		}
949
950
		return true;
951
	}
952
953
	/**
954
	 * Takes the response from the Jetpack register new site endpoint and
955
	 * verifies it worked properly.
956
	 *
957
	 * @since 2.6
958
	 *
959
	 * @param Mixed $response the response object, or the error object.
960
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
961
	 **/
962
	protected function validate_remote_register_response( $response ) {
963
		if ( is_wp_error( $response ) ) {
964
			return new \WP_Error(
965
				'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...
966
				$response->get_error_message()
967
			);
968
		}
969
970
		$code   = wp_remote_retrieve_response_code( $response );
971
		$entity = wp_remote_retrieve_body( $response );
972
973
		if ( $entity ) {
974
			$registration_response = json_decode( $entity );
975
		} else {
976
			$registration_response = false;
977
		}
978
979
		$code_type = intval( $code / 100 );
980
		if ( 5 === $code_type ) {
981
			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...
982
		} elseif ( 408 === $code ) {
983
			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...
984
		} elseif ( ! empty( $registration_response->error ) ) {
985
			if (
986
				'xml_rpc-32700' === $registration_response->error
987
				&& ! function_exists( 'xml_parser_create' )
988
			) {
989
				$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' );
990
			} else {
991
				$error_description = isset( $registration_response->error_description )
992
					? (string) $registration_response->error_description
993
					: '';
994
			}
995
996
			return new \WP_Error(
997
				(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...
998
				$error_description,
999
				$code
1000
			);
1001
		} elseif ( 200 !== $code ) {
1002
			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...
1003
		}
1004
1005
		// Jetpack ID error block.
1006
		if ( empty( $registration_response->jetpack_id ) ) {
1007
			return new \WP_Error(
1008
				'jetpack_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

Loading history...
1009
				/* translators: %s is an error message string */
1010
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1011
				$entity
1012
			);
1013
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1014
			return new \WP_Error(
1015
				'jetpack_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

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