Completed
Push — fix/close-button-bg-color ( da7e83...c55173 )
by
unknown
11:17
created

Manager::unlink_user_from_wpcom()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

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

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

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

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

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

An additional type check may prevent trouble.

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
92
93
		if ( $manager->is_connected() ) {
94
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
95
		}
96
97
		add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
98
99
		( new Nonce_Handler() )->init_schedule();
100
101
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
102
103
		add_filter( 'map_meta_cap', array( $manager, 'jetpack_connection_custom_caps' ), 1, 4 );
104
105
		Heartbeat::init();
106
		add_filter( 'jetpack_heartbeat_stats_array', array( $manager, 'add_stats_to_heartbeat' ) );
107
108
		Webhooks::init( $manager );
109
	}
110
111
	/**
112
	 * Sets up the XMLRPC request handlers.
113
	 *
114
	 * @since 9.6.0 Deprecate $is_active param.
115
	 *
116
	 * @param array                  $request_params incoming request parameters.
117
	 * @param bool                   $has_connected_owner Whether the site has a connected owner.
118
	 * @param bool                   $is_signed whether the signature check has been successful.
119
	 * @param \Jetpack_XMLRPC_Server $xmlrpc_server (optional) an instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|\Jetpack_XMLRPC_Server?

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

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

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

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

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

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

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
356
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
357
358
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
359
360
		if (
361
			empty( $token_key )
362
		||
363
			empty( $version ) || (string) $jetpack_api_version !== $version ) {
364
			return new \WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_token'.

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

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

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

Loading history...
365
		}
366
367
		if ( '0' === $user_id ) {
368
			$token_type = 'blog';
369
			$user_id    = 0;
370
		} else {
371
			$token_type = 'user';
372
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
373
				return new \WP_Error(
374
					'malformed_user_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_user_id'.

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

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

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

Loading history...
375
					'Malformed user_id in request',
376
					compact( 'signature_details' )
377
				);
378
			}
379
			$user_id = (int) $user_id;
380
381
			$user = new \WP_User( $user_id );
382
			if ( ! $user || ! $user->exists() ) {
383
				return new \WP_Error(
384
					'unknown_user',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_user'.

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

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

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

Loading history...
385
					sprintf( 'User %d does not exist', $user_id ),
386
					compact( 'signature_details' )
387
				);
388
			}
389
		}
390
391
		$token = $this->get_tokens()->get_access_token( $user_id, $token_key, false );
392
		if ( is_wp_error( $token ) ) {
393
			$token->add_data( compact( 'signature_details' ) );
394
			return $token;
395
		} elseif ( ! $token ) {
396
			return new \WP_Error(
397
				'unknown_token',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

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

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

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

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

Loading history...
440
				'Unknown signature error',
441
				compact( 'signature_details' )
442
			);
443
		} elseif ( is_wp_error( $signature ) ) {
444
			return $signature;
445
		}
446
447
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
448
		$timestamp = (int) $_GET['timestamp'];
449
		$nonce     = stripslashes( (string) $_GET['nonce'] );
450
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
451
452
		// Use up the nonce regardless of whether the signature matches.
453
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
454
			return new \WP_Error(
455
				'invalid_nonce',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

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

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

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

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

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

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

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

Loading history...
470
				'Signature mismatch',
471
				compact( 'signature_details' )
472
			);
473
		}
474
475
		/**
476
		 * Action for additional token checking.
477
		 *
478
		 * @since 7.7.0
479
		 *
480
		 * @param array $post_data request data.
481
		 * @param array $token_data token data.
482
		 */
483
		return apply_filters(
484
			'jetpack_signature_check_token',
485
			array(
486
				'type'      => $token_type,
487
				'token_key' => $token_key,
488
				'user_id'   => $token->external_user_id,
489
			),
490
			$token,
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $token.

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

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

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

Loading history...
491
			$this->raw_post_data
492
		);
493
	}
494
495
	/**
496
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI.
497
	 *
498
	 * This method is deprecated since Jetpack 9.6.0. Please use has_connected_owner instead.
499
	 *
500
	 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
501
	 *
502
	 * @deprecated 9.6.0
503
	 * @see Manager::has_connected_owner
504
	 * @return Boolean is the site connected?
505
	 */
506
	public function is_active() {
507
		return (bool) $this->get_tokens()->get_access_token( true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
508
	}
509
510
	/**
511
	 * Obtains an instance of the Tokens class.
512
	 *
513
	 * @return Tokens the Tokens object
514
	 */
515
	public function get_tokens() {
516
		return new Tokens();
517
	}
518
519
	/**
520
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
521
	 *
522
	 * @access public
523
	 * @deprecated 9.2.0 Use is_connected instead
524
	 * @see Manager::is_connected
525
	 *
526
	 * @return bool
527
	 */
528
	public function is_registered() {
529
		_deprecated_function( __METHOD__, 'jetpack-9.2' );
530
		return $this->is_connected();
531
	}
532
533
	/**
534
	 * Returns true if the site has both a token and a blog id, which indicates a site has been connected.
535
	 *
536
	 * @access public
537
	 * @since 9.2.0
538
	 *
539
	 * @return bool
540
	 */
541
	public function is_connected() {
542
		$has_blog_id    = (bool) \Jetpack_Options::get_option( 'id' );
543
		$has_blog_token = (bool) $this->get_tokens()->get_access_token();
544
		return $has_blog_id && $has_blog_token;
545
	}
546
547
	/**
548
	 * Returns true if the site has at least one connected administrator.
549
	 *
550
	 * @access public
551
	 * @since 9.2.0
552
	 *
553
	 * @return bool
554
	 */
555
	public function has_connected_admin() {
556
		return (bool) count( $this->get_connected_users( 'manage_options' ) );
557
	}
558
559
	/**
560
	 * Returns true if the site has any connected user.
561
	 *
562
	 * @access public
563
	 * @since 9.2.0
564
	 *
565
	 * @return bool
566
	 */
567
	public function has_connected_user() {
568
		return (bool) count( $this->get_connected_users() );
569
	}
570
571
	/**
572
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
573
	 * Able to select by specific capability.
574
	 *
575
	 * @param string $capability The capability of the user.
576
	 * @return array Array of WP_User objects if found.
577
	 */
578
	public function get_connected_users( $capability = 'any' ) {
579
		return $this->get_tokens()->get_connected_users( $capability );
580
	}
581
582
	/**
583
	 * Returns true if the site has a connected Blog owner (master_user).
584
	 *
585
	 * @access public
586
	 * @since 9.2.0
587
	 *
588
	 * @return bool
589
	 */
590
	public function has_connected_owner() {
591
		return (bool) $this->get_connection_owner_id();
592
	}
593
594
	/**
595
	 * Returns true if the site is connected only at a site level.
596
	 *
597
	 * Note that we are explicitly checking for the existence of the master_user option in order to account for cases where we don't have any user tokens (user-level connection) but the master_user option is set, which could be the result of a problematic user connection.
598
	 *
599
	 * @access public
600
	 * @since 9.6.0
601
	 * @deprecated 9.8.0
602
	 *
603
	 * @return bool
604
	 */
605
	public function is_userless() {
606
		_deprecated_function( __METHOD__, 'jetpack-9.8.0', 'Automattic\\Jetpack\\Connection\\Manager::is_site_connection' );
607
		return $this->is_site_connection();
608
	}
609
610
	/**
611
	 * Returns true if the site is connected only at a site level.
612
	 *
613
	 * Note that we are explicitly checking for the existence of the master_user option in order to account for cases where we don't have any user tokens (user-level connection) but the master_user option is set, which could be the result of a problematic user connection.
614
	 *
615
	 * @access public
616
	 * @since 9.8.0
617
	 *
618
	 * @return bool
619
	 */
620
	public function is_site_connection() {
621
		return $this->is_connected() && ! $this->has_connected_user() && ! \Jetpack_Options::get_option( 'master_user' );
622
	}
623
624
	/**
625
	 * Checks to see if the connection owner of the site is missing.
626
	 *
627
	 * @return bool
628
	 */
629
	public function is_missing_connection_owner() {
630
		$connection_owner = $this->get_connection_owner_id();
631
		if ( ! get_user_by( 'id', $connection_owner ) ) {
632
			return true;
633
		}
634
635
		return false;
636
	}
637
638
	/**
639
	 * Returns true if the user with the specified identifier is connected to
640
	 * WordPress.com.
641
	 *
642
	 * @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...
643
	 * @return bool Boolean is the user connected?
644
	 */
645
	public function is_user_connected( $user_id = false ) {
646
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
647
		if ( ! $user_id ) {
648
			return false;
649
		}
650
651
		return (bool) $this->get_tokens()->get_access_token( $user_id );
652
	}
653
654
	/**
655
	 * Returns the local user ID of the connection owner.
656
	 *
657
	 * @return bool|int Returns the ID of the connection owner or False if no connection owner found.
658
	 */
659
	public function get_connection_owner_id() {
660
		$owner = $this->get_connection_owner();
661
		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...
662
	}
663
664
	/**
665
	 * Get the wpcom user data of the current|specified connected user.
666
	 *
667
	 * @todo Refactor to properly load the XMLRPC client independently.
668
	 *
669
	 * @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...
670
	 * @return Object the user object.
671
	 */
672
	public function get_connected_user_data( $user_id = null ) {
673
		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...
674
			$user_id = get_current_user_id();
675
		}
676
677
		$transient_key    = "jetpack_connected_user_data_$user_id";
678
		$cached_user_data = get_transient( $transient_key );
679
680
		if ( $cached_user_data ) {
681
			return $cached_user_data;
682
		}
683
684
		$xml = new \Jetpack_IXR_Client(
685
			array(
686
				'user_id' => $user_id,
687
			)
688
		);
689
		$xml->query( 'wpcom.getUser' );
690
		if ( ! $xml->isError() ) {
691
			$user_data = $xml->getResponse();
692
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
693
			return $user_data;
694
		}
695
696
		return false;
697
	}
698
699
	/**
700
	 * Returns a user object of the connection owner.
701
	 *
702
	 * @return WP_User|false False if no connection owner found.
703
	 */
704
	public function get_connection_owner() {
705
706
		$user_id = \Jetpack_Options::get_option( 'master_user' );
707
708
		if ( ! $user_id ) {
709
			return false;
710
		}
711
712
		// Make sure user is connected.
713
		$user_token = $this->get_tokens()->get_access_token( $user_id );
714
715
		$connection_owner = false;
716
717
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
718
			$connection_owner = get_userdata( $user_token->external_user_id );
719
		}
720
721
		return $connection_owner;
722
	}
723
724
	/**
725
	 * Returns true if the provided user is the Jetpack connection owner.
726
	 * If user ID is not specified, the current user will be used.
727
	 *
728
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
729
	 * @return Boolean True the user the connection owner, false otherwise.
730
	 */
731
	public function is_connection_owner( $user_id = false ) {
732
		if ( ! $user_id ) {
733
			$user_id = get_current_user_id();
734
		}
735
736
		return ( (int) $user_id ) === $this->get_connection_owner_id();
737
	}
738
739
	/**
740
	 * Connects the user with a specified ID to a WordPress.com user using the
741
	 * remote login flow.
742
	 *
743
	 * @access public
744
	 *
745
	 * @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...
746
	 * @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...
747
	 *                              admin_url().
748
	 * @return WP_Error only in case of a failed user lookup.
749
	 */
750
	public function connect_user( $user_id = null, $redirect_url = null ) {
751
		$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...
752
		if ( null === $user_id ) {
753
			$user = wp_get_current_user();
754
		} else {
755
			$user = get_user_by( 'ID', $user_id );
756
		}
757
758
		if ( empty( $user ) ) {
759
			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...
760
		}
761
762
		if ( null === $redirect_url ) {
763
			$redirect_url = admin_url();
764
		}
765
766
		// Using wp_redirect intentionally because we're redirecting outside.
767
		wp_redirect( $this->get_authorization_url( $user, $redirect_url ) ); // phpcs:ignore WordPress.Security.SafeRedirect
768
		exit();
769
	}
770
771
	/**
772
	 * Unlinks the current user from the linked WordPress.com user.
773
	 *
774
	 * @access public
775
	 * @static
776
	 *
777
	 * @todo Refactor to properly load the XMLRPC client independently.
778
	 *
779
	 * @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...
780
	 * @param bool    $can_overwrite_primary_user Allow for the primary user to be disconnected.
781
	 * @return Boolean Whether the disconnection of the user was successful.
782
	 */
783
	public function disconnect_user( $user_id = null, $can_overwrite_primary_user = false ) {
784
		$user_id = empty( $user_id ) ? get_current_user_id() : (int) $user_id;
785
786
		// Attempt to disconnect the user from WordPress.com.
787
		$is_disconnected_from_wpcom = $this->unlink_user_from_wpcom( $user_id );
788
		if ( ! $is_disconnected_from_wpcom ) {
789
			return false;
790
		}
791
792
		// Disconnect the user locally.
793
		$is_disconnected_locally = $this->get_tokens()->disconnect_user( $user_id, $can_overwrite_primary_user );
794
		if ( $is_disconnected_locally ) {
795
			// Delete cached connected user data.
796
			$transient_key = "jetpack_connected_user_data_$user_id";
797
			delete_transient( $transient_key );
798
799
			/**
800
			 * Fires after the current user has been unlinked from WordPress.com.
801
			 *
802
			 * @since 4.1.0
803
			 *
804
			 * @param int $user_id The current user's ID.
805
			 */
806
			do_action( 'jetpack_unlinked_user', $user_id );
807
		}
808
809
		return $is_disconnected_locally;
810
	}
811
812
	/**
813
	 * Request to wpcom for a user to be unlinked from their WordPress.com account
814
	 *
815
	 * @access public
816
	 *
817
	 * @param Integer $user_id the user identifier.
818
	 *
819
	 * @return Boolean Whether the disconnection of the user was successful.
820
	 */
821
	public function unlink_user_from_wpcom( $user_id ) {
822
		// Attempt to disconnect the user from WordPress.com.
823
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
824
825
		$xml->query( 'jetpack.unlink_user', $user_id );
826
		if ( $xml->isError() ) {
827
			return false;
828
		}
829
830
		return (bool) $xml->getResponse();
831
	}
832
833
	/**
834
	 * Returns the requested Jetpack API URL.
835
	 *
836
	 * @param String $relative_url the relative API path.
837
	 * @return String API URL.
838
	 */
839
	public function api_url( $relative_url ) {
840
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
841
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
842
843
		/**
844
		 * Filters whether the connection manager should use the iframe authorization
845
		 * flow instead of the regular redirect-based flow.
846
		 *
847
		 * @since 8.3.0
848
		 *
849
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
850
		 */
851
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
852
853
		// Do not modify anything that is not related to authorize requests.
854
		if ( 'authorize' === $relative_url && $iframe_flow ) {
855
			$relative_url = 'authorize_iframe';
856
		}
857
858
		/**
859
		 * Filters the API URL that Jetpack uses for server communication.
860
		 *
861
		 * @since 8.0.0
862
		 *
863
		 * @param String $url the generated URL.
864
		 * @param String $relative_url the relative URL that was passed as an argument.
865
		 * @param String $api_base the API base string that is being used.
866
		 * @param String $api_version the API version string that is being used.
867
		 */
868
		return apply_filters(
869
			'jetpack_api_url',
870
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
871
			$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...
872
			$api_base,
873
			$api_version
874
		);
875
	}
876
877
	/**
878
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
879
	 *
880
	 * @return String XMLRPC API URL.
881
	 */
882
	public function xmlrpc_api_url() {
883
		$base = preg_replace(
884
			'#(https?://[^?/]+)(/?.*)?$#',
885
			'\\1',
886
			Constants::get_constant( 'JETPACK__API_BASE' )
887
		);
888
		return untrailingslashit( $base ) . '/xmlrpc.php';
889
	}
890
891
	/**
892
	 * Attempts Jetpack registration which sets up the site for connection. Should
893
	 * remain public because the call to action comes from the current site, not from
894
	 * WordPress.com.
895
	 *
896
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
897
	 * @return true|WP_Error The error object.
898
	 */
899
	public function register( $api_endpoint = 'register' ) {
900
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
901
		$secrets = ( new Secrets() )->generate( 'register', get_current_user_id(), 600 );
902
903
		if ( false === $secrets ) {
904
			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...
905
		}
906
907
		if (
908
			empty( $secrets['secret_1'] ) ||
909
			empty( $secrets['secret_2'] ) ||
910
			empty( $secrets['exp'] )
911
		) {
912
			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...
913
		}
914
915
		// Better to try (and fail) to set a higher timeout than this system
916
		// supports than to have register fail for more users than it should.
917
		$timeout = $this->set_min_time_limit( 60 ) / 2;
918
919
		$gmt_offset = get_option( 'gmt_offset' );
920
		if ( ! $gmt_offset ) {
921
			$gmt_offset = 0;
922
		}
923
924
		$stats_options = get_option( 'stats_options' );
925
		$stats_id      = isset( $stats_options['blog_id'] )
926
			? $stats_options['blog_id']
927
			: null;
928
929
		/**
930
		 * Filters the request body for additional property addition.
931
		 *
932
		 * @since 7.7.0
933
		 *
934
		 * @param array $post_data request data.
935
		 * @param Array $token_data token data.
936
		 */
937
		$body = apply_filters(
938
			'jetpack_register_request_body',
939
			array_merge(
940
				array(
941
					'siteurl'            => site_url(),
942
					'home'               => home_url(),
943
					'gmt_offset'         => $gmt_offset,
944
					'timezone_string'    => (string) get_option( 'timezone_string' ),
945
					'site_name'          => (string) get_option( 'blogname' ),
946
					'secret_1'           => $secrets['secret_1'],
947
					'secret_2'           => $secrets['secret_2'],
948
					'site_lang'          => get_locale(),
949
					'timeout'            => $timeout,
950
					'stats_id'           => $stats_id,
951
					'state'              => get_current_user_id(),
952
					'site_created'       => $this->get_assumed_site_creation_date(),
953
					'jetpack_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
954
					'ABSPATH'            => Constants::get_constant( 'ABSPATH' ),
955
					'current_user_email' => wp_get_current_user()->user_email,
956
					'connect_plugin'     => $this->get_plugin() ? $this->get_plugin()->get_slug() : null,
957
				),
958
				self::$extra_register_params
959
			)
960
		);
961
962
		$args = array(
963
			'method'  => 'POST',
964
			'body'    => $body,
965
			'headers' => array(
966
				'Accept' => 'application/json',
967
			),
968
			'timeout' => $timeout,
969
		);
970
971
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
972
973
		// TODO: fix URLs for bad hosts.
974
		$response = Client::_wp_remote_request(
975
			$this->api_url( $api_endpoint ),
976
			$args,
977
			true
978
		);
979
980
		// Make sure the response is valid and does not contain any Jetpack errors.
981
		$registration_details = $this->validate_remote_register_response( $response );
982
983
		if ( is_wp_error( $registration_details ) ) {
984
			return $registration_details;
985
		} elseif ( ! $registration_details ) {
986
			return new \WP_Error(
987
				'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...
988
				'Unknown error registering your Jetpack site.',
989
				wp_remote_retrieve_response_code( $response )
990
			);
991
		}
992
993
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
994
			return new \WP_Error(
995
				'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...
996
				'Unable to validate registration of your Jetpack site.',
997
				wp_remote_retrieve_response_code( $response )
998
			);
999
		}
1000
1001
		if ( isset( $registration_details->jetpack_public ) ) {
1002
			$jetpack_public = (int) $registration_details->jetpack_public;
1003
		} else {
1004
			$jetpack_public = false;
1005
		}
1006
1007
		\Jetpack_Options::update_options(
1008
			array(
1009
				'id'     => (int) $registration_details->jetpack_id,
1010
				'public' => $jetpack_public,
1011
			)
1012
		);
1013
1014
		$this->get_tokens()->update_blog_token( (string) $registration_details->jetpack_secret );
1015
1016
		/**
1017
		 * Fires when a site is registered on WordPress.com.
1018
		 *
1019
		 * @since 3.7.0
1020
		 *
1021
		 * @param int $json->jetpack_id Jetpack Blog ID.
1022
		 * @param string $json->jetpack_secret Jetpack Blog Token.
1023
		 * @param int|bool $jetpack_public Is the site public.
1024
		 */
1025
		do_action(
1026
			'jetpack_site_registered',
1027
			$registration_details->jetpack_id,
1028
			$registration_details->jetpack_secret,
1029
			$jetpack_public
1030
		);
1031
1032
		if ( isset( $registration_details->token ) ) {
1033
			/**
1034
			 * Fires when a user token is sent along with the registration data.
1035
			 *
1036
			 * @since 7.6.0
1037
			 *
1038
			 * @param object $token the administrator token for the newly registered site.
1039
			 */
1040
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
1041
		}
1042
1043
		return true;
1044
	}
1045
1046
	/**
1047
	 * Attempts Jetpack registration.
1048
	 *
1049
	 * @param bool $tos_agree Whether the user agreed to TOS.
1050
	 *
1051
	 * @return bool|WP_Error
1052
	 */
1053
	public function try_registration( $tos_agree = true ) {
1054
		if ( $tos_agree ) {
1055
			$terms_of_service = new Terms_Of_Service();
1056
			$terms_of_service->agree();
1057
		}
1058
1059
		/**
1060
		 * Action fired when the user attempts the registration.
1061
		 *
1062
		 * @since 9.7.0
1063
		 */
1064
		$pre_register = apply_filters( 'jetpack_pre_register', null );
1065
1066
		if ( is_wp_error( $pre_register ) ) {
1067
			return $pre_register;
1068
		}
1069
1070
		$tracking_data = array();
1071
1072
		if ( null !== $this->get_plugin() ) {
1073
			$tracking_data['plugin_slug'] = $this->get_plugin()->get_slug();
1074
		}
1075
1076
		$tracking = new Tracking();
1077
		$tracking->record_user_event( 'jpc_register_begin', $tracking_data );
1078
1079
		add_filter( 'jetpack_register_request_body', array( Utils::class, 'filter_register_request_body' ) );
1080
1081
		$result = $this->register();
1082
1083
		remove_filter( 'jetpack_register_request_body', array( Utils::class, 'filter_register_request_body' ) );
1084
1085
		// If there was an error with registration and the site was not registered, record this so we can show a message.
1086
		if ( ! $result || is_wp_error( $result ) ) {
1087
			return $result;
1088
		}
1089
1090
		return true;
1091
	}
1092
1093
	/**
1094
	 * Adds a parameter to the register request body
1095
	 *
1096
	 * @since 9.7.0
1097
	 *
1098
	 * @param string $name The name of the parameter to be added.
1099
	 * @param string $value The value of the parameter to be added.
1100
	 *
1101
	 * @throws \InvalidArgumentException If supplied arguments are not strings.
1102
	 * @return void
1103
	 */
1104
	public function add_register_request_param( $name, $value ) {
1105
		if ( ! is_string( $name ) || ! is_string( $value ) ) {
1106
			throw new \InvalidArgumentException( 'name and value must be strings' );
1107
		}
1108
		self::$extra_register_params[ $name ] = $value;
1109
	}
1110
1111
	/**
1112
	 * Takes the response from the Jetpack register new site endpoint and
1113
	 * verifies it worked properly.
1114
	 *
1115
	 * @since 2.6
1116
	 *
1117
	 * @param Mixed $response the response object, or the error object.
1118
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
1119
	 **/
1120
	protected function validate_remote_register_response( $response ) {
1121
		if ( is_wp_error( $response ) ) {
1122
			return new \WP_Error(
1123
				'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...
1124
				$response->get_error_message()
1125
			);
1126
		}
1127
1128
		$code   = wp_remote_retrieve_response_code( $response );
1129
		$entity = wp_remote_retrieve_body( $response );
1130
1131
		if ( $entity ) {
1132
			$registration_response = json_decode( $entity );
1133
		} else {
1134
			$registration_response = false;
1135
		}
1136
1137
		$code_type = (int) ( $code / 100 );
1138
		if ( 5 === $code_type ) {
1139
			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...
1140
		} elseif ( 408 === $code ) {
1141
			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...
1142
		} elseif ( ! empty( $registration_response->error ) ) {
1143
			if (
1144
				'xml_rpc-32700' === $registration_response->error
1145
				&& ! function_exists( 'xml_parser_create' )
1146
			) {
1147
				$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' );
1148
			} else {
1149
				$error_description = isset( $registration_response->error_description )
1150
					? (string) $registration_response->error_description
1151
					: '';
1152
			}
1153
1154
			return new \WP_Error(
1155
				(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...
1156
				$error_description,
1157
				$code
1158
			);
1159
		} elseif ( 200 !== $code ) {
1160
			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...
1161
		}
1162
1163
		// Jetpack ID error block.
1164
		if ( empty( $registration_response->jetpack_id ) ) {
1165
			return new \WP_Error(
1166
				'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...
1167
				/* translators: %s is an error message string */
1168
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1169
				$entity
1170
			);
1171
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1172
			return new \WP_Error(
1173
				'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...
1174
				/* translators: %s is an error message string */
1175
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1176
				$entity
1177
			);
1178 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1179
			return new \WP_Error(
1180
				'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...
1181
				/* translators: %s is an error message string */
1182
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1183
				$entity
1184
			);
1185
		}
1186
1187
		return $registration_response;
1188
	}
1189
1190
	/**
1191
	 * Adds a used nonce to a list of known nonces.
1192
	 *
1193
	 * @param int    $timestamp the current request timestamp.
1194
	 * @param string $nonce the nonce value.
1195
	 * @return bool whether the nonce is unique or not.
1196
	 *
1197
	 * @deprecated since 9.5.0
1198
	 * @see Nonce_Handler::add()
1199
	 */
1200
	public function add_nonce( $timestamp, $nonce ) {
1201
		_deprecated_function( __METHOD__, 'jetpack-9.5.0', 'Automattic\\Jetpack\\Connection\\Nonce_Handler::add' );
1202
		return ( new Nonce_Handler() )->add( $timestamp, $nonce );
1203
	}
1204
1205
	/**
1206
	 * Cleans nonces that were saved when calling ::add_nonce.
1207
	 *
1208
	 * @todo Properly prepare the query before executing it.
1209
	 *
1210
	 * @param bool $all whether to clean even non-expired nonces.
1211
	 *
1212
	 * @deprecated since 9.5.0
1213
	 * @see Nonce_Handler::clean_all()
1214
	 */
1215
	public function clean_nonces( $all = false ) {
1216
		_deprecated_function( __METHOD__, 'jetpack-9.5.0', 'Automattic\\Jetpack\\Connection\\Nonce_Handler::clean_all' );
1217
		( new Nonce_Handler() )->clean_all( $all ? PHP_INT_MAX : ( time() - Nonce_Handler::LIFETIME ) );
1218
	}
1219
1220
	/**
1221
	 * Sets the Connection custom capabilities.
1222
	 *
1223
	 * @param string[] $caps    Array of the user's capabilities.
1224
	 * @param string   $cap     Capability name.
1225
	 * @param int      $user_id The user ID.
1226
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1227
	 */
1228
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1229
		switch ( $cap ) {
1230
			case 'jetpack_connect':
1231
			case 'jetpack_reconnect':
1232
				$is_offline_mode = ( new Status() )->is_offline_mode();
1233
				if ( $is_offline_mode ) {
1234
					$caps = array( 'do_not_allow' );
1235
					break;
1236
				}
1237
				// Pass through. If it's not offline mode, these should match disconnect.
1238
				// Let users disconnect if it's offline mode, just in case things glitch.
1239
			case 'jetpack_disconnect':
1240
				/**
1241
				 * Filters the jetpack_disconnect capability.
1242
				 *
1243
				 * @since 8.7.0
1244
				 *
1245
				 * @param array An array containing the capability name.
1246
				 */
1247
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1248
				break;
1249 View Code Duplication
			case 'jetpack_connect_user':
1250
				$is_offline_mode = ( new Status() )->is_offline_mode();
1251
				if ( $is_offline_mode ) {
1252
					$caps = array( 'do_not_allow' );
1253
					break;
1254
				}
1255
				// With site connections in mind, non-admin users can connect their account only if a connection owner exists.
1256
				$caps = $this->has_connected_owner() ? array( 'read' ) : array( 'manage_options' );
1257
				break;
1258
		}
1259
		return $caps;
1260
	}
1261
1262
	/**
1263
	 * Builds the timeout limit for queries talking with the wpcom servers.
1264
	 *
1265
	 * Based on local php max_execution_time in php.ini
1266
	 *
1267
	 * @since 5.4
1268
	 * @return int
1269
	 **/
1270
	public function get_max_execution_time() {
1271
		$timeout = (int) ini_get( 'max_execution_time' );
1272
1273
		// Ensure exec time set in php.ini.
1274
		if ( ! $timeout ) {
1275
			$timeout = 30;
1276
		}
1277
		return $timeout;
1278
	}
1279
1280
	/**
1281
	 * Sets a minimum request timeout, and returns the current timeout
1282
	 *
1283
	 * @since 5.4
1284
	 * @param Integer $min_timeout the minimum timeout value.
1285
	 **/
1286 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1287
		$timeout = $this->get_max_execution_time();
1288
		if ( $timeout < $min_timeout ) {
1289
			$timeout = $min_timeout;
1290
			set_time_limit( $timeout );
1291
		}
1292
		return $timeout;
1293
	}
1294
1295
	/**
1296
	 * Get our assumed site creation date.
1297
	 * Calculated based on the earlier date of either:
1298
	 * - Earliest admin user registration date.
1299
	 * - Earliest date of post of any post type.
1300
	 *
1301
	 * @since 7.2.0
1302
	 *
1303
	 * @return string Assumed site creation date and time.
1304
	 */
1305
	public function get_assumed_site_creation_date() {
1306
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1307
		if ( ! empty( $cached_date ) ) {
1308
			return $cached_date;
1309
		}
1310
1311
		$earliest_registered_users  = get_users(
1312
			array(
1313
				'role'    => 'administrator',
1314
				'orderby' => 'user_registered',
1315
				'order'   => 'ASC',
1316
				'fields'  => array( 'user_registered' ),
1317
				'number'  => 1,
1318
			)
1319
		);
1320
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1321
1322
		$earliest_posts = get_posts(
1323
			array(
1324
				'posts_per_page' => 1,
1325
				'post_type'      => 'any',
1326
				'post_status'    => 'any',
1327
				'orderby'        => 'date',
1328
				'order'          => 'ASC',
1329
			)
1330
		);
1331
1332
		// If there are no posts at all, we'll count only on user registration date.
1333
		if ( $earliest_posts ) {
1334
			$earliest_post_date = $earliest_posts[0]->post_date;
1335
		} else {
1336
			$earliest_post_date = PHP_INT_MAX;
1337
		}
1338
1339
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1340
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1341
1342
		return $assumed_date;
1343
	}
1344
1345
	/**
1346
	 * Adds the activation source string as a parameter to passed arguments.
1347
	 *
1348
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1349
	 *
1350
	 * @param array $args arguments that need to have the source added.
1351
	 * @return array $amended arguments.
1352
	 */
1353 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1354
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1355
1356
		if ( $activation_source_name ) {
1357
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1358
			$args['_as'] = urlencode( $activation_source_name );
1359
		}
1360
1361
		if ( $activation_source_keyword ) {
1362
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1363
			$args['_ak'] = urlencode( $activation_source_keyword );
1364
		}
1365
1366
		return $args;
1367
	}
1368
1369
	/**
1370
	 * Generates two secret tokens and the end of life timestamp for them.
1371
	 *
1372
	 * @param String  $action  The action name.
1373
	 * @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...
1374
	 * @param Integer $exp     Expiration time in seconds.
1375
	 */
1376
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1377
		return ( new Secrets() )->generate( $action, $user_id, $exp );
1378
	}
1379
1380
	/**
1381
	 * Returns two secret tokens and the end of life timestamp for them.
1382
	 *
1383
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->get() instead.
1384
	 *
1385
	 * @param String  $action  The action name.
1386
	 * @param Integer $user_id The user identifier.
1387
	 * @return string|array an array of secrets or an error string.
1388
	 */
1389
	public function get_secrets( $action, $user_id ) {
1390
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->get' );
1391
		return ( new Secrets() )->get( $action, $user_id );
1392
	}
1393
1394
	/**
1395
	 * Deletes secret tokens in case they, for example, have expired.
1396
	 *
1397
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->delete() instead.
1398
	 *
1399
	 * @param String  $action  The action name.
1400
	 * @param Integer $user_id The user identifier.
1401
	 */
1402
	public function delete_secrets( $action, $user_id ) {
1403
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->delete' );
1404
		( new Secrets() )->delete( $action, $user_id );
1405
	}
1406
1407
	/**
1408
	 * Deletes all connection tokens and transients from the local Jetpack site.
1409
	 * If the plugin object has been provided in the constructor, the function first checks
1410
	 * whether it's the only active connection.
1411
	 * If there are any other connections, the function will do nothing and return `false`
1412
	 * (unless `$ignore_connected_plugins` is set to `true`).
1413
	 *
1414
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1415
	 *
1416
	 * @return bool True if disconnected successfully, false otherwise.
1417
	 */
1418
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1419
		// refuse to delete if we're not the last Jetpack plugin installed.
1420 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1421
			return false;
1422
		}
1423
1424
		/**
1425
		 * Fires upon the disconnect attempt.
1426
		 * Return `false` to prevent the disconnect.
1427
		 *
1428
		 * @since 8.7.0
1429
		 */
1430
		if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', true ) ) {
1431
			return false;
1432
		}
1433
1434
		\Jetpack_Options::delete_option(
1435
			array(
1436
				'master_user',
1437
				'time_diff',
1438
				'fallback_no_verify_ssl_certs',
1439
			)
1440
		);
1441
1442
		( new Secrets() )->delete_all();
1443
		$this->get_tokens()->delete_all();
1444
1445
		// Delete cached connected user data.
1446
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1447
		delete_transient( $transient_key );
1448
1449
		// Delete all XML-RPC errors.
1450
		Error_Handler::get_instance()->delete_all_errors();
1451
1452
		return true;
1453
	}
1454
1455
	/**
1456
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1457
	 * If the plugin object has been provided in the constructor, the function first check
1458
	 * whether it's the only active connection.
1459
	 * If there are any other connections, the function will do nothing and return `false`
1460
	 * (unless `$ignore_connected_plugins` is set to `true`).
1461
	 *
1462
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1463
	 *
1464
	 * @return bool True if disconnected successfully, false otherwise.
1465
	 */
1466
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1467 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1468
			return false;
1469
		}
1470
1471
		/**
1472
		 * Fires upon the disconnect attempt.
1473
		 * Return `false` to prevent the disconnect.
1474
		 *
1475
		 * @since 8.7.0
1476
		 */
1477
		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...
1478
			return false;
1479
		}
1480
1481
		$xml = new \Jetpack_IXR_Client();
1482
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1483
1484
		return true;
1485
	}
1486
1487
	/**
1488
	 * Disconnect the plugin and remove the tokens.
1489
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1490
	 * This is a proxy method to simplify the Connection package API.
1491
	 *
1492
	 * @see Manager::disable_plugin()
1493
	 * @see Manager::disconnect_site_wpcom()
1494
	 * @see Manager::delete_all_connection_tokens()
1495
	 *
1496
	 * @return bool
1497
	 */
1498
	public function remove_connection() {
1499
		$this->disable_plugin();
1500
		$this->disconnect_site_wpcom();
1501
		$this->delete_all_connection_tokens();
1502
1503
		return true;
1504
	}
1505
1506
	/**
1507
	 * Completely clearing up the connection, and initiating reconnect.
1508
	 *
1509
	 * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
1510
	 */
1511
	public function reconnect() {
1512
		( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
1513
1514
		$this->disconnect_site_wpcom( true );
1515
		$this->delete_all_connection_tokens( true );
1516
1517
		return $this->register();
1518
	}
1519
1520
	/**
1521
	 * Validate the tokens, and refresh the invalid ones.
1522
	 *
1523
	 * @return string|bool|WP_Error True if connection restored or string indicating what's to be done next. A `WP_Error` object or false otherwise.
1524
	 */
1525
	public function restore() {
1526
		// If this is a site connection we need to trigger a full reconnection as our only secure means of
1527
		// communication with WPCOM, aka the blog token, is compromised.
1528
		if ( $this->is_site_connection() ) {
1529
			return $this->reconnect();
1530
		}
1531
1532
		$validate_tokens_response = $this->get_tokens()->validate();
1533
1534
		// If token validation failed, trigger a full reconnection.
1535
		if ( is_array( $validate_tokens_response ) &&
1536
			isset( $validate_tokens_response['blog_token']['is_healthy'] ) &&
1537
			isset( $validate_tokens_response['user_token']['is_healthy'] ) ) {
1538
			$blog_token_healthy = $validate_tokens_response['blog_token']['is_healthy'];
1539
			$user_token_healthy = $validate_tokens_response['user_token']['is_healthy'];
1540
		} else {
1541
			$blog_token_healthy = false;
1542
			$user_token_healthy = false;
1543
		}
1544
1545
		// Tokens are both valid, or both invalid. We can't fix the problem we don't see, so the full reconnection is needed.
1546
		if ( $blog_token_healthy === $user_token_healthy ) {
1547
			$result = $this->reconnect();
1548
			return ( true === $result ) ? 'authorize' : $result;
1549
		}
1550
1551
		if ( ! $blog_token_healthy ) {
1552
			return $this->refresh_blog_token();
1553
		}
1554
1555
		if ( ! $user_token_healthy ) {
1556
			return ( true === $this->refresh_user_token() ) ? 'authorize' : false;
1557
		}
1558
1559
		return false;
1560
	}
1561
1562
	/**
1563
	 * Responds to a WordPress.com call to register the current site.
1564
	 * Should be changed to protected.
1565
	 *
1566
	 * @param array $registration_data Array of [ secret_1, user_id ].
1567
	 */
1568
	public function handle_registration( array $registration_data ) {
1569
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1570
		if ( empty( $registration_user_id ) ) {
1571
			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...
1572
		}
1573
1574
		return ( new Secrets() )->verify( 'register', $registration_secret_1, (int) $registration_user_id );
1575
	}
1576
1577
	/**
1578
	 * Perform the API request to validate the blog and user tokens.
1579
	 *
1580
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->validate_tokens() instead.
1581
	 *
1582
	 * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
1583
	 *
1584
	 * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
1585
	 */
1586
	public function validate_tokens( $user_id = null ) {
1587
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->validate' );
1588
		return $this->get_tokens()->validate( $user_id );
1589
	}
1590
1591
	/**
1592
	 * Verify a Previously Generated Secret.
1593
	 *
1594
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->verify() instead.
1595
	 *
1596
	 * @param string $action   The type of secret to verify.
1597
	 * @param string $secret_1 The secret string to compare to what is stored.
1598
	 * @param int    $user_id  The user ID of the owner of the secret.
1599
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1600
	 */
1601
	public function verify_secrets( $action, $secret_1, $user_id ) {
1602
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->verify' );
1603
		return ( new Secrets() )->verify( $action, $secret_1, $user_id );
1604
	}
1605
1606
	/**
1607
	 * Responds to a WordPress.com call to authorize the current user.
1608
	 * Should be changed to protected.
1609
	 */
1610
	public function handle_authorization() {
1611
1612
	}
1613
1614
	/**
1615
	 * Obtains the auth token.
1616
	 *
1617
	 * @param array $data The request data.
1618
	 * @return object|\WP_Error Returns the auth token on success.
1619
	 *                          Returns a \WP_Error on failure.
1620
	 */
1621
	public function get_token( $data ) {
1622
		return $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1623
	}
1624
1625
	/**
1626
	 * Builds a URL to the Jetpack connection auth page.
1627
	 *
1628
	 * @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...
1629
	 * @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...
1630
	 * @return string Connect URL.
1631
	 */
1632
	public function get_authorization_url( $user = null, $redirect = null ) {
1633
		if ( empty( $user ) ) {
1634
			$user = wp_get_current_user();
1635
		}
1636
1637
		$roles       = new Roles();
1638
		$role        = $roles->translate_user_to_role( $user );
1639
		$signed_role = $this->get_tokens()->sign_role( $role );
1640
1641
		/**
1642
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1643
		 * data processing.
1644
		 *
1645
		 * @since 8.0.0
1646
		 *
1647
		 * @param string $redirect_url Defaults to the site admin URL.
1648
		 */
1649
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1650
1651
		/**
1652
		 * Filter the URL to redirect the user back to when the authorization process
1653
		 * is complete.
1654
		 *
1655
		 * @since 8.0.0
1656
		 *
1657
		 * @param string $redirect_url Defaults to the site URL.
1658
		 */
1659
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1660
1661
		$secrets = ( new Secrets() )->generate( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1662
1663
		/**
1664
		 * Filter the type of authorization.
1665
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1666
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1667
		 *
1668
		 * @since 4.3.3
1669
		 *
1670
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1671
		 */
1672
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1673
1674
		/**
1675
		 * Filters the user connection request data for additional property addition.
1676
		 *
1677
		 * @since 8.0.0
1678
		 *
1679
		 * @param array $request_data request data.
1680
		 */
1681
		$body = apply_filters(
1682
			'jetpack_connect_request_body',
1683
			array(
1684
				'response_type'         => 'code',
1685
				'client_id'             => \Jetpack_Options::get_option( 'id' ),
1686
				'redirect_uri'          => add_query_arg(
1687
					array(
1688
						'handler'  => 'jetpack-connection-webhooks',
1689
						'action'   => 'authorize',
1690
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1691
						'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1692
					),
1693
					esc_url( $processing_url )
1694
				),
1695
				'state'                 => $user->ID,
1696
				'scope'                 => $signed_role,
1697
				'user_email'            => $user->user_email,
1698
				'user_login'            => $user->user_login,
1699
				'is_active'             => $this->is_active(), // TODO Deprecate this.
0 ignored issues
show
Deprecated Code introduced by
The method Automattic\Jetpack\Connection\Manager::is_active() has been deprecated with message: 9.6.0

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

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

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