Completed
Push — renovate/size-limit-preset-app... ( d2e38f...0a830a )
by
unknown
84:30 queued 73:29
created

Manager::disconnect_user()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

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