Completed
Push — add/stats-package ( c3aabb...99d182 )
by
unknown
148:14 queued 140:08
created

Manager::is_connection_owner()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
cc 5
nc 8
nop 1
dl 9
loc 9
rs 9.6111
c 0
b 0
f 0
1
<?php
2
/**
3
 * The Jetpack Connection manager class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Tracking;
14
use WP_Error;
15
16
/**
17
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
18
 * and Jetpack.
19
 */
20
class Manager {
21
22
	const SECRETS_MISSING        = 'secrets_missing';
23
	const SECRETS_EXPIRED        = 'secrets_expired';
24
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
25
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
26
	const JETPACK_MASTER_USER    = true;
27
28
	/**
29
	 * The procedure that should be run to generate secrets.
30
	 *
31
	 * @var Callable
32
	 */
33
	protected $secret_callable;
34
35
	/**
36
	 * A copy of the raw POST data for signature verification purposes.
37
	 *
38
	 * @var String
39
	 */
40
	protected $raw_post_data;
41
42
	/**
43
	 * Verification data needs to be stored to properly verify everything.
44
	 *
45
	 * @var Object
46
	 */
47
	private $xmlrpc_verification = null;
48
49
	/**
50
	 * Plugin management object.
51
	 *
52
	 * @var Plugin
53
	 */
54
	private $plugin = null;
55
56
	/**
57
	 * Initialize the object.
58
	 * Make sure to call the "Configure" first.
59
	 *
60
	 * @param string $plugin_slug Slug of the plugin using the connection (optional, but encouraged).
0 ignored issues
show
Documentation introduced by
Should the type for parameter $plugin_slug not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
61
	 *
62
	 * @see \Automattic\Jetpack\Config
63
	 */
64
	public function __construct( $plugin_slug = null ) {
65
		if ( $plugin_slug && is_string( $plugin_slug ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $plugin_slug of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
66
			$this->set_plugin_instance( new Plugin( $plugin_slug ) );
67
		}
68
	}
69
70
	/**
71
	 * Initializes required listeners. This is done separately from the constructors
72
	 * because some objects sometimes need to instantiate separate objects of this class.
73
	 *
74
	 * @todo Implement a proper nonce verification.
75
	 */
76
	public static function configure() {
77
		$manager = new self();
78
79
		add_filter(
80
			'jetpack_constant_default_value',
81
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
82
			10,
83
			2
84
		);
85
86
		$manager->setup_xmlrpc_handlers(
87
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
88
			$manager->is_active(),
89
			$manager->verify_xml_rpc_signature()
0 ignored issues
show
Bug introduced by
It seems like $manager->verify_xml_rpc_signature() targeting Automattic\Jetpack\Conne...ify_xml_rpc_signature() can also be of type array; however, Automattic\Jetpack\Conne...setup_xmlrpc_handlers() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
90
		);
91
92
		$manager->error_handler = Error_Handler::get_instance();
0 ignored issues
show
Bug introduced by
The property error_handler does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
93
94
		if ( $manager->is_active() ) {
95
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
96
		} else {
97
			add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
98
		}
99
100
		add_action( 'jetpack_clean_nonces', array( $manager, 'clean_nonces' ) );
101
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
102
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
103
		}
104
105
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
106
107
		add_filter( 'map_meta_cap', array( $manager, 'jetpack_connection_custom_caps' ), 1, 4 );
108
	}
109
110
	/**
111
	 * Sets up the XMLRPC request handlers.
112
	 *
113
	 * @param array                  $request_params incoming request parameters.
114
	 * @param Boolean                $is_active whether the connection is currently active.
115
	 * @param Boolean                $is_signed whether the signature check has been successful.
116
	 * @param \Jetpack_XMLRPC_Server $xmlrpc_server (optional) an instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|\Jetpack_XMLRPC_Server?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
117
	 */
118
	public function setup_xmlrpc_handlers(
119
		$request_params,
120
		$is_active,
121
		$is_signed,
122
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
123
	) {
124
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
125
126
		if (
127
			! isset( $request_params['for'] )
128
			|| 'jetpack' !== $request_params['for']
129
		) {
130
			return false;
131
		}
132
133
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
134
		if (
135
			isset( $request_params['jetpack'] )
136
			&& 'comms' === $request_params['jetpack']
137
		) {
138
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
139
				// Use the real constant here for WordPress' sake.
140
				define( 'XMLRPC_REQUEST', true );
141
			}
142
143
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
144
145
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
146
		}
147
148
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
149
			return false;
150
		}
151
		// Display errors can cause the XML to be not well formed.
152
		@ini_set( 'display_errors', false ); // phpcs:ignore
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
153
154
		if ( $xmlrpc_server ) {
155
			$this->xmlrpc_server = $xmlrpc_server;
0 ignored issues
show
Bug introduced by
The property xmlrpc_server does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
156
		} else {
157
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
158
		}
159
160
		$this->require_jetpack_authentication();
161
162
		if ( $is_active ) {
163
			// Hack to preserve $HTTP_RAW_POST_DATA.
164
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
165
166
			if ( $is_signed ) {
167
				// The actual API methods.
168
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
169
			} else {
170
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
171
				// active Jetpack connection, so that additional users can link their account.
172
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
173
			}
174
		} else {
175
			// The bootstrap API methods.
176
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
177
178
			if ( $is_signed ) {
179
				// The jetpack Provision method is available for blog-token-signed requests.
180
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
181
			} else {
182
				new XMLRPC_Connector( $this );
183
			}
184
		}
185
186
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
187
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
188
		return true;
189
	}
190
191
	/**
192
	 * Initializes the REST API connector on the init hook.
193
	 */
194
	public function initialize_rest_api_registration_connector() {
195
		new REST_Connector( $this );
196
	}
197
198
	/**
199
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
200
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
201
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
202
	 * which is accessible via a different URI. Most of the below is copied directly
203
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
204
	 *
205
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
206
	 */
207
	public function alternate_xmlrpc() {
208
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
209
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
210
		global $HTTP_RAW_POST_DATA;
211
212
		// Some browser-embedded clients send cookies. We don't want them.
213
		$_COOKIE = array();
214
215
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
216
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
217
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
218
		}
219
220
		// phpcs:enable
221
222
		include_once ABSPATH . 'wp-admin/includes/admin.php';
223
		include_once ABSPATH . WPINC . '/class-IXR.php';
224
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
225
226
		/**
227
		 * Filters the class used for handling XML-RPC requests.
228
		 *
229
		 * @since 3.1.0
230
		 *
231
		 * @param string $class The name of the XML-RPC server class.
232
		 */
233
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
234
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
235
236
		// Fire off the request.
237
		nocache_headers();
238
		$wp_xmlrpc_server->serve_request();
239
240
		exit;
241
	}
242
243
	/**
244
	 * Removes all XML-RPC methods that are not `jetpack.*`.
245
	 * Only used in our alternate XML-RPC endpoint, where we want to
246
	 * ensure that Core and other plugins' methods are not exposed.
247
	 *
248
	 * @param array $methods a list of registered WordPress XMLRPC methods.
249
	 * @return array filtered $methods
250
	 */
251
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
252
		$jetpack_methods = array();
253
254
		foreach ( $methods as $method => $callback ) {
255
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
256
				$jetpack_methods[ $method ] = $callback;
257
			}
258
		}
259
260
		return $jetpack_methods;
261
	}
262
263
	/**
264
	 * Removes all other authentication methods not to allow other
265
	 * methods to validate unauthenticated requests.
266
	 */
267
	public function require_jetpack_authentication() {
268
		// Don't let anyone authenticate.
269
		$_COOKIE = array();
270
		remove_all_filters( 'authenticate' );
271
		remove_all_actions( 'wp_login_failed' );
272
273
		if ( $this->is_active() ) {
274
			// Allow Jetpack authentication.
275
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
276
		}
277
	}
278
279
	/**
280
	 * Authenticates XML-RPC and other requests from the Jetpack Server
281
	 *
282
	 * @param WP_User|Mixed $user user object if authenticated.
283
	 * @param String        $username username.
284
	 * @param String        $password password string.
285
	 * @return WP_User|Mixed authenticated user or error.
286
	 */
287
	public function authenticate_jetpack( $user, $username, $password ) {
288
		if ( is_a( $user, '\\WP_User' ) ) {
289
			return $user;
290
		}
291
292
		$token_details = $this->verify_xml_rpc_signature();
293
294
		if ( ! $token_details ) {
295
			return $user;
296
		}
297
298
		if ( 'user' !== $token_details['type'] ) {
299
			return $user;
300
		}
301
302
		if ( ! $token_details['user_id'] ) {
303
			return $user;
304
		}
305
306
		nocache_headers();
307
308
		return new \WP_User( $token_details['user_id'] );
309
	}
310
311
	/**
312
	 * Verifies the signature of the current request.
313
	 *
314
	 * @return false|array
315
	 */
316
	public function verify_xml_rpc_signature() {
317
		if ( is_null( $this->xmlrpc_verification ) ) {
318
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
319
320
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
321
				/**
322
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
323
				 *
324
				 * @since 7.5.0
325
				 *
326
				 * @param WP_Error $signature_verification_error The verification error
327
				 */
328
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
329
330
				Error_Handler::get_instance()->report_error( $this->xmlrpc_verification );
331
332
			}
333
		}
334
335
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
336
	}
337
338
	/**
339
	 * Verifies the signature of the current request.
340
	 *
341
	 * This function has side effects and should not be used. Instead,
342
	 * use the memoized version `->verify_xml_rpc_signature()`.
343
	 *
344
	 * @internal
345
	 * @todo Refactor to use proper nonce verification.
346
	 */
347
	private function internal_verify_xml_rpc_signature() {
348
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
349
		// It's not for us.
350
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
351
			return false;
352
		}
353
354
		$signature_details = array(
355
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
356
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
357
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
358
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
359
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
360
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
361
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
362
		);
363
364
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
365
		@list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
366
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
367
368
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
369
370
		if (
371
			empty( $token_key )
372
		||
373
			empty( $version ) || strval( $jetpack_api_version ) !== $version ) {
374
			return new \WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_token'.

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

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

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

Loading history...
375
		}
376
377
		if ( '0' === $user_id ) {
378
			$token_type = 'blog';
379
			$user_id    = 0;
380
		} else {
381
			$token_type = 'user';
382
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
383
				return new \WP_Error(
384
					'malformed_user_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_user_id'.

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

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

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

Loading history...
385
					'Malformed user_id in request',
386
					compact( 'signature_details' )
387
				);
388
			}
389
			$user_id = (int) $user_id;
390
391
			$user = new \WP_User( $user_id );
392
			if ( ! $user || ! $user->exists() ) {
393
				return new \WP_Error(
394
					'unknown_user',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_user'.

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

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

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

Loading history...
395
					sprintf( 'User %d does not exist', $user_id ),
396
					compact( 'signature_details' )
397
				);
398
			}
399
		}
400
401
		$token = $this->get_access_token( $user_id, $token_key, false );
402
		if ( is_wp_error( $token ) ) {
403
			$token->add_data( compact( 'signature_details' ) );
404
			return $token;
405
		} elseif ( ! $token ) {
406
			return new \WP_Error(
407
				'unknown_token',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
408
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
409
				compact( 'signature_details' )
410
			);
411
		}
412
413
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
414
		// phpcs:disable WordPress.Security.NonceVerification.Missing
415
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
416
			$post_data   = $_POST;
417
			$file_hashes = array();
418
			foreach ( $post_data as $post_data_key => $post_data_value ) {
419
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
420
					continue;
421
				}
422
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
423
				$file_hashes[ $post_data_key ] = $post_data_value;
424
			}
425
426
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
427
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
428
				$post_data[ $post_data_key ] = $post_data_value;
429
			}
430
431
			ksort( $post_data );
432
433
			$body = http_build_query( stripslashes_deep( $post_data ) );
434
		} elseif ( is_null( $this->raw_post_data ) ) {
435
			$body = file_get_contents( 'php://input' );
436
		} else {
437
			$body = null;
438
		}
439
		// phpcs:enable
440
441
		$signature = $jetpack_signature->sign_current_request(
442
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
443
		);
444
445
		$signature_details['url'] = $jetpack_signature->current_request_url;
446
447
		if ( ! $signature ) {
448
			return new \WP_Error(
449
				'could_not_sign',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'could_not_sign'.

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

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

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

Loading history...
450
				'Unknown signature error',
451
				compact( 'signature_details' )
452
			);
453
		} elseif ( is_wp_error( $signature ) ) {
454
			return $signature;
455
		}
456
457
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
458
		$timestamp = (int) $_GET['timestamp'];
459
		$nonce     = stripslashes( (string) $_GET['nonce'] );
460
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
461
462
		// Use up the nonce regardless of whether the signature matches.
463
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
464
			return new \WP_Error(
465
				'invalid_nonce',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

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

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

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

Loading history...
466
				'Could not add nonce',
467
				compact( 'signature_details' )
468
			);
469
		}
470
471
		// Be careful about what you do with this debugging data.
472
		// If a malicious requester has access to the expected signature,
473
		// bad things might be possible.
474
		$signature_details['expected'] = $signature;
475
476
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
477
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
478
			return new \WP_Error(
479
				'signature_mismatch',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'signature_mismatch'.

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

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

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

Loading history...
480
				'Signature mismatch',
481
				compact( 'signature_details' )
482
			);
483
		}
484
485
		/**
486
		 * Action for additional token checking.
487
		 *
488
		 * @since 7.7.0
489
		 *
490
		 * @param array $post_data request data.
491
		 * @param array $token_data token data.
492
		 */
493
		return apply_filters(
494
			'jetpack_signature_check_token',
495
			array(
496
				'type'      => $token_type,
497
				'token_key' => $token_key,
498
				'user_id'   => $token->external_user_id,
499
			),
500
			$token,
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $token.

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

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

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

Loading history...
501
			$this->raw_post_data
502
		);
503
	}
504
505
	/**
506
	 * Returns true if the current site is connected to WordPress.com.
507
	 *
508
	 * @return Boolean is the site connected?
509
	 */
510
	public function is_active() {
511
		return (bool) $this->get_access_token( self::JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
self::JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
564
		$connection_owner = false;
565
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
566
			$connection_owner = $user_token->external_user_id;
567
		}
568
569
		return $connection_owner;
570
	}
571
572
	/**
573
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
574
	 * Able to select by specific capability.
575
	 *
576
	 * @param string $capability The capability of the user.
577
	 * @return array Array of WP_User objects if found.
578
	 */
579
	public function get_connected_users( $capability = 'any' ) {
580
		$connected_users    = array();
581
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
582
583
		if ( ! empty( $connected_user_ids ) ) {
584
			foreach ( $connected_user_ids as $id ) {
585
				// Check for capability.
586
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
587
					continue;
588
				}
589
590
				$connected_users[] = get_userdata( $id );
591
			}
592
		}
593
594
		return $connected_users;
595
	}
596
597
	/**
598
	 * Get the wpcom user data of the current|specified connected user.
599
	 *
600
	 * @todo Refactor to properly load the XMLRPC client independently.
601
	 *
602
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
603
	 * @return Object the user object.
604
	 */
605 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
606
		if ( ! $user_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user_id of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
607
			$user_id = get_current_user_id();
608
		}
609
610
		$transient_key    = "jetpack_connected_user_data_$user_id";
611
		$cached_user_data = get_transient( $transient_key );
612
613
		if ( $cached_user_data ) {
614
			return $cached_user_data;
615
		}
616
617
		$xml = new \Jetpack_IXR_Client(
618
			array(
619
				'user_id' => $user_id,
620
			)
621
		);
622
		$xml->query( 'wpcom.getUser' );
623
		if ( ! $xml->isError() ) {
624
			$user_data = $xml->getResponse();
625
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
626
			return $user_data;
627
		}
628
629
		return false;
630
	}
631
632
	/**
633
	 * Returns a user object of the connection owner.
634
	 *
635
	 * @return object|false False if no connection owner found.
636
	 */
637 View Code Duplication
	public function get_connection_owner() {
638
		$user_token = $this->get_access_token( self::JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
self::JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
661
662
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
663
	}
664
665
	/**
666
	 * Connects the user with a specified ID to a WordPress.com user using the
667
	 * remote login flow.
668
	 *
669
	 * @access public
670
	 *
671
	 * @param Integer $user_id (optional) the user identifier, defaults to current user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
672
	 * @param String  $redirect_url the URL to redirect the user to for processing, defaults to
0 ignored issues
show
Documentation introduced by
Should the type for parameter $redirect_url not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
673
	 *                              admin_url().
674
	 * @return WP_Error only in case of a failed user lookup.
675
	 */
676
	public function connect_user( $user_id = null, $redirect_url = null ) {
677
		$user = null;
0 ignored issues
show
Unused Code introduced by
$user is not used, you could remove the assignment.

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

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

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

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

Loading history...
678
		if ( null === $user_id ) {
679
			$user = wp_get_current_user();
680
		} else {
681
			$user = get_user_by( 'ID', $user_id );
682
		}
683
684
		if ( empty( $user ) ) {
685
			return new \WP_Error( 'user_not_found', 'Attempting to connect a non-existent user.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_not_found'.

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

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

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

Loading history...
686
		}
687
688
		if ( null === $redirect_url ) {
689
			$redirect_url = admin_url();
0 ignored issues
show
Unused Code introduced by
$redirect_url is not used, you could remove the assignment.

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

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

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

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

Loading history...
690
		}
691
692
		// Using wp_redirect intentionally because we're redirecting outside.
693
		wp_redirect( $this->get_authorization_url( $user ) ); // phpcs:ignore WordPress.Security.SafeRedirect
694
		exit();
695
	}
696
697
	/**
698
	 * Unlinks the current user from the linked WordPress.com user.
699
	 *
700
	 * @access public
701
	 * @static
702
	 *
703
	 * @todo Refactor to properly load the XMLRPC client independently.
704
	 *
705
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

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

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

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

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

Loading history...
786
			$api_base,
787
			$api_version
788
		);
789
	}
790
791
	/**
792
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
793
	 *
794
	 * @return String XMLRPC API URL.
795
	 */
796
	public function xmlrpc_api_url() {
797
		$base = preg_replace(
798
			'#(https?://[^?/]+)(/?.*)?$#',
799
			'\\1',
800
			Constants::get_constant( 'JETPACK__API_BASE' )
801
		);
802
		return untrailingslashit( $base ) . '/xmlrpc.php';
803
	}
804
805
	/**
806
	 * Attempts Jetpack registration which sets up the site for connection. Should
807
	 * remain public because the call to action comes from the current site, not from
808
	 * WordPress.com.
809
	 *
810
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
811
	 * @return 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
				'ABSPATH'         => Constants::get_constant( 'ABSPATH' ),
864
			)
865
		);
866
867
		$args = array(
868
			'method'  => 'POST',
869
			'body'    => $body,
870
			'headers' => array(
871
				'Accept' => 'application/json',
872
			),
873
			'timeout' => $timeout,
874
		);
875
876
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
877
878
		// TODO: fix URLs for bad hosts.
879
		$response = Client::_wp_remote_request(
880
			$this->api_url( $api_endpoint ),
881
			$args,
882
			true
883
		);
884
885
		// Make sure the response is valid and does not contain any Jetpack errors.
886
		$registration_details = $this->validate_remote_register_response( $response );
887
888
		if ( is_wp_error( $registration_details ) ) {
889
			return $registration_details;
890
		} elseif ( ! $registration_details ) {
891
			return new \WP_Error(
892
				'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...
893
				'Unknown error registering your Jetpack site.',
894
				wp_remote_retrieve_response_code( $response )
895
			);
896
		}
897
898
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
899
			return new \WP_Error(
900
				'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...
901
				'Unable to validate registration of your Jetpack site.',
902
				wp_remote_retrieve_response_code( $response )
903
			);
904
		}
905
906
		if ( isset( $registration_details->jetpack_public ) ) {
907
			$jetpack_public = (int) $registration_details->jetpack_public;
908
		} else {
909
			$jetpack_public = false;
910
		}
911
912
		\Jetpack_Options::update_options(
913
			array(
914
				'id'         => (int) $registration_details->jetpack_id,
915
				'blog_token' => (string) $registration_details->jetpack_secret,
916
				'public'     => $jetpack_public,
917
			)
918
		);
919
920
		/**
921
		 * Fires when a site is registered on WordPress.com.
922
		 *
923
		 * @since 3.7.0
924
		 *
925
		 * @param int $json->jetpack_id Jetpack Blog ID.
926
		 * @param string $json->jetpack_secret Jetpack Blog Token.
927
		 * @param int|bool $jetpack_public Is the site public.
928
		 */
929
		do_action(
930
			'jetpack_site_registered',
931
			$registration_details->jetpack_id,
932
			$registration_details->jetpack_secret,
933
			$jetpack_public
934
		);
935
936
		if ( isset( $registration_details->token ) ) {
937
			/**
938
			 * Fires when a user token is sent along with the registration data.
939
			 *
940
			 * @since 7.6.0
941
			 *
942
			 * @param object $token the administrator token for the newly registered site.
943
			 */
944
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
945
		}
946
947
		return true;
948
	}
949
950
	/**
951
	 * Takes the response from the Jetpack register new site endpoint and
952
	 * verifies it worked properly.
953
	 *
954
	 * @since 2.6
955
	 *
956
	 * @param Mixed $response the response object, or the error object.
957
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
958
	 **/
959
	protected function validate_remote_register_response( $response ) {
960
		if ( is_wp_error( $response ) ) {
961
			return new \WP_Error(
962
				'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...
963
				$response->get_error_message()
964
			);
965
		}
966
967
		$code   = wp_remote_retrieve_response_code( $response );
968
		$entity = wp_remote_retrieve_body( $response );
969
970
		if ( $entity ) {
971
			$registration_response = json_decode( $entity );
972
		} else {
973
			$registration_response = false;
974
		}
975
976
		$code_type = intval( $code / 100 );
977
		if ( 5 === $code_type ) {
978
			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...
979
		} elseif ( 408 === $code ) {
980
			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...
981
		} elseif ( ! empty( $registration_response->error ) ) {
982
			if (
983
				'xml_rpc-32700' === $registration_response->error
984
				&& ! function_exists( 'xml_parser_create' )
985
			) {
986
				$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' );
987
			} else {
988
				$error_description = isset( $registration_response->error_description )
989
					? (string) $registration_response->error_description
990
					: '';
991
			}
992
993
			return new \WP_Error(
994
				(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...
995
				$error_description,
996
				$code
997
			);
998
		} elseif ( 200 !== $code ) {
999
			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...
1000
		}
1001
1002
		// Jetpack ID error block.
1003
		if ( empty( $registration_response->jetpack_id ) ) {
1004
			return new \WP_Error(
1005
				'jetpack_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

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

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

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

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

Loading history...
1013
				/* translators: %s is an error message string */
1014
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1015
				$entity
1016
			);
1017 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1018
			return new \WP_Error(
1019
				'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...
1020
				/* translators: %s is an error message string */
1021
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1022
				$entity
1023
			);
1024
		}
1025
1026
		return $registration_response;
1027
	}
1028
1029
	/**
1030
	 * Adds a used nonce to a list of known nonces.
1031
	 *
1032
	 * @param int    $timestamp the current request timestamp.
1033
	 * @param string $nonce the nonce value.
1034
	 * @return bool whether the nonce is unique or not.
1035
	 */
1036
	public function add_nonce( $timestamp, $nonce ) {
1037
		global $wpdb;
1038
		static $nonces_used_this_request = array();
1039
1040
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
1041
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
1042
		}
1043
1044
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
1045
		$timestamp = (int) $timestamp;
1046
		$nonce     = esc_sql( $nonce );
1047
1048
		// Raw query so we can avoid races: add_option will also update.
1049
		$show_errors = $wpdb->show_errors( false );
1050
1051
		$old_nonce = $wpdb->get_row(
1052
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1053
		);
1054
1055
		if ( is_null( $old_nonce ) ) {
1056
			$return = $wpdb->query(
1057
				$wpdb->prepare(
1058
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1059
					"jetpack_nonce_{$timestamp}_{$nonce}",
1060
					time(),
1061
					'no'
1062
				)
1063
			);
1064
		} else {
1065
			$return = false;
1066
		}
1067
1068
		$wpdb->show_errors( $show_errors );
1069
1070
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1071
1072
		return $return;
1073
	}
1074
1075
	/**
1076
	 * Cleans nonces that were saved when calling ::add_nonce.
1077
	 *
1078
	 * @todo Properly prepare the query before executing it.
1079
	 *
1080
	 * @param bool $all whether to clean even non-expired nonces.
1081
	 */
1082
	public function clean_nonces( $all = false ) {
1083
		global $wpdb;
1084
1085
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1086
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1087
1088
		if ( true !== $all ) {
1089
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1090
			$sql_args[] = time() - 3600;
1091
		}
1092
1093
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1094
1095
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1096
1097
		for ( $i = 0; $i < 1000; $i++ ) {
1098
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1099
				break;
1100
			}
1101
		}
1102
	}
1103
1104
	/**
1105
	 * Sets the Connection custom capabilities.
1106
	 *
1107
	 * @param string[] $caps    Array of the user's capabilities.
1108
	 * @param string   $cap     Capability name.
1109
	 * @param int      $user_id The user ID.
1110
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1111
	 */
1112
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) {
1113
		$is_development_mode = ( new Status() )->is_development_mode();
1114
		switch ( $cap ) {
1115
			case 'jetpack_connect':
1116
			case 'jetpack_reconnect':
1117
				if ( $is_development_mode ) {
1118
					$caps = array( 'do_not_allow' );
1119
					break;
1120
				}
1121
				// Pass through. If it's not development mode, these should match disconnect.
1122
				// Let users disconnect if it's development mode, just in case things glitch.
1123
			case 'jetpack_disconnect':
1124
				/**
1125
				 * Filters the jetpack_disconnect capability.
1126
				 *
1127
				 * @since 8.7.0
1128
				 *
1129
				 * @param array An array containing the capability name.
1130
				 */
1131
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1132
				break;
1133
			case 'jetpack_connect_user':
1134
				if ( $is_development_mode ) {
1135
					$caps = array( 'do_not_allow' );
1136
					break;
1137
				}
1138
				$caps = array( 'read' );
1139
				break;
1140
		}
1141
		return $caps;
1142
	}
1143
1144
	/**
1145
	 * Builds the timeout limit for queries talking with the wpcom servers.
1146
	 *
1147
	 * Based on local php max_execution_time in php.ini
1148
	 *
1149
	 * @since 5.4
1150
	 * @return int
1151
	 **/
1152
	public function get_max_execution_time() {
1153
		$timeout = (int) ini_get( 'max_execution_time' );
1154
1155
		// Ensure exec time set in php.ini.
1156
		if ( ! $timeout ) {
1157
			$timeout = 30;
1158
		}
1159
		return $timeout;
1160
	}
1161
1162
	/**
1163
	 * Sets a minimum request timeout, and returns the current timeout
1164
	 *
1165
	 * @since 5.4
1166
	 * @param Integer $min_timeout the minimum timeout value.
1167
	 **/
1168 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1169
		$timeout = $this->get_max_execution_time();
1170
		if ( $timeout < $min_timeout ) {
1171
			$timeout = $min_timeout;
1172
			set_time_limit( $timeout );
1173
		}
1174
		return $timeout;
1175
	}
1176
1177
	/**
1178
	 * Get our assumed site creation date.
1179
	 * Calculated based on the earlier date of either:
1180
	 * - Earliest admin user registration date.
1181
	 * - Earliest date of post of any post type.
1182
	 *
1183
	 * @since 7.2.0
1184
	 *
1185
	 * @return string Assumed site creation date and time.
1186
	 */
1187
	public function get_assumed_site_creation_date() {
1188
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1189
		if ( ! empty( $cached_date ) ) {
1190
			return $cached_date;
1191
		}
1192
1193
		$earliest_registered_users  = get_users(
1194
			array(
1195
				'role'    => 'administrator',
1196
				'orderby' => 'user_registered',
1197
				'order'   => 'ASC',
1198
				'fields'  => array( 'user_registered' ),
1199
				'number'  => 1,
1200
			)
1201
		);
1202
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1203
1204
		$earliest_posts = get_posts(
1205
			array(
1206
				'posts_per_page' => 1,
1207
				'post_type'      => 'any',
1208
				'post_status'    => 'any',
1209
				'orderby'        => 'date',
1210
				'order'          => 'ASC',
1211
			)
1212
		);
1213
1214
		// If there are no posts at all, we'll count only on user registration date.
1215
		if ( $earliest_posts ) {
1216
			$earliest_post_date = $earliest_posts[0]->post_date;
1217
		} else {
1218
			$earliest_post_date = PHP_INT_MAX;
1219
		}
1220
1221
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1222
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1223
1224
		return $assumed_date;
1225
	}
1226
1227
	/**
1228
	 * Adds the activation source string as a parameter to passed arguments.
1229
	 *
1230
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1231
	 *
1232
	 * @param array $args arguments that need to have the source added.
1233
	 * @return array $amended arguments.
1234
	 */
1235 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1236
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1237
1238
		if ( $activation_source_name ) {
1239
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1240
			$args['_as'] = urlencode( $activation_source_name );
1241
		}
1242
1243
		if ( $activation_source_keyword ) {
1244
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1245
			$args['_ak'] = urlencode( $activation_source_keyword );
1246
		}
1247
1248
		return $args;
1249
	}
1250
1251
	/**
1252
	 * Returns the callable that would be used to generate secrets.
1253
	 *
1254
	 * @return Callable a function that returns a secure string to be used as a secret.
1255
	 */
1256
	protected function get_secret_callable() {
1257
		if ( ! isset( $this->secret_callable ) ) {
1258
			/**
1259
			 * Allows modification of the callable that is used to generate connection secrets.
1260
			 *
1261
			 * @param Callable a function or method that returns a secret string.
1262
			 */
1263
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', array( $this, 'secret_callable_method' ) );
1264
		}
1265
1266
		return $this->secret_callable;
1267
	}
1268
1269
	/**
1270
	 * Runs the wp_generate_password function with the required parameters. This is the
1271
	 * default implementation of the secret callable, can be overridden using the
1272
	 * jetpack_connection_secret_generator filter.
1273
	 *
1274
	 * @return String $secret value.
1275
	 */
1276
	private function secret_callable_method() {
1277
		return wp_generate_password( 32, false );
1278
	}
1279
1280
	/**
1281
	 * Generates two secret tokens and the end of life timestamp for them.
1282
	 *
1283
	 * @param String  $action  The action name.
1284
	 * @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...
1285
	 * @param Integer $exp     Expiration time in seconds.
1286
	 */
1287
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1288
		if ( false === $user_id ) {
1289
			$user_id = get_current_user_id();
1290
		}
1291
1292
		$callable = $this->get_secret_callable();
1293
1294
		$secrets = \Jetpack_Options::get_raw_option(
1295
			self::SECRETS_OPTION_NAME,
1296
			array()
1297
		);
1298
1299
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1300
1301
		if (
1302
			isset( $secrets[ $secret_name ] ) &&
1303
			$secrets[ $secret_name ]['exp'] > time()
1304
		) {
1305
			return $secrets[ $secret_name ];
1306
		}
1307
1308
		$secret_value = array(
1309
			'secret_1' => call_user_func( $callable ),
1310
			'secret_2' => call_user_func( $callable ),
1311
			'exp'      => time() + $exp,
1312
		);
1313
1314
		$secrets[ $secret_name ] = $secret_value;
1315
1316
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1317
		return $secrets[ $secret_name ];
1318
	}
1319
1320
	/**
1321
	 * Returns two secret tokens and the end of life timestamp for them.
1322
	 *
1323
	 * @param String  $action  The action name.
1324
	 * @param Integer $user_id The user identifier.
1325
	 * @return string|array an array of secrets or an error string.
1326
	 */
1327
	public function get_secrets( $action, $user_id ) {
1328
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1329
		$secrets     = \Jetpack_Options::get_raw_option(
1330
			self::SECRETS_OPTION_NAME,
1331
			array()
1332
		);
1333
1334
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1335
			return self::SECRETS_MISSING;
1336
		}
1337
1338
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1339
			$this->delete_secrets( $action, $user_id );
1340
			return self::SECRETS_EXPIRED;
1341
		}
1342
1343
		return $secrets[ $secret_name ];
1344
	}
1345
1346
	/**
1347
	 * Deletes secret tokens in case they, for example, have expired.
1348
	 *
1349
	 * @param String  $action  The action name.
1350
	 * @param Integer $user_id The user identifier.
1351
	 */
1352
	public function delete_secrets( $action, $user_id ) {
1353
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1354
		$secrets     = \Jetpack_Options::get_raw_option(
1355
			self::SECRETS_OPTION_NAME,
1356
			array()
1357
		);
1358
		if ( isset( $secrets[ $secret_name ] ) ) {
1359
			unset( $secrets[ $secret_name ] );
1360
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1361
		}
1362
	}
1363
1364
	/**
1365
	 * Deletes all connection tokens and transients from the local Jetpack site.
1366
	 * If the plugin object has been provided in the constructor, the function first checks
1367
	 * whether it's the only active connection.
1368
	 * If there are any other connections, the function will do nothing and return `false`
1369
	 * (unless `$ignore_connected_plugins` is set to `true`).
1370
	 *
1371
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1372
	 *
1373
	 * @return bool True if disconnected successfully, false otherwise.
1374
	 */
1375
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1376 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1377
			return false;
1378
		}
1379
1380
		/**
1381
		 * Fires upon the disconnect attempt.
1382
		 * Return `false` to prevent the disconnect.
1383
		 *
1384
		 * @since 8.7.0
1385
		 */
1386
		if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', true, $this ) ) {
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this.

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

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

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

Loading history...
1387
			return false;
1388
		}
1389
1390
		\Jetpack_Options::delete_option(
1391
			array(
1392
				'blog_token',
1393
				'user_token',
1394
				'user_tokens',
1395
				'master_user',
1396
				'time_diff',
1397
				'fallback_no_verify_ssl_certs',
1398
			)
1399
		);
1400
1401
		\Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
1402
1403
		// Delete cached connected user data.
1404
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1405
		delete_transient( $transient_key );
1406
1407
		// Delete all XML-RPC errors.
1408
		Error_Handler::get_instance()->delete_all_errors();
1409
1410
		return true;
1411
	}
1412
1413
	/**
1414
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1415
	 * If the plugin object has been provided in the constructor, the function first check
1416
	 * whether it's the only active connection.
1417
	 * If there are any other connections, the function will do nothing and return `false`
1418
	 * (unless `$ignore_connected_plugins` is set to `true`).
1419
	 *
1420
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1421
	 *
1422
	 * @return bool True if disconnected successfully, false otherwise.
1423
	 */
1424
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1425 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1426
			return false;
1427
		}
1428
1429
		/**
1430
		 * Fires upon the disconnect attempt.
1431
		 * Return `false` to prevent the disconnect.
1432
		 *
1433
		 * @since 8.7.0
1434
		 */
1435
		if ( ! apply_filters( 'jetpack_connection_disconnect_site_wpcom', true, $this ) ) {
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this.

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

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

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

Loading history...
1436
			return false;
1437
		}
1438
1439
		$xml = new \Jetpack_IXR_Client();
1440
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1441
1442
		return true;
1443
	}
1444
1445
	/**
1446
	 * Disconnect the plugin and remove the tokens.
1447
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1448
	 * This is a proxy method to simplify the Connection package API.
1449
	 *
1450
	 * @see Manager::disable_plugin()
1451
	 * @see Manager::disconnect_site_wpcom()
1452
	 * @see Manager::delete_all_connection_tokens()
1453
	 *
1454
	 * @return bool
1455
	 */
1456
	public function remove_connection() {
1457
		$this->disable_plugin();
1458
		$this->disconnect_site_wpcom();
1459
		$this->delete_all_connection_tokens();
1460
1461
		return true;
1462
	}
1463
1464
	/**
1465
	 * Responds to a WordPress.com call to register the current site.
1466
	 * Should be changed to protected.
1467
	 *
1468
	 * @param array $registration_data Array of [ secret_1, user_id ].
1469
	 */
1470
	public function handle_registration( array $registration_data ) {
1471
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1472
		if ( empty( $registration_user_id ) ) {
1473
			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...
1474
		}
1475
1476
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1477
	}
1478
1479
	/**
1480
	 * Verify a Previously Generated Secret.
1481
	 *
1482
	 * @param string $action   The type of secret to verify.
1483
	 * @param string $secret_1 The secret string to compare to what is stored.
1484
	 * @param int    $user_id  The user ID of the owner of the secret.
1485
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1486
	 */
1487
	public function verify_secrets( $action, $secret_1, $user_id ) {
1488
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1489
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1490
			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...
1491
		}
1492
1493
		$user = get_user_by( 'id', $user_id );
1494
1495
		/**
1496
		 * We've begun verifying the previously generated secret.
1497
		 *
1498
		 * @since 7.5.0
1499
		 *
1500
		 * @param string   $action The type of secret to verify.
1501
		 * @param \WP_User $user The user object.
1502
		 */
1503
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1504
1505
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1506
			/**
1507
			 * Verifying of the previously generated secret has failed.
1508
			 *
1509
			 * @since 7.5.0
1510
			 *
1511
			 * @param string    $action  The type of secret to verify.
1512
			 * @param \WP_User  $user The user object.
1513
			 * @param \WP_Error $error The error object.
1514
			 */
1515
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1516
1517
			return $error;
1518
		};
1519
1520
		$stored_secrets = $this->get_secrets( $action, $user_id );
1521
		$this->delete_secrets( $action, $user_id );
1522
1523
		$error = null;
1524
		if ( empty( $secret_1 ) ) {
1525
			$error = $return_error(
1526
				new \WP_Error(
1527
					'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...
1528
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1529
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1530
					400
1531
				)
1532
			);
1533
		} elseif ( ! is_string( $secret_1 ) ) {
1534
			$error = $return_error(
1535
				new \WP_Error(
1536
					'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...
1537
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1538
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1539
					400
1540
				)
1541
			);
1542
		} elseif ( empty( $user_id ) ) {
1543
			// $user_id is passed around during registration as "state".
1544
			$error = $return_error(
1545
				new \WP_Error(
1546
					'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...
1547
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1548
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1549
					400
1550
				)
1551
			);
1552
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1553
			$error = $return_error(
1554
				new \WP_Error(
1555
					'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...
1556
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1557
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1558
					400
1559
				)
1560
			);
1561
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1562
			$error = $return_error(
1563
				new \WP_Error(
1564
					'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...
1565
					__( 'Verification secrets not found', 'jetpack' ),
1566
					400
1567
				)
1568
			);
1569
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1570
			$error = $return_error(
1571
				new \WP_Error(
1572
					'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...
1573
					__( 'Verification took too long', 'jetpack' ),
1574
					400
1575
				)
1576
			);
1577
		} elseif ( ! $stored_secrets ) {
1578
			$error = $return_error(
1579
				new \WP_Error(
1580
					'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...
1581
					__( 'Verification secrets are empty', 'jetpack' ),
1582
					400
1583
				)
1584
			);
1585
		} elseif ( is_wp_error( $stored_secrets ) ) {
1586
			$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...
1587
			$error = $return_error( $stored_secrets );
1588
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1589
			$error = $return_error(
1590
				new \WP_Error(
1591
					'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...
1592
					__( 'Verification secrets are incomplete', 'jetpack' ),
1593
					400
1594
				)
1595
			);
1596
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1597
			$error = $return_error(
1598
				new \WP_Error(
1599
					'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...
1600
					__( 'Secret mismatch', 'jetpack' ),
1601
					400
1602
				)
1603
			);
1604
		}
1605
1606
		// Something went wrong during the checks, returning the error.
1607
		if ( ! empty( $error ) ) {
1608
			return $error;
1609
		}
1610
1611
		/**
1612
		 * We've succeeded at verifying the previously generated secret.
1613
		 *
1614
		 * @since 7.5.0
1615
		 *
1616
		 * @param string   $action The type of secret to verify.
1617
		 * @param \WP_User $user The user object.
1618
		 */
1619
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1620
1621
		return $stored_secrets['secret_2'];
1622
	}
1623
1624
	/**
1625
	 * Responds to a WordPress.com call to authorize the current user.
1626
	 * Should be changed to protected.
1627
	 */
1628
	public function handle_authorization() {
1629
1630
	}
1631
1632
	/**
1633
	 * Obtains the auth token.
1634
	 *
1635
	 * @param array $data The request data.
1636
	 * @return object|\WP_Error Returns the auth token on success.
1637
	 *                          Returns a \WP_Error on failure.
1638
	 */
1639
	public function get_token( $data ) {
1640
		$roles = new Roles();
1641
		$role  = $roles->translate_current_user_to_role();
1642
1643
		if ( ! $role ) {
1644
			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...
1645
		}
1646
1647
		$client_secret = $this->get_access_token();
1648
		if ( ! $client_secret ) {
1649
			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...
1650
		}
1651
1652
		/**
1653
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1654
		 * data processing.
1655
		 *
1656
		 * @since 8.0.0
1657
		 *
1658
		 * @param string $redirect_url Defaults to the site admin URL.
1659
		 */
1660
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1661
1662
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1663
1664
		/**
1665
		* Filter the URL to redirect the user back to when the authentication process
1666
		* is complete.
1667
		*
1668
		* @since 8.0.0
1669
		*
1670
		* @param string $redirect_url Defaults to the site URL.
1671
		*/
1672
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1673
1674
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1675
			? $data['redirect_uri']
1676
			: add_query_arg(
1677
				array(
1678
					'action'   => 'authorize',
1679
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1680
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1681
				),
1682
				esc_url( $processing_url )
1683
			);
1684
1685
		/**
1686
		 * Filters the token request data.
1687
		 *
1688
		 * @since 8.0.0
1689
		 *
1690
		 * @param array $request_data request data.
1691
		 */
1692
		$body = apply_filters(
1693
			'jetpack_token_request_body',
1694
			array(
1695
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1696
				'client_secret' => $client_secret->secret,
1697
				'grant_type'    => 'authorization_code',
1698
				'code'          => $data['code'],
1699
				'redirect_uri'  => $redirect_uri,
1700
			)
1701
		);
1702
1703
		$args = array(
1704
			'method'  => 'POST',
1705
			'body'    => $body,
1706
			'headers' => array(
1707
				'Accept' => 'application/json',
1708
			),
1709
		);
1710
1711
		add_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1712
		$response = Client::_wp_remote_request( Utils::fix_url_for_bad_hosts( $this->api_url( 'token' ) ), $args );
1713
		remove_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1714
1715
		if ( is_wp_error( $response ) ) {
1716
			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...
1717
		}
1718
1719
		$code   = wp_remote_retrieve_response_code( $response );
1720
		$entity = wp_remote_retrieve_body( $response );
1721
1722
		if ( $entity ) {
1723
			$json = json_decode( $entity );
1724
		} else {
1725
			$json = false;
1726
		}
1727
1728
		if ( 200 !== $code || ! empty( $json->error ) ) {
1729
			if ( empty( $json->error ) ) {
1730
				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...
1731
			}
1732
1733
			/* translators: Error description string. */
1734
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1735
1736
			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...
1737
		}
1738
1739
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1740
			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...
1741
		}
1742
1743
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1744
			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...
1745
		}
1746
1747
		if ( empty( $json->scope ) ) {
1748
			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...
1749
		}
1750
1751
		// TODO: get rid of the error silencer.
1752
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1753
		@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...
1754
		if ( empty( $role ) || empty( $hmac ) ) {
1755
			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...
1756
		}
1757
1758
		if ( $this->sign_role( $role ) !== $json->scope ) {
1759
			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...
1760
		}
1761
1762
		$cap = $roles->translate_role_to_cap( $role );
1763
		if ( ! $cap ) {
1764
			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...
1765
		}
1766
1767
		if ( ! current_user_can( $cap ) ) {
1768
			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...
1769
		}
1770
1771
		/**
1772
		 * Fires after user has successfully received an auth token.
1773
		 *
1774
		 * @since 3.9.0
1775
		 */
1776
		do_action( 'jetpack_user_authorized' );
1777
1778
		return (string) $json->access_token;
1779
	}
1780
1781
	/**
1782
	 * Increases the request timeout value to 30 seconds.
1783
	 *
1784
	 * @return int Returns 30.
1785
	 */
1786
	public function increase_timeout() {
1787
		return 30;
1788
	}
1789
1790
	/**
1791
	 * Builds a URL to the Jetpack connection auth page.
1792
	 *
1793
	 * @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...
1794
	 * @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...
1795
	 * @return string Connect URL.
1796
	 */
1797
	public function get_authorization_url( $user = null, $redirect = null ) {
1798
1799
		if ( empty( $user ) ) {
1800
			$user = wp_get_current_user();
1801
		}
1802
1803
		$roles       = new Roles();
1804
		$role        = $roles->translate_user_to_role( $user );
1805
		$signed_role = $this->sign_role( $role );
1806
1807
		/**
1808
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1809
		 * data processing.
1810
		 *
1811
		 * @since 8.0.0
1812
		 *
1813
		 * @param string $redirect_url Defaults to the site admin URL.
1814
		 */
1815
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1816
1817
		/**
1818
		 * Filter the URL to redirect the user back to when the authorization process
1819
		 * is complete.
1820
		 *
1821
		 * @since 8.0.0
1822
		 *
1823
		 * @param string $redirect_url Defaults to the site URL.
1824
		 */
1825
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1826
1827
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1828
1829
		/**
1830
		 * Filter the type of authorization.
1831
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1832
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1833
		 *
1834
		 * @since 4.3.3
1835
		 *
1836
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1837
		 */
1838
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1839
1840
		/**
1841
		 * Filters the user connection request data for additional property addition.
1842
		 *
1843
		 * @since 8.0.0
1844
		 *
1845
		 * @param array $request_data request data.
1846
		 */
1847
		$body = apply_filters(
1848
			'jetpack_connect_request_body',
1849
			array(
1850
				'response_type' => 'code',
1851
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1852
				'redirect_uri'  => add_query_arg(
1853
					array(
1854
						'action'   => 'authorize',
1855
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1856
						'redirect' => rawurlencode( $redirect ),
1857
					),
1858
					esc_url( $processing_url )
1859
				),
1860
				'state'         => $user->ID,
1861
				'scope'         => $signed_role,
1862
				'user_email'    => $user->user_email,
1863
				'user_login'    => $user->user_login,
1864
				'is_active'     => $this->is_active(),
1865
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1866
				'auth_type'     => $auth_type,
1867
				'secret'        => $secrets['secret_1'],
1868
				'blogname'      => get_option( 'blogname' ),
1869
				'site_url'      => site_url(),
1870
				'home_url'      => home_url(),
1871
				'site_icon'     => get_site_icon_url(),
1872
				'site_lang'     => get_locale(),
1873
				'site_created'  => $this->get_assumed_site_creation_date(),
1874
			)
1875
		);
1876
1877
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1878
1879
		$api_url = $this->api_url( 'authorize' );
1880
1881
		return add_query_arg( $body, $api_url );
1882
	}
1883
1884
	/**
1885
	 * Authorizes the user by obtaining and storing the user token.
1886
	 *
1887
	 * @param array $data The request data.
1888
	 * @return string|\WP_Error Returns a string on success.
1889
	 *                          Returns a \WP_Error on failure.
1890
	 */
1891
	public function authorize( $data = array() ) {
1892
		/**
1893
		 * Action fired when user authorization starts.
1894
		 *
1895
		 * @since 8.0.0
1896
		 */
1897
		do_action( 'jetpack_authorize_starting' );
1898
1899
		$roles = new Roles();
1900
		$role  = $roles->translate_current_user_to_role();
1901
1902
		if ( ! $role ) {
1903
			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...
1904
		}
1905
1906
		$cap = $roles->translate_role_to_cap( $role );
1907
		if ( ! $cap ) {
1908
			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...
1909
		}
1910
1911
		if ( ! empty( $data['error'] ) ) {
1912
			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...
1913
		}
1914
1915
		if ( ! isset( $data['state'] ) ) {
1916
			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...
1917
		}
1918
1919
		if ( ! ctype_digit( $data['state'] ) ) {
1920
			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...
1921
		}
1922
1923
		$current_user_id = get_current_user_id();
1924
		if ( $current_user_id !== (int) $data['state'] ) {
1925
			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...
1926
		}
1927
1928
		if ( empty( $data['code'] ) ) {
1929
			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...
1930
		}
1931
1932
		$token = $this->get_token( $data );
1933
1934 View Code Duplication
		if ( is_wp_error( $token ) ) {
1935
			$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...
1936
			if ( empty( $code ) ) {
1937
				$code = 'invalid_token';
1938
			}
1939
			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...
1940
		}
1941
1942
		if ( ! $token ) {
1943
			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...
1944
		}
1945
1946
		$is_master_user = ! $this->is_active();
1947
1948
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
1949
1950
		if ( ! $is_master_user ) {
1951
			/**
1952
			 * Action fired when a secondary user has been authorized.
1953
			 *
1954
			 * @since 8.0.0
1955
			 */
1956
			do_action( 'jetpack_authorize_ending_linked' );
1957
			return 'linked';
1958
		}
1959
1960
		/**
1961
		 * Action fired when the master user has been authorized.
1962
		 *
1963
		 * @since 8.0.0
1964
		 *
1965
		 * @param array $data The request data.
1966
		 */
1967
		do_action( 'jetpack_authorize_ending_authorized', $data );
1968
1969
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
1970
1971
		// Start nonce cleaner.
1972
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
1973
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
1974
1975
		return 'authorized';
1976
	}
1977
1978
	/**
1979
	 * Disconnects from the Jetpack servers.
1980
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1981
	 */
1982
	public function disconnect_site() {
1983
1984
	}
1985
1986
	/**
1987
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1988
	 *
1989
	 * @param string $text The string to hash.
1990
	 * @return string
1991
	 */
1992
	public function sha1_base64( $text ) {
1993
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1994
	}
1995
1996
	/**
1997
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1998
	 *
1999
	 * @param string $domain The domain to check.
2000
	 *
2001
	 * @return bool|WP_Error
2002
	 */
2003
	public function is_usable_domain( $domain ) {
2004
2005
		// If it's empty, just fail out.
2006
		if ( ! $domain ) {
2007
			return new \WP_Error(
2008
				'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...
2009
				/* translators: %1$s is a domain name. */
2010
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
2011
			);
2012
		}
2013
2014
		/**
2015
		 * Skips the usuable domain check when connecting a site.
2016
		 *
2017
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
2018
		 *
2019
		 * @since 4.1.0
2020
		 *
2021
		 * @param bool If the check should be skipped. Default false.
2022
		 */
2023
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
2024
			return true;
2025
		}
2026
2027
		// None of the explicit localhosts.
2028
		$forbidden_domains = array(
2029
			'wordpress.com',
2030
			'localhost',
2031
			'localhost.localdomain',
2032
			'127.0.0.1',
2033
			'local.wordpress.test',         // VVV pattern.
2034
			'local.wordpress-trunk.test',   // VVV pattern.
2035
			'src.wordpress-develop.test',   // VVV pattern.
2036
			'build.wordpress-develop.test', // VVV pattern.
2037
		);
2038 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
2039
			return new \WP_Error(
2040
				'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...
2041
				sprintf(
2042
					/* translators: %1$s is a domain name. */
2043
					__(
2044
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
2045
						'jetpack'
2046
					),
2047
					$domain
2048
				)
2049
			);
2050
		}
2051
2052
		// No .test or .local domains.
2053 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
2054
			return new \WP_Error(
2055
				'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...
2056
				sprintf(
2057
					/* translators: %1$s is a domain name. */
2058
					__(
2059
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
2060
						'jetpack'
2061
					),
2062
					$domain
2063
				)
2064
			);
2065
		}
2066
2067
		// No WPCOM subdomains.
2068 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
2069
			return new \WP_Error(
2070
				'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...
2071
				sprintf(
2072
					/* translators: %1$s is a domain name. */
2073
					__(
2074
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
2075
						'jetpack'
2076
					),
2077
					$domain
2078
				)
2079
			);
2080
		}
2081
2082
		// If PHP was compiled without support for the Filter module (very edge case).
2083
		if ( ! function_exists( 'filter_var' ) ) {
2084
			// Just pass back true for now, and let wpcom sort it out.
2085
			return true;
2086
		}
2087
2088
		return true;
2089
	}
2090
2091
	/**
2092
	 * Gets the requested token.
2093
	 *
2094
	 * Tokens are one of two types:
2095
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
2096
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
2097
	 *    are not associated with a user account. They represent the site's connection with
2098
	 *    the Jetpack servers.
2099
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
2100
	 *
2101
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
2102
	 * token, and $private is a secret that should never be displayed anywhere or sent
2103
	 * over the network; it's used only for signing things.
2104
	 *
2105
	 * Blog Tokens can be "Normal" or "Special".
2106
	 * * Normal: The result of a normal connection flow. They look like
2107
	 *   "{$random_string_1}.{$random_string_2}"
2108
	 *   That is, $token_key and $private are both random strings.
2109
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
2110
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
2111
	 *   constant (rare).
2112
	 * * Special: A connection token for sites that have gone through an alternative
2113
	 *   connection flow. They look like:
2114
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
2115
	 *   That is, $private is a random string and $token_key has a special structure with
2116
	 *   lots of semicolons.
2117
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
2118
	 *   JETPACK_BLOG_TOKEN constant.
2119
	 *
2120
	 * In particular, note that Normal Blog Tokens never start with ";" and that
2121
	 * Special Blog Tokens always do.
2122
	 *
2123
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
2124
	 * order:
2125
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
2126
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
2127
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
2128
	 *
2129
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
2130
	 * @param string|false $token_key If provided, check that the token matches the provided input.
2131
	 * @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.
2132
	 *
2133
	 * @return object|false
2134
	 */
2135
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
2136
		$possible_special_tokens = array();
2137
		$possible_normal_tokens  = array();
2138
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
2139
2140
		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...
2141
			if ( ! $user_tokens ) {
2142
				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...
2143
			}
2144
			if ( self::JETPACK_MASTER_USER === $user_id ) {
2145
				$user_id = \Jetpack_Options::get_option( 'master_user' );
2146
				if ( ! $user_id ) {
2147
					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...
2148
				}
2149
			}
2150
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
2151
				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...
2152
			}
2153
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
2154 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
2155
				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...
2156
			}
2157 View Code Duplication
			if ( $user_token_chunks[2] !== (string) $user_id ) {
2158
				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...
2159
			}
2160
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
2161
		} else {
2162
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
2163
			if ( $stored_blog_token ) {
2164
				$possible_normal_tokens[] = $stored_blog_token;
2165
			}
2166
2167
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
2168
2169
			if ( $defined_tokens_string ) {
2170
				$defined_tokens = explode( ',', $defined_tokens_string );
2171
				foreach ( $defined_tokens as $defined_token ) {
2172
					if ( ';' === $defined_token[0] ) {
2173
						$possible_special_tokens[] = $defined_token;
2174
					} else {
2175
						$possible_normal_tokens[] = $defined_token;
2176
					}
2177
				}
2178
			}
2179
		}
2180
2181
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2182
			$possible_tokens = $possible_normal_tokens;
2183
		} else {
2184
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
2185
		}
2186
2187
		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...
2188
			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...
2189
		}
2190
2191
		$valid_token = false;
2192
2193
		if ( false === $token_key ) {
2194
			// Use first token.
2195
			$valid_token = $possible_tokens[0];
2196
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2197
			// Use first normal token.
2198
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
2199
		} else {
2200
			// Use the token matching $token_key or false if none.
2201
			// Ensure we check the full key.
2202
			$token_check = rtrim( $token_key, '.' ) . '.';
2203
2204
			foreach ( $possible_tokens as $possible_token ) {
2205
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
2206
					$valid_token = $possible_token;
2207
					break;
2208
				}
2209
			}
2210
		}
2211
2212
		if ( ! $valid_token ) {
2213
			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...
2214
		}
2215
2216
		return (object) array(
2217
			'secret'           => $valid_token,
2218
			'external_user_id' => (int) $user_id,
2219
		);
2220
	}
2221
2222
	/**
2223
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2224
	 * since it is passed by reference to various methods.
2225
	 * Capture it here so we can verify the signature later.
2226
	 *
2227
	 * @param array $methods an array of available XMLRPC methods.
2228
	 * @return array the same array, since this method doesn't add or remove anything.
2229
	 */
2230
	public function xmlrpc_methods( $methods ) {
2231
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
2232
		return $methods;
2233
	}
2234
2235
	/**
2236
	 * Resets the raw post data parameter for testing purposes.
2237
	 */
2238
	public function reset_raw_post_data() {
2239
		$this->raw_post_data = null;
2240
	}
2241
2242
	/**
2243
	 * Registering an additional method.
2244
	 *
2245
	 * @param array $methods an array of available XMLRPC methods.
2246
	 * @return array the amended array in case the method is added.
2247
	 */
2248
	public function public_xmlrpc_methods( $methods ) {
2249
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2250
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2251
		}
2252
		return $methods;
2253
	}
2254
2255
	/**
2256
	 * Handles a getOptions XMLRPC method call.
2257
	 *
2258
	 * @param array $args method call arguments.
2259
	 * @return an amended XMLRPC server options array.
2260
	 */
2261
	public function jetpack_get_options( $args ) {
2262
		global $wp_xmlrpc_server;
2263
2264
		$wp_xmlrpc_server->escape( $args );
2265
2266
		$username = $args[1];
2267
		$password = $args[2];
2268
2269
		$user = $wp_xmlrpc_server->login( $username, $password );
2270
		if ( ! $user ) {
2271
			return $wp_xmlrpc_server->error;
2272
		}
2273
2274
		$options   = array();
2275
		$user_data = $this->get_connected_user_data();
2276
		if ( is_array( $user_data ) ) {
2277
			$options['jetpack_user_id']         = array(
2278
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2279
				'readonly' => true,
2280
				'value'    => $user_data['ID'],
2281
			);
2282
			$options['jetpack_user_login']      = array(
2283
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2284
				'readonly' => true,
2285
				'value'    => $user_data['login'],
2286
			);
2287
			$options['jetpack_user_email']      = array(
2288
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2289
				'readonly' => true,
2290
				'value'    => $user_data['email'],
2291
			);
2292
			$options['jetpack_user_site_count'] = array(
2293
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2294
				'readonly' => true,
2295
				'value'    => $user_data['site_count'],
2296
			);
2297
		}
2298
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2299
		$args                           = stripslashes_deep( $args );
2300
		return $wp_xmlrpc_server->wp_getOptions( $args );
2301
	}
2302
2303
	/**
2304
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2305
	 *
2306
	 * @param array $options standard Core options.
2307
	 * @return array amended options.
2308
	 */
2309
	public function xmlrpc_options( $options ) {
2310
		$jetpack_client_id = false;
2311
		if ( $this->is_active() ) {
2312
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2313
		}
2314
		$options['jetpack_version'] = array(
2315
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2316
			'readonly' => true,
2317
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2318
		);
2319
2320
		$options['jetpack_client_id'] = array(
2321
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2322
			'readonly' => true,
2323
			'value'    => $jetpack_client_id,
2324
		);
2325
		return $options;
2326
	}
2327
2328
	/**
2329
	 * Resets the saved authentication state in between testing requests.
2330
	 */
2331
	public function reset_saved_auth_state() {
2332
		$this->xmlrpc_verification = null;
2333
	}
2334
2335
	/**
2336
	 * Sign a user role with the master access token.
2337
	 * If not specified, will default to the current user.
2338
	 *
2339
	 * @access public
2340
	 *
2341
	 * @param string $role    User role.
2342
	 * @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...
2343
	 * @return string Signed user role.
2344
	 */
2345
	public function sign_role( $role, $user_id = null ) {
2346
		if ( empty( $user_id ) ) {
2347
			$user_id = (int) get_current_user_id();
2348
		}
2349
2350
		if ( ! $user_id ) {
2351
			return false;
2352
		}
2353
2354
		$token = $this->get_access_token();
2355
		if ( ! $token || is_wp_error( $token ) ) {
2356
			return false;
2357
		}
2358
2359
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2360
	}
2361
2362
	/**
2363
	 * Set the plugin instance.
2364
	 *
2365
	 * @param Plugin $plugin_instance The plugin instance.
2366
	 *
2367
	 * @return $this
2368
	 */
2369
	public function set_plugin_instance( Plugin $plugin_instance ) {
2370
		$this->plugin = $plugin_instance;
2371
2372
		return $this;
2373
	}
2374
2375
	/**
2376
	 * Retrieve the plugin management object.
2377
	 *
2378
	 * @return Plugin
2379
	 */
2380
	public function get_plugin() {
2381
		return $this->plugin;
2382
	}
2383
2384
	/**
2385
	 * Get all connected plugins information, excluding those disconnected by user.
2386
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2387
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2388
	 * so please make sure not to run the method too early in the code.
2389
	 *
2390
	 * @return array|WP_Error
2391
	 */
2392
	public function get_connected_plugins() {
2393
		$maybe_plugins = Plugin_Storage::get_all( true );
2394
2395
		if ( $maybe_plugins instanceof WP_Error ) {
2396
			return $maybe_plugins;
2397
		}
2398
2399
		return $maybe_plugins;
2400
	}
2401
2402
	/**
2403
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2404
	 * Note: this method does not remove any access tokens.
2405
	 *
2406
	 * @return bool
2407
	 */
2408
	public function disable_plugin() {
2409
		if ( ! $this->plugin ) {
2410
			return false;
2411
		}
2412
2413
		return $this->plugin->disable();
2414
	}
2415
2416
	/**
2417
	 * Force plugin reconnect after user-initiated disconnect.
2418
	 * After its called, the plugin will be allowed to use the connection again.
2419
	 * Note: this method does not initialize access tokens.
2420
	 *
2421
	 * @return bool
2422
	 */
2423
	public function enable_plugin() {
2424
		if ( ! $this->plugin ) {
2425
			return false;
2426
		}
2427
2428
		return $this->plugin->enable();
2429
	}
2430
2431
	/**
2432
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2433
	 * If no plugin slug was passed into the constructor, always returns true.
2434
	 *
2435
	 * @return bool
2436
	 */
2437
	public function is_plugin_enabled() {
2438
		if ( ! $this->plugin ) {
2439
			return true;
2440
		}
2441
2442
		return $this->plugin->is_enabled();
2443
	}
2444
2445
}
2446