Completed
Push — update/jitm_jetpack_is_mobile ( 9d9d1e...df4eca )
by
unknown
106:06 queued 94:29
created

Manager::try_registration()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 10
nop 1
dl 0
loc 39
rs 8.6737
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\Heartbeat;
12
use Automattic\Jetpack\Roles;
13
use Automattic\Jetpack\Status;
14
use Automattic\Jetpack\Terms_Of_Service;
15
use Automattic\Jetpack\Tracking;
16
use WP_Error;
17
use WP_User;
18
19
/**
20
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
21
 * and Jetpack.
22
 */
23
class Manager {
24
	/**
25
	 * A copy of the raw POST data for signature verification purposes.
26
	 *
27
	 * @var String
28
	 */
29
	protected $raw_post_data;
30
31
	/**
32
	 * Verification data needs to be stored to properly verify everything.
33
	 *
34
	 * @var Object
35
	 */
36
	private $xmlrpc_verification = null;
37
38
	/**
39
	 * Plugin management object.
40
	 *
41
	 * @var Plugin
42
	 */
43
	private $plugin = null;
44
45
	/**
46
	 * Holds extra parameters that will be sent along in the register request body.
47
	 *
48
	 * Use Manager::add_register_request_param to add values to this array.
49
	 *
50
	 * @since 9.7.0
51
	 * @var array
52
	 */
53
	private static $extra_register_params = array();
54
55
	/**
56
	 * Initialize the object.
57
	 * Make sure to call the "Configure" first.
58
	 *
59
	 * @param string $plugin_slug Slug of the plugin using the connection (optional, but encouraged).
0 ignored issues
show
Documentation introduced by
Should the type for parameter $plugin_slug not be string|null?

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

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

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

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

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

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

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

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
65
			$this->set_plugin_instance( new Plugin( $plugin_slug ) );
66
		}
67
	}
68
69
	/**
70
	 * Initializes required listeners. This is done separately from the constructors
71
	 * because some objects sometimes need to instantiate separate objects of this class.
72
	 *
73
	 * @todo Implement a proper nonce verification.
74
	 */
75
	public static function configure() {
76
		$manager = new self();
77
78
		add_filter(
79
			'jetpack_constant_default_value',
80
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
81
			10,
82
			2
83
		);
84
85
		$manager->setup_xmlrpc_handlers(
86
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
87
			$manager->has_connected_owner(),
88
			$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...
89
		);
90
91
		$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...
92
93
		if ( $manager->is_connected() ) {
94
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
95
		}
96
97
		add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
98
99
		( new Nonce_Handler() )->init_schedule();
100
101
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
102
103
		add_filter( 'map_meta_cap', array( $manager, 'jetpack_connection_custom_caps' ), 1, 4 );
104
105
		Heartbeat::init();
106
		add_filter( 'jetpack_heartbeat_stats_array', array( $manager, 'add_stats_to_heartbeat' ) );
107
108
		Webhooks::init( $manager );
109
	}
110
111
	/**
112
	 * Sets up the XMLRPC request handlers.
113
	 *
114
	 * @since 9.6.0 Deprecate $is_active param.
115
	 *
116
	 * @param array                  $request_params incoming request parameters.
117
	 * @param bool                   $has_connected_owner Whether the site has a connected owner.
118
	 * @param bool                   $is_signed whether the signature check has been successful.
119
	 * @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...
120
	 */
121
	public function setup_xmlrpc_handlers(
122
		$request_params,
123
		$has_connected_owner,
124
		$is_signed,
125
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
126
	) {
127
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
128
129
		if (
130
			! isset( $request_params['for'] )
131
			|| 'jetpack' !== $request_params['for']
132
		) {
133
			return false;
134
		}
135
136
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
137
		if (
138
			isset( $request_params['jetpack'] )
139
			&& 'comms' === $request_params['jetpack']
140
		) {
141
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
142
				// Use the real constant here for WordPress' sake.
143
				define( 'XMLRPC_REQUEST', true );
144
			}
145
146
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
147
148
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
149
		}
150
151
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
152
			return false;
153
		}
154
		// Display errors can cause the XML to be not well formed.
155
		@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...
156
157
		if ( $xmlrpc_server ) {
158
			$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...
159
		} else {
160
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
161
		}
162
163
		$this->require_jetpack_authentication();
164
165
		if ( $is_signed ) {
166
			// If the site is connected either at a site or user level and the request is signed, expose the methods.
167
			// The callback is responsible to determine whether the request is signed with blog or user token and act accordingly.
168
			// The actual API methods.
169
			$callback = array( $this->xmlrpc_server, 'xmlrpc_methods' );
170
171
			// Hack to preserve $HTTP_RAW_POST_DATA.
172
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
173
174
		} elseif ( $has_connected_owner && ! $is_signed ) {
175
			// The jetpack.authorize method should be available for unauthenticated users on a site with an
176
			// active Jetpack connection, so that additional users can link their account.
177
			$callback = array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' );
178
179
		} else {
180
			// Any other unsigned request should expose the bootstrap methods.
181
			$callback = array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' );
182
			new XMLRPC_Connector( $this );
183
		}
184
185
		add_filter( 'xmlrpc_methods', $callback );
186
187
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
188
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
189
		return true;
190
	}
191
192
	/**
193
	 * Initializes the REST API connector on the init hook.
194
	 */
195
	public function initialize_rest_api_registration_connector() {
196
		new REST_Connector( $this );
197
	}
198
199
	/**
200
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
201
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
202
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
203
	 * which is accessible via a different URI. Most of the below is copied directly
204
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
205
	 *
206
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
207
	 */
208
	public function alternate_xmlrpc() {
209
		// Some browser-embedded clients send cookies. We don't want them.
210
		$_COOKIE = array();
211
212
		include_once ABSPATH . 'wp-admin/includes/admin.php';
213
		include_once ABSPATH . WPINC . '/class-IXR.php';
214
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
215
216
		/**
217
		 * Filters the class used for handling XML-RPC requests.
218
		 *
219
		 * @since 3.1.0
220
		 *
221
		 * @param string $class The name of the XML-RPC server class.
222
		 */
223
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
224
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
225
226
		// Fire off the request.
227
		nocache_headers();
228
		$wp_xmlrpc_server->serve_request();
229
230
		exit;
231
	}
232
233
	/**
234
	 * Removes all XML-RPC methods that are not `jetpack.*`.
235
	 * Only used in our alternate XML-RPC endpoint, where we want to
236
	 * ensure that Core and other plugins' methods are not exposed.
237
	 *
238
	 * @param array $methods a list of registered WordPress XMLRPC methods.
239
	 * @return array filtered $methods
240
	 */
241
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
242
		$jetpack_methods = array();
243
244
		foreach ( $methods as $method => $callback ) {
245
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
246
				$jetpack_methods[ $method ] = $callback;
247
			}
248
		}
249
250
		return $jetpack_methods;
251
	}
252
253
	/**
254
	 * Removes all other authentication methods not to allow other
255
	 * methods to validate unauthenticated requests.
256
	 */
257
	public function require_jetpack_authentication() {
258
		// Don't let anyone authenticate.
259
		$_COOKIE = array();
260
		remove_all_filters( 'authenticate' );
261
		remove_all_actions( 'wp_login_failed' );
262
263
		if ( $this->is_connected() ) {
264
			// Allow Jetpack authentication.
265
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
266
		}
267
	}
268
269
	/**
270
	 * Authenticates XML-RPC and other requests from the Jetpack Server
271
	 *
272
	 * @param WP_User|Mixed $user user object if authenticated.
273
	 * @param String        $username username.
274
	 * @param String        $password password string.
275
	 * @return WP_User|Mixed authenticated user or error.
276
	 */
277
	public function authenticate_jetpack( $user, $username, $password ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
278
		if ( is_a( $user, '\\WP_User' ) ) {
279
			return $user;
280
		}
281
282
		$token_details = $this->verify_xml_rpc_signature();
283
284
		if ( ! $token_details ) {
285
			return $user;
286
		}
287
288
		if ( 'user' !== $token_details['type'] ) {
289
			return $user;
290
		}
291
292
		if ( ! $token_details['user_id'] ) {
293
			return $user;
294
		}
295
296
		nocache_headers();
297
298
		return new \WP_User( $token_details['user_id'] );
299
	}
300
301
	/**
302
	 * Verifies the signature of the current request.
303
	 *
304
	 * @return false|array
305
	 */
306
	public function verify_xml_rpc_signature() {
307
		if ( is_null( $this->xmlrpc_verification ) ) {
308
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
309
310
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
311
				/**
312
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
313
				 *
314
				 * @since 7.5.0
315
				 *
316
				 * @param WP_Error $signature_verification_error The verification error
317
				 */
318
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
319
320
				Error_Handler::get_instance()->report_error( $this->xmlrpc_verification );
321
322
			}
323
		}
324
325
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
326
	}
327
328
	/**
329
	 * Verifies the signature of the current request.
330
	 *
331
	 * This function has side effects and should not be used. Instead,
332
	 * use the memoized version `->verify_xml_rpc_signature()`.
333
	 *
334
	 * @internal
335
	 * @todo Refactor to use proper nonce verification.
336
	 */
337
	private function internal_verify_xml_rpc_signature() {
338
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
339
		// It's not for us.
340
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
341
			return false;
342
		}
343
344
		$signature_details = array(
345
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
346
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
347
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
348
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
349
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
350
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
351
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
352
		);
353
354
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
355
		@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...
356
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
357
358
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
359
360
		if (
361
			empty( $token_key )
362
		||
363
			empty( $version ) || (string) $jetpack_api_version !== $version ) {
364
			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...
365
		}
366
367
		if ( '0' === $user_id ) {
368
			$token_type = 'blog';
369
			$user_id    = 0;
370
		} else {
371
			$token_type = 'user';
372
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
373
				return new \WP_Error(
374
					'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...
375
					'Malformed user_id in request',
376
					compact( 'signature_details' )
377
				);
378
			}
379
			$user_id = (int) $user_id;
380
381
			$user = new \WP_User( $user_id );
382
			if ( ! $user || ! $user->exists() ) {
383
				return new \WP_Error(
384
					'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...
385
					sprintf( 'User %d does not exist', $user_id ),
386
					compact( 'signature_details' )
387
				);
388
			}
389
		}
390
391
		$token = $this->get_tokens()->get_access_token( $user_id, $token_key, false );
392
		if ( is_wp_error( $token ) ) {
393
			$token->add_data( compact( 'signature_details' ) );
394
			return $token;
395
		} elseif ( ! $token ) {
396
			return new \WP_Error(
397
				'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...
398
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
399
				compact( 'signature_details' )
400
			);
401
		}
402
403
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
404
		// phpcs:disable WordPress.Security.NonceVerification.Missing
405
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
406
			$post_data   = $_POST;
407
			$file_hashes = array();
408
			foreach ( $post_data as $post_data_key => $post_data_value ) {
409
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
410
					continue;
411
				}
412
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
413
				$file_hashes[ $post_data_key ] = $post_data_value;
414
			}
415
416
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
417
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
418
				$post_data[ $post_data_key ] = $post_data_value;
419
			}
420
421
			ksort( $post_data );
422
423
			$body = http_build_query( stripslashes_deep( $post_data ) );
424
		} elseif ( is_null( $this->raw_post_data ) ) {
425
			$body = file_get_contents( 'php://input' );
426
		} else {
427
			$body = null;
428
		}
429
		// phpcs:enable
430
431
		$signature = $jetpack_signature->sign_current_request(
432
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
433
		);
434
435
		$signature_details['url'] = $jetpack_signature->current_request_url;
436
437
		if ( ! $signature ) {
438
			return new \WP_Error(
439
				'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...
440
				'Unknown signature error',
441
				compact( 'signature_details' )
442
			);
443
		} elseif ( is_wp_error( $signature ) ) {
444
			return $signature;
445
		}
446
447
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
448
		$timestamp = (int) $_GET['timestamp'];
449
		$nonce     = stripslashes( (string) $_GET['nonce'] );
450
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
451
452
		// Use up the nonce regardless of whether the signature matches.
453
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
454
			return new \WP_Error(
455
				'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...
456
				'Could not add nonce',
457
				compact( 'signature_details' )
458
			);
459
		}
460
461
		// Be careful about what you do with this debugging data.
462
		// If a malicious requester has access to the expected signature,
463
		// bad things might be possible.
464
		$signature_details['expected'] = $signature;
465
466
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
467
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
468
			return new \WP_Error(
469
				'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...
470
				'Signature mismatch',
471
				compact( 'signature_details' )
472
			);
473
		}
474
475
		/**
476
		 * Action for additional token checking.
477
		 *
478
		 * @since 7.7.0
479
		 *
480
		 * @param array $post_data request data.
481
		 * @param array $token_data token data.
482
		 */
483
		return apply_filters(
484
			'jetpack_signature_check_token',
485
			array(
486
				'type'      => $token_type,
487
				'token_key' => $token_key,
488
				'user_id'   => $token->external_user_id,
489
			),
490
			$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...
491
			$this->raw_post_data
492
		);
493
	}
494
495
	/**
496
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI.
497
	 *
498
	 * This method is deprecated since Jetpack 9.6.0. Please use has_connected_owner instead.
499
	 *
500
	 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
501
	 *
502
	 * @deprecated 9.6.0
503
	 * @see Manager::has_connected_owner
504
	 * @return Boolean is the site connected?
505
	 */
506
	public function is_active() {
507
		return (bool) $this->get_tokens()->get_access_token( true );
0 ignored issues
show
Documentation introduced by
true 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...
508
	}
509
510
	/**
511
	 * Obtains an instance of the Tokens class.
512
	 *
513
	 * @return Tokens the Tokens object
514
	 */
515
	public function get_tokens() {
516
		return new Tokens();
517
	}
518
519
	/**
520
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
521
	 *
522
	 * @access public
523
	 * @deprecated 9.2.0 Use is_connected instead
524
	 * @see Manager::is_connected
525
	 *
526
	 * @return bool
527
	 */
528
	public function is_registered() {
529
		_deprecated_function( __METHOD__, 'jetpack-9.2' );
530
		return $this->is_connected();
531
	}
532
533
	/**
534
	 * Returns true if the site has both a token and a blog id, which indicates a site has been connected.
535
	 *
536
	 * @access public
537
	 * @since 9.2.0
538
	 *
539
	 * @return bool
540
	 */
541
	public function is_connected() {
542
		$has_blog_id    = (bool) \Jetpack_Options::get_option( 'id' );
543
		$has_blog_token = (bool) $this->get_tokens()->get_access_token();
544
		return $has_blog_id && $has_blog_token;
545
	}
546
547
	/**
548
	 * Returns true if the site has at least one connected administrator.
549
	 *
550
	 * @access public
551
	 * @since 9.2.0
552
	 *
553
	 * @return bool
554
	 */
555
	public function has_connected_admin() {
556
		return (bool) count( $this->get_connected_users( 'manage_options' ) );
557
	}
558
559
	/**
560
	 * Returns true if the site has any connected user.
561
	 *
562
	 * @access public
563
	 * @since 9.2.0
564
	 *
565
	 * @return bool
566
	 */
567
	public function has_connected_user() {
568
		return (bool) count( $this->get_connected_users() );
569
	}
570
571
	/**
572
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
573
	 * Able to select by specific capability.
574
	 *
575
	 * @param string $capability The capability of the user.
576
	 * @return array Array of WP_User objects if found.
577
	 */
578
	public function get_connected_users( $capability = 'any' ) {
579
		return $this->get_tokens()->get_connected_users( $capability );
580
	}
581
582
	/**
583
	 * Returns true if the site has a connected Blog owner (master_user).
584
	 *
585
	 * @access public
586
	 * @since 9.2.0
587
	 *
588
	 * @return bool
589
	 */
590
	public function has_connected_owner() {
591
		return (bool) $this->get_connection_owner_id();
592
	}
593
594
	/**
595
	 * Returns true if the site is connected only at a site level.
596
	 *
597
	 * Note that we are explicitly checking for the existence of the master_user option in order to account for cases where we don't have any user tokens (user-level connection) but the master_user option is set, which could be the result of a problematic user connection.
598
	 *
599
	 * @access public
600
	 * @since 9.6.0
601
	 *
602
	 * @return bool
603
	 */
604
	public function is_userless() {
605
		return $this->is_connected() && ! $this->has_connected_user() && ! \Jetpack_Options::get_option( 'master_user' );
606
	}
607
608
	/**
609
	 * Checks to see if the connection owner of the site is missing.
610
	 *
611
	 * @return bool
612
	 */
613
	public function is_missing_connection_owner() {
614
		$connection_owner = $this->get_connection_owner_id();
615
		if ( ! get_user_by( 'id', $connection_owner ) ) {
616
			return true;
617
		}
618
619
		return false;
620
	}
621
622
	/**
623
	 * Returns true if the user with the specified identifier is connected to
624
	 * WordPress.com.
625
	 *
626
	 * @param int $user_id the user identifier. Default is the current user.
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...
627
	 * @return bool Boolean is the user connected?
628
	 */
629
	public function is_user_connected( $user_id = false ) {
630
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
631
		if ( ! $user_id ) {
632
			return false;
633
		}
634
635
		return (bool) $this->get_tokens()->get_access_token( $user_id );
636
	}
637
638
	/**
639
	 * Returns the local user ID of the connection owner.
640
	 *
641
	 * @return bool|int Returns the ID of the connection owner or False if no connection owner found.
642
	 */
643
	public function get_connection_owner_id() {
644
		$owner = $this->get_connection_owner();
645
		return $owner instanceof \WP_User ? $owner->ID : false;
0 ignored issues
show
Bug introduced by
The class WP_User does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
646
	}
647
648
	/**
649
	 * Get the wpcom user data of the current|specified connected user.
650
	 *
651
	 * @todo Refactor to properly load the XMLRPC client independently.
652
	 *
653
	 * @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...
654
	 * @return Object the user object.
655
	 */
656
	public function get_connected_user_data( $user_id = null ) {
657
		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...
658
			$user_id = get_current_user_id();
659
		}
660
661
		$transient_key    = "jetpack_connected_user_data_$user_id";
662
		$cached_user_data = get_transient( $transient_key );
663
664
		if ( $cached_user_data ) {
665
			return $cached_user_data;
666
		}
667
668
		$xml = new \Jetpack_IXR_Client(
669
			array(
670
				'user_id' => $user_id,
671
			)
672
		);
673
		$xml->query( 'wpcom.getUser' );
674
		if ( ! $xml->isError() ) {
675
			$user_data = $xml->getResponse();
676
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
677
			return $user_data;
678
		}
679
680
		return false;
681
	}
682
683
	/**
684
	 * Returns a user object of the connection owner.
685
	 *
686
	 * @return WP_User|false False if no connection owner found.
687
	 */
688
	public function get_connection_owner() {
689
690
		$user_id = \Jetpack_Options::get_option( 'master_user' );
691
692
		if ( ! $user_id ) {
693
			return false;
694
		}
695
696
		// Make sure user is connected.
697
		$user_token = $this->get_tokens()->get_access_token( $user_id );
698
699
		$connection_owner = false;
700
701
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
702
			$connection_owner = get_userdata( $user_token->external_user_id );
703
		}
704
705
		return $connection_owner;
706
	}
707
708
	/**
709
	 * Returns true if the provided user is the Jetpack connection owner.
710
	 * If user ID is not specified, the current user will be used.
711
	 *
712
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
713
	 * @return Boolean True the user the connection owner, false otherwise.
714
	 */
715
	public function is_connection_owner( $user_id = false ) {
716
		if ( ! $user_id ) {
717
			$user_id = get_current_user_id();
718
		}
719
720
		return ( (int) $user_id ) === $this->get_connection_owner_id();
721
	}
722
723
	/**
724
	 * Connects the user with a specified ID to a WordPress.com user using the
725
	 * remote login flow.
726
	 *
727
	 * @access public
728
	 *
729
	 * @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...
730
	 * @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...
731
	 *                              admin_url().
732
	 * @return WP_Error only in case of a failed user lookup.
733
	 */
734
	public function connect_user( $user_id = null, $redirect_url = null ) {
735
		$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...
736
		if ( null === $user_id ) {
737
			$user = wp_get_current_user();
738
		} else {
739
			$user = get_user_by( 'ID', $user_id );
740
		}
741
742
		if ( empty( $user ) ) {
743
			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...
744
		}
745
746
		if ( null === $redirect_url ) {
747
			$redirect_url = admin_url();
748
		}
749
750
		// Using wp_redirect intentionally because we're redirecting outside.
751
		wp_redirect( $this->get_authorization_url( $user, $redirect_url ) ); // phpcs:ignore WordPress.Security.SafeRedirect
752
		exit();
753
	}
754
755
	/**
756
	 * Unlinks the current user from the linked WordPress.com user.
757
	 *
758
	 * @access public
759
	 * @static
760
	 *
761
	 * @todo Refactor to properly load the XMLRPC client independently.
762
	 *
763
	 * @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...
764
	 * @param bool    $can_overwrite_primary_user Allow for the primary user to be disconnected.
765
	 * @return Boolean Whether the disconnection of the user was successful.
766
	 */
767
	public function disconnect_user( $user_id = null, $can_overwrite_primary_user = false ) {
768
		$user_id = empty( $user_id ) ? get_current_user_id() : (int) $user_id;
769
770
		$result = $this->get_tokens()->disconnect_user( $user_id, $can_overwrite_primary_user );
771
772
		if ( $result ) {
773
			$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
774
			$xml->query( 'jetpack.unlink_user', $user_id );
775
776
			// Delete cached connected user data.
777
			$transient_key = "jetpack_connected_user_data_$user_id";
778
			delete_transient( $transient_key );
779
780
			/**
781
			 * Fires after the current user has been unlinked from WordPress.com.
782
			 *
783
			 * @since 4.1.0
784
			 *
785
			 * @param int $user_id The current user's ID.
786
			 */
787
			do_action( 'jetpack_unlinked_user', $user_id );
788
		}
789
		return $result;
790
	}
791
792
	/**
793
	 * Returns the requested Jetpack API URL.
794
	 *
795
	 * @param String $relative_url the relative API path.
796
	 * @return String API URL.
797
	 */
798
	public function api_url( $relative_url ) {
799
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
800
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
801
802
		/**
803
		 * Filters whether the connection manager should use the iframe authorization
804
		 * flow instead of the regular redirect-based flow.
805
		 *
806
		 * @since 8.3.0
807
		 *
808
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
809
		 */
810
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
811
812
		// Do not modify anything that is not related to authorize requests.
813
		if ( 'authorize' === $relative_url && $iframe_flow ) {
814
			$relative_url = 'authorize_iframe';
815
		}
816
817
		/**
818
		 * Filters the API URL that Jetpack uses for server communication.
819
		 *
820
		 * @since 8.0.0
821
		 *
822
		 * @param String $url the generated URL.
823
		 * @param String $relative_url the relative URL that was passed as an argument.
824
		 * @param String $api_base the API base string that is being used.
825
		 * @param String $api_version the API version string that is being used.
826
		 */
827
		return apply_filters(
828
			'jetpack_api_url',
829
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
830
			$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...
831
			$api_base,
832
			$api_version
833
		);
834
	}
835
836
	/**
837
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
838
	 *
839
	 * @return String XMLRPC API URL.
840
	 */
841
	public function xmlrpc_api_url() {
842
		$base = preg_replace(
843
			'#(https?://[^?/]+)(/?.*)?$#',
844
			'\\1',
845
			Constants::get_constant( 'JETPACK__API_BASE' )
846
		);
847
		return untrailingslashit( $base ) . '/xmlrpc.php';
848
	}
849
850
	/**
851
	 * Attempts Jetpack registration which sets up the site for connection. Should
852
	 * remain public because the call to action comes from the current site, not from
853
	 * WordPress.com.
854
	 *
855
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
856
	 * @return true|WP_Error The error object.
857
	 */
858
	public function register( $api_endpoint = 'register' ) {
859
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
860
		$secrets = ( new Secrets() )->generate( 'register', get_current_user_id(), 600 );
861
862
		if ( false === $secrets ) {
863
			return new WP_Error( 'cannot_save_secrets', __( 'Jetpack experienced an issue trying to save options (cannot_save_secrets). We suggest that you contact your hosting provider, and ask them for help checking that the options table is writable on your site.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_save_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...
864
		}
865
866
		if (
867
			empty( $secrets['secret_1'] ) ||
868
			empty( $secrets['secret_2'] ) ||
869
			empty( $secrets['exp'] )
870
		) {
871
			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...
872
		}
873
874
		// Better to try (and fail) to set a higher timeout than this system
875
		// supports than to have register fail for more users than it should.
876
		$timeout = $this->set_min_time_limit( 60 ) / 2;
877
878
		$gmt_offset = get_option( 'gmt_offset' );
879
		if ( ! $gmt_offset ) {
880
			$gmt_offset = 0;
881
		}
882
883
		$stats_options = get_option( 'stats_options' );
884
		$stats_id      = isset( $stats_options['blog_id'] )
885
			? $stats_options['blog_id']
886
			: null;
887
888
		/**
889
		 * Filters the request body for additional property addition.
890
		 *
891
		 * @since 7.7.0
892
		 *
893
		 * @param array $post_data request data.
894
		 * @param Array $token_data token data.
895
		 */
896
		$body = apply_filters(
897
			'jetpack_register_request_body',
898
			array_merge(
899
				array(
900
					'siteurl'            => site_url(),
901
					'home'               => home_url(),
902
					'gmt_offset'         => $gmt_offset,
903
					'timezone_string'    => (string) get_option( 'timezone_string' ),
904
					'site_name'          => (string) get_option( 'blogname' ),
905
					'secret_1'           => $secrets['secret_1'],
906
					'secret_2'           => $secrets['secret_2'],
907
					'site_lang'          => get_locale(),
908
					'timeout'            => $timeout,
909
					'stats_id'           => $stats_id,
910
					'state'              => get_current_user_id(),
911
					'site_created'       => $this->get_assumed_site_creation_date(),
912
					'jetpack_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
913
					'ABSPATH'            => Constants::get_constant( 'ABSPATH' ),
914
					'current_user_email' => wp_get_current_user()->user_email,
915
					'connect_plugin'     => $this->get_plugin() ? $this->get_plugin()->get_slug() : null,
916
				),
917
				self::$extra_register_params
918
			)
919
		);
920
921
		$args = array(
922
			'method'  => 'POST',
923
			'body'    => $body,
924
			'headers' => array(
925
				'Accept' => 'application/json',
926
			),
927
			'timeout' => $timeout,
928
		);
929
930
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
931
932
		// TODO: fix URLs for bad hosts.
933
		$response = Client::_wp_remote_request(
934
			$this->api_url( $api_endpoint ),
935
			$args,
936
			true
937
		);
938
939
		// Make sure the response is valid and does not contain any Jetpack errors.
940
		$registration_details = $this->validate_remote_register_response( $response );
941
942
		if ( is_wp_error( $registration_details ) ) {
943
			return $registration_details;
944
		} elseif ( ! $registration_details ) {
945
			return new \WP_Error(
946
				'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...
947
				'Unknown error registering your Jetpack site.',
948
				wp_remote_retrieve_response_code( $response )
949
			);
950
		}
951
952
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
953
			return new \WP_Error(
954
				'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...
955
				'Unable to validate registration of your Jetpack site.',
956
				wp_remote_retrieve_response_code( $response )
957
			);
958
		}
959
960
		if ( isset( $registration_details->jetpack_public ) ) {
961
			$jetpack_public = (int) $registration_details->jetpack_public;
962
		} else {
963
			$jetpack_public = false;
964
		}
965
966
		\Jetpack_Options::update_options(
967
			array(
968
				'id'     => (int) $registration_details->jetpack_id,
969
				'public' => $jetpack_public,
970
			)
971
		);
972
973
		$this->get_tokens()->update_blog_token( (string) $registration_details->jetpack_secret );
974
975
		/**
976
		 * Fires when a site is registered on WordPress.com.
977
		 *
978
		 * @since 3.7.0
979
		 *
980
		 * @param int $json->jetpack_id Jetpack Blog ID.
981
		 * @param string $json->jetpack_secret Jetpack Blog Token.
982
		 * @param int|bool $jetpack_public Is the site public.
983
		 */
984
		do_action(
985
			'jetpack_site_registered',
986
			$registration_details->jetpack_id,
987
			$registration_details->jetpack_secret,
988
			$jetpack_public
989
		);
990
991
		if ( isset( $registration_details->token ) ) {
992
			/**
993
			 * Fires when a user token is sent along with the registration data.
994
			 *
995
			 * @since 7.6.0
996
			 *
997
			 * @param object $token the administrator token for the newly registered site.
998
			 */
999
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
1000
		}
1001
1002
		return true;
1003
	}
1004
1005
	/**
1006
	 * Attempts Jetpack registration.
1007
	 *
1008
	 * @param bool $tos_agree Whether the user agreed to TOS.
1009
	 *
1010
	 * @return bool|WP_Error
1011
	 */
1012
	public function try_registration( $tos_agree = true ) {
1013
		if ( $tos_agree ) {
1014
			$terms_of_service = new Terms_Of_Service();
1015
			$terms_of_service->agree();
1016
		}
1017
1018
		/**
1019
		 * Action fired when the user attempts the registration.
1020
		 *
1021
		 * @since 9.7.0
1022
		 */
1023
		$pre_register = apply_filters( 'jetpack_pre_register', null );
1024
1025
		if ( is_wp_error( $pre_register ) ) {
1026
			return $pre_register;
1027
		}
1028
1029
		$tracking_data = array();
1030
1031
		if ( null !== $this->get_plugin() ) {
1032
			$tracking_data['plugin_slug'] = $this->get_plugin()->get_slug();
1033
		}
1034
1035
		$tracking = new Tracking();
1036
		$tracking->record_user_event( 'jpc_register_begin', $tracking_data );
1037
1038
		add_filter( 'jetpack_register_request_body', array( Utils::class, 'filter_register_request_body' ) );
1039
1040
		$result = $this->register();
1041
1042
		remove_filter( 'jetpack_register_request_body', array( Utils::class, 'filter_register_request_body' ) );
1043
1044
		// If there was an error with registration and the site was not registered, record this so we can show a message.
1045
		if ( ! $result || is_wp_error( $result ) ) {
1046
			return $result;
1047
		}
1048
1049
		return true;
1050
	}
1051
1052
	/**
1053
	 * Adds a parameter to the register request body
1054
	 *
1055
	 * @since 9.7.0
1056
	 *
1057
	 * @param string $name The name of the parameter to be added.
1058
	 * @param string $value The value of the parameter to be added.
1059
	 *
1060
	 * @throws \InvalidArgumentException If supplied arguments are not strings.
1061
	 * @return void
1062
	 */
1063
	public function add_register_request_param( $name, $value ) {
1064
		if ( ! is_string( $name ) || ! is_string( $value ) ) {
1065
			throw new \InvalidArgumentException( 'name and value must be strings' );
1066
		}
1067
		self::$extra_register_params[ $name ] = $value;
1068
	}
1069
1070
	/**
1071
	 * Takes the response from the Jetpack register new site endpoint and
1072
	 * verifies it worked properly.
1073
	 *
1074
	 * @since 2.6
1075
	 *
1076
	 * @param Mixed $response the response object, or the error object.
1077
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
1078
	 **/
1079
	protected function validate_remote_register_response( $response ) {
1080
		if ( is_wp_error( $response ) ) {
1081
			return new \WP_Error(
1082
				'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...
1083
				$response->get_error_message()
1084
			);
1085
		}
1086
1087
		$code   = wp_remote_retrieve_response_code( $response );
1088
		$entity = wp_remote_retrieve_body( $response );
1089
1090
		if ( $entity ) {
1091
			$registration_response = json_decode( $entity );
1092
		} else {
1093
			$registration_response = false;
1094
		}
1095
1096
		$code_type = (int) ( $code / 100 );
1097
		if ( 5 === $code_type ) {
1098
			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...
1099
		} elseif ( 408 === $code ) {
1100
			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...
1101
		} elseif ( ! empty( $registration_response->error ) ) {
1102
			if (
1103
				'xml_rpc-32700' === $registration_response->error
1104
				&& ! function_exists( 'xml_parser_create' )
1105
			) {
1106
				$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' );
1107
			} else {
1108
				$error_description = isset( $registration_response->error_description )
1109
					? (string) $registration_response->error_description
1110
					: '';
1111
			}
1112
1113
			return new \WP_Error(
1114
				(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...
1115
				$error_description,
1116
				$code
1117
			);
1118
		} elseif ( 200 !== $code ) {
1119
			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...
1120
		}
1121
1122
		// Jetpack ID error block.
1123
		if ( empty( $registration_response->jetpack_id ) ) {
1124
			return new \WP_Error(
1125
				'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...
1126
				/* translators: %s is an error message string */
1127
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1128
				$entity
1129
			);
1130
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1131
			return new \WP_Error(
1132
				'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...
1133
				/* translators: %s is an error message string */
1134
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1135
				$entity
1136
			);
1137 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1138
			return new \WP_Error(
1139
				'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...
1140
				/* translators: %s is an error message string */
1141
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1142
				$entity
1143
			);
1144
		}
1145
1146
		return $registration_response;
1147
	}
1148
1149
	/**
1150
	 * Adds a used nonce to a list of known nonces.
1151
	 *
1152
	 * @param int    $timestamp the current request timestamp.
1153
	 * @param string $nonce the nonce value.
1154
	 * @return bool whether the nonce is unique or not.
1155
	 *
1156
	 * @deprecated since 9.5.0
1157
	 * @see Nonce_Handler::add()
1158
	 */
1159
	public function add_nonce( $timestamp, $nonce ) {
1160
		_deprecated_function( __METHOD__, 'jetpack-9.5.0', 'Automattic\\Jetpack\\Connection\\Nonce_Handler::add' );
1161
		return ( new Nonce_Handler() )->add( $timestamp, $nonce );
1162
	}
1163
1164
	/**
1165
	 * Cleans nonces that were saved when calling ::add_nonce.
1166
	 *
1167
	 * @todo Properly prepare the query before executing it.
1168
	 *
1169
	 * @param bool $all whether to clean even non-expired nonces.
1170
	 *
1171
	 * @deprecated since 9.5.0
1172
	 * @see Nonce_Handler::clean_all()
1173
	 */
1174
	public function clean_nonces( $all = false ) {
1175
		_deprecated_function( __METHOD__, 'jetpack-9.5.0', 'Automattic\\Jetpack\\Connection\\Nonce_Handler::clean_all' );
1176
		( new Nonce_Handler() )->clean_all( $all ? PHP_INT_MAX : ( time() - Nonce_Handler::LIFETIME ) );
1177
	}
1178
1179
	/**
1180
	 * Sets the Connection custom capabilities.
1181
	 *
1182
	 * @param string[] $caps    Array of the user's capabilities.
1183
	 * @param string   $cap     Capability name.
1184
	 * @param int      $user_id The user ID.
1185
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1186
	 */
1187
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1188
		switch ( $cap ) {
1189
			case 'jetpack_connect':
1190
			case 'jetpack_reconnect':
1191
				$is_offline_mode = ( new Status() )->is_offline_mode();
1192
				if ( $is_offline_mode ) {
1193
					$caps = array( 'do_not_allow' );
1194
					break;
1195
				}
1196
				// Pass through. If it's not offline mode, these should match disconnect.
1197
				// Let users disconnect if it's offline mode, just in case things glitch.
1198
			case 'jetpack_disconnect':
1199
				/**
1200
				 * Filters the jetpack_disconnect capability.
1201
				 *
1202
				 * @since 8.7.0
1203
				 *
1204
				 * @param array An array containing the capability name.
1205
				 */
1206
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1207
				break;
1208 View Code Duplication
			case 'jetpack_connect_user':
1209
				$is_offline_mode = ( new Status() )->is_offline_mode();
1210
				if ( $is_offline_mode ) {
1211
					$caps = array( 'do_not_allow' );
1212
					break;
1213
				}
1214
				// With user-less connections in mind, non-admin users can connect their account only if a connection owner exists.
1215
				$caps = $this->has_connected_owner() ? array( 'read' ) : array( 'manage_options' );
1216
				break;
1217
		}
1218
		return $caps;
1219
	}
1220
1221
	/**
1222
	 * Builds the timeout limit for queries talking with the wpcom servers.
1223
	 *
1224
	 * Based on local php max_execution_time in php.ini
1225
	 *
1226
	 * @since 5.4
1227
	 * @return int
1228
	 **/
1229
	public function get_max_execution_time() {
1230
		$timeout = (int) ini_get( 'max_execution_time' );
1231
1232
		// Ensure exec time set in php.ini.
1233
		if ( ! $timeout ) {
1234
			$timeout = 30;
1235
		}
1236
		return $timeout;
1237
	}
1238
1239
	/**
1240
	 * Sets a minimum request timeout, and returns the current timeout
1241
	 *
1242
	 * @since 5.4
1243
	 * @param Integer $min_timeout the minimum timeout value.
1244
	 **/
1245 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1246
		$timeout = $this->get_max_execution_time();
1247
		if ( $timeout < $min_timeout ) {
1248
			$timeout = $min_timeout;
1249
			set_time_limit( $timeout );
1250
		}
1251
		return $timeout;
1252
	}
1253
1254
	/**
1255
	 * Get our assumed site creation date.
1256
	 * Calculated based on the earlier date of either:
1257
	 * - Earliest admin user registration date.
1258
	 * - Earliest date of post of any post type.
1259
	 *
1260
	 * @since 7.2.0
1261
	 *
1262
	 * @return string Assumed site creation date and time.
1263
	 */
1264
	public function get_assumed_site_creation_date() {
1265
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1266
		if ( ! empty( $cached_date ) ) {
1267
			return $cached_date;
1268
		}
1269
1270
		$earliest_registered_users  = get_users(
1271
			array(
1272
				'role'    => 'administrator',
1273
				'orderby' => 'user_registered',
1274
				'order'   => 'ASC',
1275
				'fields'  => array( 'user_registered' ),
1276
				'number'  => 1,
1277
			)
1278
		);
1279
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1280
1281
		$earliest_posts = get_posts(
1282
			array(
1283
				'posts_per_page' => 1,
1284
				'post_type'      => 'any',
1285
				'post_status'    => 'any',
1286
				'orderby'        => 'date',
1287
				'order'          => 'ASC',
1288
			)
1289
		);
1290
1291
		// If there are no posts at all, we'll count only on user registration date.
1292
		if ( $earliest_posts ) {
1293
			$earliest_post_date = $earliest_posts[0]->post_date;
1294
		} else {
1295
			$earliest_post_date = PHP_INT_MAX;
1296
		}
1297
1298
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1299
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1300
1301
		return $assumed_date;
1302
	}
1303
1304
	/**
1305
	 * Adds the activation source string as a parameter to passed arguments.
1306
	 *
1307
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1308
	 *
1309
	 * @param array $args arguments that need to have the source added.
1310
	 * @return array $amended arguments.
1311
	 */
1312 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1313
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1314
1315
		if ( $activation_source_name ) {
1316
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1317
			$args['_as'] = urlencode( $activation_source_name );
1318
		}
1319
1320
		if ( $activation_source_keyword ) {
1321
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1322
			$args['_ak'] = urlencode( $activation_source_keyword );
1323
		}
1324
1325
		return $args;
1326
	}
1327
1328
	/**
1329
	 * Generates two secret tokens and the end of life timestamp for them.
1330
	 *
1331
	 * @param String  $action  The action name.
1332
	 * @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...
1333
	 * @param Integer $exp     Expiration time in seconds.
1334
	 */
1335
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1336
		return ( new Secrets() )->generate( $action, $user_id, $exp );
1337
	}
1338
1339
	/**
1340
	 * Returns two secret tokens and the end of life timestamp for them.
1341
	 *
1342
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->get() instead.
1343
	 *
1344
	 * @param String  $action  The action name.
1345
	 * @param Integer $user_id The user identifier.
1346
	 * @return string|array an array of secrets or an error string.
1347
	 */
1348
	public function get_secrets( $action, $user_id ) {
1349
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->get' );
1350
		return ( new Secrets() )->get( $action, $user_id );
1351
	}
1352
1353
	/**
1354
	 * Deletes secret tokens in case they, for example, have expired.
1355
	 *
1356
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->delete() instead.
1357
	 *
1358
	 * @param String  $action  The action name.
1359
	 * @param Integer $user_id The user identifier.
1360
	 */
1361
	public function delete_secrets( $action, $user_id ) {
1362
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->delete' );
1363
		( new Secrets() )->delete( $action, $user_id );
1364
	}
1365
1366
	/**
1367
	 * Deletes all connection tokens and transients from the local Jetpack site.
1368
	 * If the plugin object has been provided in the constructor, the function first checks
1369
	 * whether it's the only active connection.
1370
	 * If there are any other connections, the function will do nothing and return `false`
1371
	 * (unless `$ignore_connected_plugins` is set to `true`).
1372
	 *
1373
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1374
	 *
1375
	 * @return bool True if disconnected successfully, false otherwise.
1376
	 */
1377
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1378
		// refuse to delete if we're not the last Jetpack plugin installed.
1379 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1380
			return false;
1381
		}
1382
1383
		/**
1384
		 * Fires upon the disconnect attempt.
1385
		 * Return `false` to prevent the disconnect.
1386
		 *
1387
		 * @since 8.7.0
1388
		 */
1389
		if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', true ) ) {
1390
			return false;
1391
		}
1392
1393
		\Jetpack_Options::delete_option(
1394
			array(
1395
				'master_user',
1396
				'time_diff',
1397
				'fallback_no_verify_ssl_certs',
1398
			)
1399
		);
1400
1401
		( new Secrets() )->delete_all();
1402
		$this->get_tokens()->delete_all();
1403
1404
		// Delete cached connected user data.
1405
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1406
		delete_transient( $transient_key );
1407
1408
		// Delete all XML-RPC errors.
1409
		Error_Handler::get_instance()->delete_all_errors();
1410
1411
		return true;
1412
	}
1413
1414
	/**
1415
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1416
	 * If the plugin object has been provided in the constructor, the function first check
1417
	 * whether it's the only active connection.
1418
	 * If there are any other connections, the function will do nothing and return `false`
1419
	 * (unless `$ignore_connected_plugins` is set to `true`).
1420
	 *
1421
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1422
	 *
1423
	 * @return bool True if disconnected successfully, false otherwise.
1424
	 */
1425
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1426 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1427
			return false;
1428
		}
1429
1430
		/**
1431
		 * Fires upon the disconnect attempt.
1432
		 * Return `false` to prevent the disconnect.
1433
		 *
1434
		 * @since 8.7.0
1435
		 */
1436
		if ( ! apply_filters( 'jetpack_connection_disconnect_site_wpcom', true, $this ) ) {
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this.

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

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

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

Loading history...
1437
			return false;
1438
		}
1439
1440
		$xml = new \Jetpack_IXR_Client();
1441
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1442
1443
		return true;
1444
	}
1445
1446
	/**
1447
	 * Disconnect the plugin and remove the tokens.
1448
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1449
	 * This is a proxy method to simplify the Connection package API.
1450
	 *
1451
	 * @see Manager::disable_plugin()
1452
	 * @see Manager::disconnect_site_wpcom()
1453
	 * @see Manager::delete_all_connection_tokens()
1454
	 *
1455
	 * @return bool
1456
	 */
1457
	public function remove_connection() {
1458
		$this->disable_plugin();
1459
		$this->disconnect_site_wpcom();
1460
		$this->delete_all_connection_tokens();
1461
1462
		return true;
1463
	}
1464
1465
	/**
1466
	 * Completely clearing up the connection, and initiating reconnect.
1467
	 *
1468
	 * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
1469
	 */
1470
	public function reconnect() {
1471
		( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
1472
1473
		$this->disconnect_site_wpcom( true );
1474
		$this->delete_all_connection_tokens( true );
1475
1476
		return $this->register();
1477
	}
1478
1479
	/**
1480
	 * Validate the tokens, and refresh the invalid ones.
1481
	 *
1482
	 * @return string|bool|WP_Error True if connection restored or string indicating what's to be done next. A `WP_Error` object or false otherwise.
1483
	 */
1484
	public function restore() {
1485
		// If this is a userless connection we need to trigger a full reconnection as our only secure means of
1486
		// communication with WPCOM, aka the blog token, is compromised.
1487
		if ( $this->is_userless() ) {
1488
			return $this->reconnect();
1489
		}
1490
1491
		$validate_tokens_response = $this->get_tokens()->validate();
1492
1493
		// If token validation failed, trigger a full reconnection.
1494
		if ( is_array( $validate_tokens_response ) &&
1495
			isset( $validate_tokens_response['blog_token']['is_healthy'] ) &&
1496
			isset( $validate_tokens_response['user_token']['is_healthy'] ) ) {
1497
			$blog_token_healthy = $validate_tokens_response['blog_token']['is_healthy'];
1498
			$user_token_healthy = $validate_tokens_response['user_token']['is_healthy'];
1499
		} else {
1500
			$blog_token_healthy = false;
1501
			$user_token_healthy = false;
1502
		}
1503
1504
		// Tokens are both valid, or both invalid. We can't fix the problem we don't see, so the full reconnection is needed.
1505
		if ( $blog_token_healthy === $user_token_healthy ) {
1506
			$result = $this->reconnect();
1507
			return ( true === $result ) ? 'authorize' : $result;
1508
		}
1509
1510
		if ( ! $blog_token_healthy ) {
1511
			return $this->refresh_blog_token();
1512
		}
1513
1514
		if ( ! $user_token_healthy ) {
1515
			return ( true === $this->refresh_user_token() ) ? 'authorize' : false;
1516
		}
1517
1518
		return false;
1519
	}
1520
1521
	/**
1522
	 * Responds to a WordPress.com call to register the current site.
1523
	 * Should be changed to protected.
1524
	 *
1525
	 * @param array $registration_data Array of [ secret_1, user_id ].
1526
	 */
1527
	public function handle_registration( array $registration_data ) {
1528
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1529
		if ( empty( $registration_user_id ) ) {
1530
			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...
1531
		}
1532
1533
		return ( new Secrets() )->verify( 'register', $registration_secret_1, (int) $registration_user_id );
1534
	}
1535
1536
	/**
1537
	 * Perform the API request to validate the blog and user tokens.
1538
	 *
1539
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->validate_tokens() instead.
1540
	 *
1541
	 * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
1542
	 *
1543
	 * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
1544
	 */
1545
	public function validate_tokens( $user_id = null ) {
1546
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->validate' );
1547
		return $this->get_tokens()->validate( $user_id );
1548
	}
1549
1550
	/**
1551
	 * Verify a Previously Generated Secret.
1552
	 *
1553
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->verify() instead.
1554
	 *
1555
	 * @param string $action   The type of secret to verify.
1556
	 * @param string $secret_1 The secret string to compare to what is stored.
1557
	 * @param int    $user_id  The user ID of the owner of the secret.
1558
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1559
	 */
1560
	public function verify_secrets( $action, $secret_1, $user_id ) {
1561
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->verify' );
1562
		return ( new Secrets() )->verify( $action, $secret_1, $user_id );
1563
	}
1564
1565
	/**
1566
	 * Responds to a WordPress.com call to authorize the current user.
1567
	 * Should be changed to protected.
1568
	 */
1569
	public function handle_authorization() {
1570
1571
	}
1572
1573
	/**
1574
	 * Obtains the auth token.
1575
	 *
1576
	 * @param array $data The request data.
1577
	 * @return object|\WP_Error Returns the auth token on success.
1578
	 *                          Returns a \WP_Error on failure.
1579
	 */
1580
	public function get_token( $data ) {
1581
		return $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1582
	}
1583
1584
	/**
1585
	 * Builds a URL to the Jetpack connection auth page.
1586
	 *
1587
	 * @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...
1588
	 * @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...
1589
	 * @return string Connect URL.
1590
	 */
1591
	public function get_authorization_url( $user = null, $redirect = null ) {
1592
		if ( empty( $user ) ) {
1593
			$user = wp_get_current_user();
1594
		}
1595
1596
		$roles       = new Roles();
1597
		$role        = $roles->translate_user_to_role( $user );
1598
		$signed_role = $this->get_tokens()->sign_role( $role );
1599
1600
		/**
1601
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1602
		 * data processing.
1603
		 *
1604
		 * @since 8.0.0
1605
		 *
1606
		 * @param string $redirect_url Defaults to the site admin URL.
1607
		 */
1608
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1609
1610
		/**
1611
		 * Filter the URL to redirect the user back to when the authorization process
1612
		 * is complete.
1613
		 *
1614
		 * @since 8.0.0
1615
		 *
1616
		 * @param string $redirect_url Defaults to the site URL.
1617
		 */
1618
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1619
1620
		$secrets = ( new Secrets() )->generate( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1621
1622
		/**
1623
		 * Filter the type of authorization.
1624
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1625
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1626
		 *
1627
		 * @since 4.3.3
1628
		 *
1629
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1630
		 */
1631
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1632
1633
		/**
1634
		 * Filters the user connection request data for additional property addition.
1635
		 *
1636
		 * @since 8.0.0
1637
		 *
1638
		 * @param array $request_data request data.
1639
		 */
1640
		$body = apply_filters(
1641
			'jetpack_connect_request_body',
1642
			array(
1643
				'response_type' => 'code',
1644
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1645
				'redirect_uri'  => add_query_arg(
1646
					array(
1647
						'handler'  => 'jetpack-connection-webhooks',
1648
						'action'   => 'authorize',
1649
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1650
						'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1651
					),
1652
					esc_url( $processing_url )
1653
				),
1654
				'state'         => $user->ID,
1655
				'scope'         => $signed_role,
1656
				'user_email'    => $user->user_email,
1657
				'user_login'    => $user->user_login,
1658
				'is_active'     => $this->is_active(), // TODO Deprecate this.
0 ignored issues
show
Deprecated Code introduced by
The method Automattic\Jetpack\Connection\Manager::is_active() has been deprecated with message: 9.6.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1659
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1660
				'auth_type'     => $auth_type,
1661
				'secret'        => $secrets['secret_1'],
1662
				'blogname'      => get_option( 'blogname' ),
1663
				'site_url'      => site_url(),
1664
				'home_url'      => home_url(),
1665
				'site_icon'     => get_site_icon_url(),
1666
				'site_lang'     => get_locale(),
1667
				'site_created'  => $this->get_assumed_site_creation_date(),
1668
				'userless'      => ! $this->has_connected_owner(),
1669
			)
1670
		);
1671
1672
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1673
1674
		$api_url = $this->api_url( 'authorize' );
1675
1676
		return add_query_arg( $body, $api_url );
1677
	}
1678
1679
	/**
1680
	 * Authorizes the user by obtaining and storing the user token.
1681
	 *
1682
	 * @param array $data The request data.
1683
	 * @return string|\WP_Error Returns a string on success.
1684
	 *                          Returns a \WP_Error on failure.
1685
	 */
1686
	public function authorize( $data = array() ) {
1687
		/**
1688
		 * Action fired when user authorization starts.
1689
		 *
1690
		 * @since 8.0.0
1691
		 */
1692
		do_action( 'jetpack_authorize_starting' );
1693
1694
		$roles = new Roles();
1695
		$role  = $roles->translate_current_user_to_role();
1696
1697
		if ( ! $role ) {
1698
			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...
1699
		}
1700
1701
		$cap = $roles->translate_role_to_cap( $role );
1702
		if ( ! $cap ) {
1703
			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...
1704
		}
1705
1706
		if ( ! empty( $data['error'] ) ) {
1707
			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...
1708
		}
1709
1710
		if ( ! isset( $data['state'] ) ) {
1711
			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...
1712
		}
1713
1714
		if ( ! ctype_digit( $data['state'] ) ) {
1715
			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...
1716
		}
1717
1718
		$current_user_id = get_current_user_id();
1719
		if ( $current_user_id !== (int) $data['state'] ) {
1720
			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...
1721
		}
1722
1723
		if ( empty( $data['code'] ) ) {
1724
			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...
1725
		}
1726
1727
		$token = $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1728
1729 View Code Duplication
		if ( is_wp_error( $token ) ) {
1730
			$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...
1731
			if ( empty( $code ) ) {
1732
				$code = 'invalid_token';
1733
			}
1734
			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...
1735
		}
1736
1737
		if ( ! $token ) {
1738
			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...
1739
		}
1740
1741
		$is_connection_owner = ! $this->has_connected_owner();
1742
1743
		$this->get_tokens()->update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_connection_owner );
1744
1745
		/**
1746
		 * Fires after user has successfully received an auth token.
1747
		 *
1748
		 * @since 3.9.0
1749
		 */
1750
		do_action( 'jetpack_user_authorized' );
1751
1752
		if ( ! $is_connection_owner ) {
1753
			/**
1754
			 * Action fired when a secondary user has been authorized.
1755
			 *
1756
			 * @since 8.0.0
1757
			 */
1758
			do_action( 'jetpack_authorize_ending_linked' );
1759
			return 'linked';
1760
		}
1761
1762
		/**
1763
		 * Action fired when the master user has been authorized.
1764
		 *
1765
		 * @since 8.0.0
1766
		 *
1767
		 * @param array $data The request data.
1768
		 */
1769
		do_action( 'jetpack_authorize_ending_authorized', $data );
1770
1771
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
1772
1773
		( new Nonce_Handler() )->reschedule();
1774
1775
		return 'authorized';
1776
	}
1777
1778
	/**
1779
	 * Disconnects from the Jetpack servers.
1780
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1781
	 */
1782
	public function disconnect_site() {
1783
1784
	}
1785
1786
	/**
1787
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1788
	 *
1789
	 * @param string $text The string to hash.
1790
	 * @return string
1791
	 */
1792
	public function sha1_base64( $text ) {
1793
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1794
	}
1795
1796
	/**
1797
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1798
	 *
1799
	 * @param string $domain The domain to check.
1800
	 *
1801
	 * @return bool|WP_Error
1802
	 */
1803
	public function is_usable_domain( $domain ) {
1804
1805
		// If it's empty, just fail out.
1806
		if ( ! $domain ) {
1807
			return new \WP_Error(
1808
				'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...
1809
				/* translators: %1$s is a domain name. */
1810
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1811
			);
1812
		}
1813
1814
		/**
1815
		 * Skips the usuable domain check when connecting a site.
1816
		 *
1817
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1818
		 *
1819
		 * @since 4.1.0
1820
		 *
1821
		 * @param bool If the check should be skipped. Default false.
1822
		 */
1823
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1824
			return true;
1825
		}
1826
1827
		// None of the explicit localhosts.
1828
		$forbidden_domains = array(
1829
			'wordpress.com',
1830
			'localhost',
1831
			'localhost.localdomain',
1832
			'127.0.0.1',
1833
			'local.wordpress.test',         // VVV pattern.
1834
			'local.wordpress-trunk.test',   // VVV pattern.
1835
			'src.wordpress-develop.test',   // VVV pattern.
1836
			'build.wordpress-develop.test', // VVV pattern.
1837
		);
1838 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1839
			return new \WP_Error(
1840
				'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...
1841
				sprintf(
1842
					/* translators: %1$s is a domain name. */
1843
					__(
1844
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1845
						'jetpack'
1846
					),
1847
					$domain
1848
				)
1849
			);
1850
		}
1851
1852
		// No .test or .local domains.
1853 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1854
			return new \WP_Error(
1855
				'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...
1856
				sprintf(
1857
					/* translators: %1$s is a domain name. */
1858
					__(
1859
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1860
						'jetpack'
1861
					),
1862
					$domain
1863
				)
1864
			);
1865
		}
1866
1867
		// No WPCOM subdomains.
1868 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1869
			return new \WP_Error(
1870
				'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...
1871
				sprintf(
1872
					/* translators: %1$s is a domain name. */
1873
					__(
1874
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1875
						'jetpack'
1876
					),
1877
					$domain
1878
				)
1879
			);
1880
		}
1881
1882
		// If PHP was compiled without support for the Filter module (very edge case).
1883
		if ( ! function_exists( 'filter_var' ) ) {
1884
			// Just pass back true for now, and let wpcom sort it out.
1885
			return true;
1886
		}
1887
1888
		return true;
1889
	}
1890
1891
	/**
1892
	 * Gets the requested token.
1893
	 *
1894
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_access_token() instead.
1895
	 *
1896
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1897
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1898
	 * @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.
1899
	 *
1900
	 * @return object|false
1901
	 *
1902
	 * @see $this->get_tokens()->get_access_token()
1903
	 */
1904
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1905
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_access_token' );
1906
		return $this->get_tokens()->get_access_token( $user_id, $token_key, $suppress_errors );
1907
	}
1908
1909
	/**
1910
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
1911
	 * since it is passed by reference to various methods.
1912
	 * Capture it here so we can verify the signature later.
1913
	 *
1914
	 * @param array $methods an array of available XMLRPC methods.
1915
	 * @return array the same array, since this method doesn't add or remove anything.
1916
	 */
1917
	public function xmlrpc_methods( $methods ) {
1918
		$this->raw_post_data = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
1919
		return $methods;
1920
	}
1921
1922
	/**
1923
	 * Resets the raw post data parameter for testing purposes.
1924
	 */
1925
	public function reset_raw_post_data() {
1926
		$this->raw_post_data = null;
1927
	}
1928
1929
	/**
1930
	 * Registering an additional method.
1931
	 *
1932
	 * @param array $methods an array of available XMLRPC methods.
1933
	 * @return array the amended array in case the method is added.
1934
	 */
1935
	public function public_xmlrpc_methods( $methods ) {
1936
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
1937
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
1938
		}
1939
		return $methods;
1940
	}
1941
1942
	/**
1943
	 * Handles a getOptions XMLRPC method call.
1944
	 *
1945
	 * @param array $args method call arguments.
1946
	 * @return an amended XMLRPC server options array.
1947
	 */
1948
	public function jetpack_get_options( $args ) {
1949
		global $wp_xmlrpc_server;
1950
1951
		$wp_xmlrpc_server->escape( $args );
1952
1953
		$username = $args[1];
1954
		$password = $args[2];
1955
1956
		$user = $wp_xmlrpc_server->login( $username, $password );
1957
		if ( ! $user ) {
1958
			return $wp_xmlrpc_server->error;
1959
		}
1960
1961
		$options   = array();
1962
		$user_data = $this->get_connected_user_data();
1963
		if ( is_array( $user_data ) ) {
1964
			$options['jetpack_user_id']         = array(
1965
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
1966
				'readonly' => true,
1967
				'value'    => $user_data['ID'],
1968
			);
1969
			$options['jetpack_user_login']      = array(
1970
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
1971
				'readonly' => true,
1972
				'value'    => $user_data['login'],
1973
			);
1974
			$options['jetpack_user_email']      = array(
1975
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
1976
				'readonly' => true,
1977
				'value'    => $user_data['email'],
1978
			);
1979
			$options['jetpack_user_site_count'] = array(
1980
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
1981
				'readonly' => true,
1982
				'value'    => $user_data['site_count'],
1983
			);
1984
		}
1985
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
1986
		$args                           = stripslashes_deep( $args );
1987
		return $wp_xmlrpc_server->wp_getOptions( $args );
1988
	}
1989
1990
	/**
1991
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
1992
	 *
1993
	 * @param array $options standard Core options.
1994
	 * @return array amended options.
1995
	 */
1996
	public function xmlrpc_options( $options ) {
1997
		$jetpack_client_id = false;
1998
		if ( $this->is_connected() ) {
1999
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2000
		}
2001
		$options['jetpack_version'] = array(
2002
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2003
			'readonly' => true,
2004
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2005
		);
2006
2007
		$options['jetpack_client_id'] = array(
2008
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2009
			'readonly' => true,
2010
			'value'    => $jetpack_client_id,
2011
		);
2012
		return $options;
2013
	}
2014
2015
	/**
2016
	 * Resets the saved authentication state in between testing requests.
2017
	 */
2018
	public function reset_saved_auth_state() {
2019
		$this->xmlrpc_verification = null;
2020
	}
2021
2022
	/**
2023
	 * Sign a user role with the master access token.
2024
	 * If not specified, will default to the current user.
2025
	 *
2026
	 * @access public
2027
	 *
2028
	 * @param string $role    User role.
2029
	 * @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...
2030
	 * @return string Signed user role.
2031
	 */
2032
	public function sign_role( $role, $user_id = null ) {
2033
		return $this->get_tokens()->sign_role( $role, $user_id );
2034
	}
2035
2036
	/**
2037
	 * Set the plugin instance.
2038
	 *
2039
	 * @param Plugin $plugin_instance The plugin instance.
2040
	 *
2041
	 * @return $this
2042
	 */
2043
	public function set_plugin_instance( Plugin $plugin_instance ) {
2044
		$this->plugin = $plugin_instance;
2045
2046
		return $this;
2047
	}
2048
2049
	/**
2050
	 * Retrieve the plugin management object.
2051
	 *
2052
	 * @return Plugin|null
2053
	 */
2054
	public function get_plugin() {
2055
		return $this->plugin;
2056
	}
2057
2058
	/**
2059
	 * Get all connected plugins information, excluding those disconnected by user.
2060
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2061
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2062
	 * so please make sure not to run the method too early in the code.
2063
	 *
2064
	 * @return array|WP_Error
2065
	 */
2066
	public function get_connected_plugins() {
2067
		$maybe_plugins = Plugin_Storage::get_all( true );
2068
2069
		if ( $maybe_plugins instanceof WP_Error ) {
2070
			return $maybe_plugins;
2071
		}
2072
2073
		return $maybe_plugins;
2074
	}
2075
2076
	/**
2077
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2078
	 * Note: this method does not remove any access tokens.
2079
	 *
2080
	 * @return bool
2081
	 */
2082
	public function disable_plugin() {
2083
		if ( ! $this->plugin ) {
2084
			return false;
2085
		}
2086
2087
		return $this->plugin->disable();
2088
	}
2089
2090
	/**
2091
	 * Force plugin reconnect after user-initiated disconnect.
2092
	 * After its called, the plugin will be allowed to use the connection again.
2093
	 * Note: this method does not initialize access tokens.
2094
	 *
2095
	 * @return bool
2096
	 */
2097
	public function enable_plugin() {
2098
		if ( ! $this->plugin ) {
2099
			return false;
2100
		}
2101
2102
		return $this->plugin->enable();
2103
	}
2104
2105
	/**
2106
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2107
	 * If no plugin slug was passed into the constructor, always returns true.
2108
	 *
2109
	 * @return bool
2110
	 */
2111
	public function is_plugin_enabled() {
2112
		if ( ! $this->plugin ) {
2113
			return true;
2114
		}
2115
2116
		return $this->plugin->is_enabled();
2117
	}
2118
2119
	/**
2120
	 * Perform the API request to refresh the blog token.
2121
	 * Note that we are making this request on behalf of the Jetpack master user,
2122
	 * given they were (most probably) the ones that registered the site at the first place.
2123
	 *
2124
	 * @return WP_Error|bool The result of updating the blog_token option.
2125
	 */
2126
	public function refresh_blog_token() {
2127
		( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
2128
2129
		$blog_id = \Jetpack_Options::get_option( 'id' );
2130
		if ( ! $blog_id ) {
2131
			return new WP_Error( 'site_not_registered', 'Site not registered.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'site_not_registered'.

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

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

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

Loading history...
2132
		}
2133
2134
		$url     = sprintf(
2135
			'%s/%s/v%s/%s',
2136
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
2137
			'wpcom',
2138
			'2',
2139
			'sites/' . $blog_id . '/jetpack-refresh-blog-token'
2140
		);
2141
		$method  = 'POST';
2142
		$user_id = get_current_user_id();
2143
2144
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2145
2146
		if ( is_wp_error( $response ) ) {
2147
			return new WP_Error( 'refresh_blog_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 'refresh_blog_token_http_request_failed'.

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

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

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

Loading history...
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...
2148
		}
2149
2150
		$code   = wp_remote_retrieve_response_code( $response );
2151
		$entity = wp_remote_retrieve_body( $response );
2152
2153
		if ( $entity ) {
2154
			$json = json_decode( $entity );
2155
		} else {
2156
			$json = false;
2157
		}
2158
2159 View Code Duplication
		if ( 200 !== $code ) {
2160
			if ( empty( $json->code ) ) {
2161
				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...
2162
			}
2163
2164
			/* translators: Error description string. */
2165
			$error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->message ) : '';
2166
2167
			return new WP_Error( (string) $json->code, $error_description, $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with (string) $json->code.

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

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

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

Loading history...
2168
		}
2169
2170
		if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
2171
			return new WP_Error( 'jetpack_secret', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_secret'.

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

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

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

Loading history...
2172
		}
2173
2174
		return $this->get_tokens()->update_blog_token( (string) $json->jetpack_secret );
2175
	}
2176
2177
	/**
2178
	 * Disconnect the user from WP.com, and initiate the reconnect process.
2179
	 *
2180
	 * @return bool
2181
	 */
2182
	public function refresh_user_token() {
2183
		( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2184
		$this->disconnect_user( null, true );
2185
		return true;
2186
	}
2187
2188
	/**
2189
	 * Fetches a signed token.
2190
	 *
2191
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_signed_token() instead.
2192
	 *
2193
	 * @param object $token the token.
2194
	 * @return WP_Error|string a signed token
2195
	 */
2196
	public function get_signed_token( $token ) {
2197
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_signed_token' );
2198
		return $this->get_tokens()->get_signed_token( $token );
2199
	}
2200
2201
	/**
2202
	 * If the site-level connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2203
	 *
2204
	 * @param array $stats The Heartbeat stats array.
2205
	 * @return array $stats
2206
	 */
2207
	public function add_stats_to_heartbeat( $stats ) {
2208
2209
		if ( ! $this->is_connected() ) {
2210
			return $stats;
2211
		}
2212
2213
		$active_plugins_using_connection = Plugin_Storage::get_all();
2214
		foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
2215
			if ( 'jetpack' !== $plugin_slug ) {
2216
				$stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2217
				$stats[ $stats_group ][] = $plugin_slug;
2218
			}
2219
		}
2220
		return $stats;
2221
	}
2222
}
2223