Completed
Push — add/connection-heartbeat ( 874505 )
by
unknown
28:51 queued 21:28
created

Manager::add_stats_to_heartbeat()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
2296
			if ( 'jetpack' !== $plugin_slug ) {
2297
				$stats_group           = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2298
				$stats[ $stats_group ] = $plugin_slug;
2299
			}
2300
		}
2301
		return $stats;
2302
	}
2303
2304
}
2305