Completed
Push — fix/sync-empty-errors ( 53827c...ec13f3 )
by
unknown
89:12 queued 80:44
created

Manager::verify_xml_rpc_signature()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

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