Completed
Push — add/testing-info ( be1095...03b7e9 )
by
unknown
09:20
created

Manager::get_token()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 3
rs 10
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'            => Urls::site_url(),
942
					'home'               => Urls::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
		$allow_inplace_authorization = isset( $registration_details->allow_inplace_authorization ) ? $registration_details->allow_inplace_authorization : false;
1017
		$alternate_authorization_url = isset( $registration_details->alternate_authorization_url ) ? $registration_details->alternate_authorization_url : '';
1018
1019
		if ( ! $allow_inplace_authorization ) {
1020
			// Forces register_site REST endpoint to return the Calypso authorization URL.
1021
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_false', 20 );
1022
		}
1023
1024
		add_filter(
1025
			'jetpack_register_site_rest_response',
1026
			function ( $response ) use ( $allow_inplace_authorization, $alternate_authorization_url ) {
1027
				$response['allowInplaceAuthorization'] = $allow_inplace_authorization;
1028
				$response['alternateAuthorizeUrl']     = $alternate_authorization_url;
1029
				return $response;
1030
			}
1031
		);
1032
1033
		/**
1034
		 * Fires when a site is registered on WordPress.com.
1035
		 *
1036
		 * @since 3.7.0
1037
		 *
1038
		 * @param int $json->jetpack_id Jetpack Blog ID.
1039
		 * @param string $json->jetpack_secret Jetpack Blog Token.
1040
		 * @param int|bool $jetpack_public Is the site public.
1041
		 */
1042
		do_action(
1043
			'jetpack_site_registered',
1044
			$registration_details->jetpack_id,
1045
			$registration_details->jetpack_secret,
1046
			$jetpack_public
1047
		);
1048
1049
		if ( isset( $registration_details->token ) ) {
1050
			/**
1051
			 * Fires when a user token is sent along with the registration data.
1052
			 *
1053
			 * @since 7.6.0
1054
			 *
1055
			 * @param object $token the administrator token for the newly registered site.
1056
			 */
1057
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
1058
		}
1059
1060
		return true;
1061
	}
1062
1063
	/**
1064
	 * Attempts Jetpack registration.
1065
	 *
1066
	 * @param bool $tos_agree Whether the user agreed to TOS.
1067
	 *
1068
	 * @return bool|WP_Error
1069
	 */
1070
	public function try_registration( $tos_agree = true ) {
1071
		if ( $tos_agree ) {
1072
			$terms_of_service = new Terms_Of_Service();
1073
			$terms_of_service->agree();
1074
		}
1075
1076
		/**
1077
		 * Action fired when the user attempts the registration.
1078
		 *
1079
		 * @since 9.7.0
1080
		 */
1081
		$pre_register = apply_filters( 'jetpack_pre_register', null );
1082
1083
		if ( is_wp_error( $pre_register ) ) {
1084
			return $pre_register;
1085
		}
1086
1087
		$tracking_data = array();
1088
1089
		if ( null !== $this->get_plugin() ) {
1090
			$tracking_data['plugin_slug'] = $this->get_plugin()->get_slug();
1091
		}
1092
1093
		$tracking = new Tracking();
1094
		$tracking->record_user_event( 'jpc_register_begin', $tracking_data );
1095
1096
		add_filter( 'jetpack_register_request_body', array( Utils::class, 'filter_register_request_body' ) );
1097
1098
		$result = $this->register();
1099
1100
		remove_filter( 'jetpack_register_request_body', array( Utils::class, 'filter_register_request_body' ) );
1101
1102
		// If there was an error with registration and the site was not registered, record this so we can show a message.
1103
		if ( ! $result || is_wp_error( $result ) ) {
1104
			return $result;
1105
		}
1106
1107
		return true;
1108
	}
1109
1110
	/**
1111
	 * Adds a parameter to the register request body
1112
	 *
1113
	 * @since 9.7.0
1114
	 *
1115
	 * @param string $name The name of the parameter to be added.
1116
	 * @param string $value The value of the parameter to be added.
1117
	 *
1118
	 * @throws \InvalidArgumentException If supplied arguments are not strings.
1119
	 * @return void
1120
	 */
1121
	public function add_register_request_param( $name, $value ) {
1122
		if ( ! is_string( $name ) || ! is_string( $value ) ) {
1123
			throw new \InvalidArgumentException( 'name and value must be strings' );
1124
		}
1125
		self::$extra_register_params[ $name ] = $value;
1126
	}
1127
1128
	/**
1129
	 * Takes the response from the Jetpack register new site endpoint and
1130
	 * verifies it worked properly.
1131
	 *
1132
	 * @since 2.6
1133
	 *
1134
	 * @param Mixed $response the response object, or the error object.
1135
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
1136
	 **/
1137
	protected function validate_remote_register_response( $response ) {
1138
		if ( is_wp_error( $response ) ) {
1139
			return new \WP_Error(
1140
				'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...
1141
				$response->get_error_message()
1142
			);
1143
		}
1144
1145
		$code   = wp_remote_retrieve_response_code( $response );
1146
		$entity = wp_remote_retrieve_body( $response );
1147
1148
		if ( $entity ) {
1149
			$registration_response = json_decode( $entity );
1150
		} else {
1151
			$registration_response = false;
1152
		}
1153
1154
		$code_type = (int) ( $code / 100 );
1155
		if ( 5 === $code_type ) {
1156
			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...
1157
		} elseif ( 408 === $code ) {
1158
			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...
1159
		} elseif ( ! empty( $registration_response->error ) ) {
1160
			if (
1161
				'xml_rpc-32700' === $registration_response->error
1162
				&& ! function_exists( 'xml_parser_create' )
1163
			) {
1164
				$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' );
1165
			} else {
1166
				$error_description = isset( $registration_response->error_description )
1167
					? (string) $registration_response->error_description
1168
					: '';
1169
			}
1170
1171
			return new \WP_Error(
1172
				(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...
1173
				$error_description,
1174
				$code
1175
			);
1176
		} elseif ( 200 !== $code ) {
1177
			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...
1178
		}
1179
1180
		// Jetpack ID error block.
1181
		if ( empty( $registration_response->jetpack_id ) ) {
1182
			return new \WP_Error(
1183
				'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...
1184
				/* translators: %s is an error message string */
1185
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1186
				$entity
1187
			);
1188
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1189
			return new \WP_Error(
1190
				'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...
1191
				/* translators: %s is an error message string */
1192
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1193
				$entity
1194
			);
1195 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1196
			return new \WP_Error(
1197
				'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...
1198
				/* translators: %s is an error message string */
1199
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1200
				$entity
1201
			);
1202
		}
1203
1204
		return $registration_response;
1205
	}
1206
1207
	/**
1208
	 * Adds a used nonce to a list of known nonces.
1209
	 *
1210
	 * @param int    $timestamp the current request timestamp.
1211
	 * @param string $nonce the nonce value.
1212
	 * @return bool whether the nonce is unique or not.
1213
	 *
1214
	 * @deprecated since 9.5.0
1215
	 * @see Nonce_Handler::add()
1216
	 */
1217
	public function add_nonce( $timestamp, $nonce ) {
1218
		_deprecated_function( __METHOD__, 'jetpack-9.5.0', 'Automattic\\Jetpack\\Connection\\Nonce_Handler::add' );
1219
		return ( new Nonce_Handler() )->add( $timestamp, $nonce );
1220
	}
1221
1222
	/**
1223
	 * Cleans nonces that were saved when calling ::add_nonce.
1224
	 *
1225
	 * @todo Properly prepare the query before executing it.
1226
	 *
1227
	 * @param bool $all whether to clean even non-expired nonces.
1228
	 *
1229
	 * @deprecated since 9.5.0
1230
	 * @see Nonce_Handler::clean_all()
1231
	 */
1232
	public function clean_nonces( $all = false ) {
1233
		_deprecated_function( __METHOD__, 'jetpack-9.5.0', 'Automattic\\Jetpack\\Connection\\Nonce_Handler::clean_all' );
1234
		( new Nonce_Handler() )->clean_all( $all ? PHP_INT_MAX : ( time() - Nonce_Handler::LIFETIME ) );
1235
	}
1236
1237
	/**
1238
	 * Sets the Connection custom capabilities.
1239
	 *
1240
	 * @param string[] $caps    Array of the user's capabilities.
1241
	 * @param string   $cap     Capability name.
1242
	 * @param int      $user_id The user ID.
1243
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1244
	 */
1245
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1246
		switch ( $cap ) {
1247
			case 'jetpack_connect':
1248
			case 'jetpack_reconnect':
1249
				$is_offline_mode = ( new Status() )->is_offline_mode();
1250
				if ( $is_offline_mode ) {
1251
					$caps = array( 'do_not_allow' );
1252
					break;
1253
				}
1254
				// Pass through. If it's not offline mode, these should match disconnect.
1255
				// Let users disconnect if it's offline mode, just in case things glitch.
1256
			case 'jetpack_disconnect':
1257
				/**
1258
				 * Filters the jetpack_disconnect capability.
1259
				 *
1260
				 * @since 8.7.0
1261
				 *
1262
				 * @param array An array containing the capability name.
1263
				 */
1264
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1265
				break;
1266 View Code Duplication
			case 'jetpack_connect_user':
1267
				$is_offline_mode = ( new Status() )->is_offline_mode();
1268
				if ( $is_offline_mode ) {
1269
					$caps = array( 'do_not_allow' );
1270
					break;
1271
				}
1272
				// With site connections in mind, non-admin users can connect their account only if a connection owner exists.
1273
				$caps = $this->has_connected_owner() ? array( 'read' ) : array( 'manage_options' );
1274
				break;
1275
		}
1276
		return $caps;
1277
	}
1278
1279
	/**
1280
	 * Builds the timeout limit for queries talking with the wpcom servers.
1281
	 *
1282
	 * Based on local php max_execution_time in php.ini
1283
	 *
1284
	 * @since 5.4
1285
	 * @return int
1286
	 **/
1287
	public function get_max_execution_time() {
1288
		$timeout = (int) ini_get( 'max_execution_time' );
1289
1290
		// Ensure exec time set in php.ini.
1291
		if ( ! $timeout ) {
1292
			$timeout = 30;
1293
		}
1294
		return $timeout;
1295
	}
1296
1297
	/**
1298
	 * Sets a minimum request timeout, and returns the current timeout
1299
	 *
1300
	 * @since 5.4
1301
	 * @param Integer $min_timeout the minimum timeout value.
1302
	 **/
1303 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1304
		$timeout = $this->get_max_execution_time();
1305
		if ( $timeout < $min_timeout ) {
1306
			$timeout = $min_timeout;
1307
			set_time_limit( $timeout );
1308
		}
1309
		return $timeout;
1310
	}
1311
1312
	/**
1313
	 * Get our assumed site creation date.
1314
	 * Calculated based on the earlier date of either:
1315
	 * - Earliest admin user registration date.
1316
	 * - Earliest date of post of any post type.
1317
	 *
1318
	 * @since 7.2.0
1319
	 *
1320
	 * @return string Assumed site creation date and time.
1321
	 */
1322
	public function get_assumed_site_creation_date() {
1323
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1324
		if ( ! empty( $cached_date ) ) {
1325
			return $cached_date;
1326
		}
1327
1328
		$earliest_registered_users  = get_users(
1329
			array(
1330
				'role'    => 'administrator',
1331
				'orderby' => 'user_registered',
1332
				'order'   => 'ASC',
1333
				'fields'  => array( 'user_registered' ),
1334
				'number'  => 1,
1335
			)
1336
		);
1337
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1338
1339
		$earliest_posts = get_posts(
1340
			array(
1341
				'posts_per_page' => 1,
1342
				'post_type'      => 'any',
1343
				'post_status'    => 'any',
1344
				'orderby'        => 'date',
1345
				'order'          => 'ASC',
1346
			)
1347
		);
1348
1349
		// If there are no posts at all, we'll count only on user registration date.
1350
		if ( $earliest_posts ) {
1351
			$earliest_post_date = $earliest_posts[0]->post_date;
1352
		} else {
1353
			$earliest_post_date = PHP_INT_MAX;
1354
		}
1355
1356
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1357
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1358
1359
		return $assumed_date;
1360
	}
1361
1362
	/**
1363
	 * Adds the activation source string as a parameter to passed arguments.
1364
	 *
1365
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1366
	 *
1367
	 * @param array $args arguments that need to have the source added.
1368
	 * @return array $amended arguments.
1369
	 */
1370 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1371
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1372
1373
		if ( $activation_source_name ) {
1374
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1375
			$args['_as'] = urlencode( $activation_source_name );
1376
		}
1377
1378
		if ( $activation_source_keyword ) {
1379
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1380
			$args['_ak'] = urlencode( $activation_source_keyword );
1381
		}
1382
1383
		return $args;
1384
	}
1385
1386
	/**
1387
	 * Generates two secret tokens and the end of life timestamp for them.
1388
	 *
1389
	 * @param String  $action  The action name.
1390
	 * @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...
1391
	 * @param Integer $exp     Expiration time in seconds.
1392
	 */
1393
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1394
		return ( new Secrets() )->generate( $action, $user_id, $exp );
1395
	}
1396
1397
	/**
1398
	 * Returns two secret tokens and the end of life timestamp for them.
1399
	 *
1400
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->get() instead.
1401
	 *
1402
	 * @param String  $action  The action name.
1403
	 * @param Integer $user_id The user identifier.
1404
	 * @return string|array an array of secrets or an error string.
1405
	 */
1406
	public function get_secrets( $action, $user_id ) {
1407
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->get' );
1408
		return ( new Secrets() )->get( $action, $user_id );
1409
	}
1410
1411
	/**
1412
	 * Deletes secret tokens in case they, for example, have expired.
1413
	 *
1414
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->delete() instead.
1415
	 *
1416
	 * @param String  $action  The action name.
1417
	 * @param Integer $user_id The user identifier.
1418
	 */
1419
	public function delete_secrets( $action, $user_id ) {
1420
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->delete' );
1421
		( new Secrets() )->delete( $action, $user_id );
1422
	}
1423
1424
	/**
1425
	 * Deletes all connection tokens and transients from the local Jetpack site.
1426
	 * If the plugin object has been provided in the constructor, the function first checks
1427
	 * whether it's the only active connection.
1428
	 * If there are any other connections, the function will do nothing and return `false`
1429
	 * (unless `$ignore_connected_plugins` is set to `true`).
1430
	 *
1431
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1432
	 *
1433
	 * @return bool True if disconnected successfully, false otherwise.
1434
	 */
1435
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1436
		// refuse to delete if we're not the last Jetpack plugin installed.
1437 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1438
			return false;
1439
		}
1440
1441
		/**
1442
		 * Fires upon the disconnect attempt.
1443
		 * Return `false` to prevent the disconnect.
1444
		 *
1445
		 * @since 8.7.0
1446
		 */
1447
		if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', true ) ) {
1448
			return false;
1449
		}
1450
1451
		\Jetpack_Options::delete_option(
1452
			array(
1453
				'master_user',
1454
				'time_diff',
1455
				'fallback_no_verify_ssl_certs',
1456
			)
1457
		);
1458
1459
		( new Secrets() )->delete_all();
1460
		$this->get_tokens()->delete_all();
1461
1462
		// Delete cached connected user data.
1463
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1464
		delete_transient( $transient_key );
1465
1466
		// Delete all XML-RPC errors.
1467
		Error_Handler::get_instance()->delete_all_errors();
1468
1469
		return true;
1470
	}
1471
1472
	/**
1473
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1474
	 * If the plugin object has been provided in the constructor, the function first check
1475
	 * whether it's the only active connection.
1476
	 * If there are any other connections, the function will do nothing and return `false`
1477
	 * (unless `$ignore_connected_plugins` is set to `true`).
1478
	 *
1479
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1480
	 *
1481
	 * @return bool True if disconnected successfully, false otherwise.
1482
	 */
1483
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1484 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1485
			return false;
1486
		}
1487
1488
		/**
1489
		 * Fires upon the disconnect attempt.
1490
		 * Return `false` to prevent the disconnect.
1491
		 *
1492
		 * @since 8.7.0
1493
		 */
1494
		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...
1495
			return false;
1496
		}
1497
1498
		$xml = new \Jetpack_IXR_Client();
1499
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1500
1501
		return true;
1502
	}
1503
1504
	/**
1505
	 * Disconnect the plugin and remove the tokens.
1506
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1507
	 * This is a proxy method to simplify the Connection package API.
1508
	 *
1509
	 * @see Manager::disable_plugin()
1510
	 * @see Manager::disconnect_site_wpcom()
1511
	 * @see Manager::delete_all_connection_tokens()
1512
	 *
1513
	 * @return bool
1514
	 */
1515
	public function remove_connection() {
1516
		$this->disable_plugin();
1517
		$this->disconnect_site_wpcom();
1518
		$this->delete_all_connection_tokens();
1519
1520
		return true;
1521
	}
1522
1523
	/**
1524
	 * Completely clearing up the connection, and initiating reconnect.
1525
	 *
1526
	 * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
1527
	 */
1528
	public function reconnect() {
1529
		( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
1530
1531
		$this->disconnect_site_wpcom( true );
1532
		$this->delete_all_connection_tokens( true );
1533
1534
		return $this->register();
1535
	}
1536
1537
	/**
1538
	 * Validate the tokens, and refresh the invalid ones.
1539
	 *
1540
	 * @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.
1541
	 */
1542
	public function restore() {
1543
		// If this is a site connection we need to trigger a full reconnection as our only secure means of
1544
		// communication with WPCOM, aka the blog token, is compromised.
1545
		if ( $this->is_site_connection() ) {
1546
			return $this->reconnect();
1547
		}
1548
1549
		$validate_tokens_response = $this->get_tokens()->validate();
1550
1551
		// If token validation failed, trigger a full reconnection.
1552
		if ( is_array( $validate_tokens_response ) &&
1553
			isset( $validate_tokens_response['blog_token']['is_healthy'] ) &&
1554
			isset( $validate_tokens_response['user_token']['is_healthy'] ) ) {
1555
			$blog_token_healthy = $validate_tokens_response['blog_token']['is_healthy'];
1556
			$user_token_healthy = $validate_tokens_response['user_token']['is_healthy'];
1557
		} else {
1558
			$blog_token_healthy = false;
1559
			$user_token_healthy = false;
1560
		}
1561
1562
		// Tokens are both valid, or both invalid. We can't fix the problem we don't see, so the full reconnection is needed.
1563
		if ( $blog_token_healthy === $user_token_healthy ) {
1564
			$result = $this->reconnect();
1565
			return ( true === $result ) ? 'authorize' : $result;
1566
		}
1567
1568
		if ( ! $blog_token_healthy ) {
1569
			return $this->refresh_blog_token();
1570
		}
1571
1572
		if ( ! $user_token_healthy ) {
1573
			return ( true === $this->refresh_user_token() ) ? 'authorize' : false;
1574
		}
1575
1576
		return false;
1577
	}
1578
1579
	/**
1580
	 * Responds to a WordPress.com call to register the current site.
1581
	 * Should be changed to protected.
1582
	 *
1583
	 * @param array $registration_data Array of [ secret_1, user_id ].
1584
	 */
1585
	public function handle_registration( array $registration_data ) {
1586
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1587
		if ( empty( $registration_user_id ) ) {
1588
			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...
1589
		}
1590
1591
		return ( new Secrets() )->verify( 'register', $registration_secret_1, (int) $registration_user_id );
1592
	}
1593
1594
	/**
1595
	 * Perform the API request to validate the blog and user tokens.
1596
	 *
1597
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->validate_tokens() instead.
1598
	 *
1599
	 * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
1600
	 *
1601
	 * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
1602
	 */
1603
	public function validate_tokens( $user_id = null ) {
1604
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->validate' );
1605
		return $this->get_tokens()->validate( $user_id );
1606
	}
1607
1608
	/**
1609
	 * Verify a Previously Generated Secret.
1610
	 *
1611
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->verify() instead.
1612
	 *
1613
	 * @param string $action   The type of secret to verify.
1614
	 * @param string $secret_1 The secret string to compare to what is stored.
1615
	 * @param int    $user_id  The user ID of the owner of the secret.
1616
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1617
	 */
1618
	public function verify_secrets( $action, $secret_1, $user_id ) {
1619
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->verify' );
1620
		return ( new Secrets() )->verify( $action, $secret_1, $user_id );
1621
	}
1622
1623
	/**
1624
	 * Responds to a WordPress.com call to authorize the current user.
1625
	 * Should be changed to protected.
1626
	 */
1627
	public function handle_authorization() {
1628
1629
	}
1630
1631
	/**
1632
	 * Obtains the auth token.
1633
	 *
1634
	 * @param array $data The request data.
1635
	 * @return object|\WP_Error Returns the auth token on success.
1636
	 *                          Returns a \WP_Error on failure.
1637
	 */
1638
	public function get_token( $data ) {
1639
		return $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1640
	}
1641
1642
	/**
1643
	 * Builds a URL to the Jetpack connection auth page.
1644
	 *
1645
	 * @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...
1646
	 * @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...
1647
	 * @return string Connect URL.
1648
	 */
1649
	public function get_authorization_url( $user = null, $redirect = null ) {
1650
		if ( empty( $user ) ) {
1651
			$user = wp_get_current_user();
1652
		}
1653
1654
		$roles       = new Roles();
1655
		$role        = $roles->translate_user_to_role( $user );
1656
		$signed_role = $this->get_tokens()->sign_role( $role );
1657
1658
		/**
1659
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1660
		 * data processing.
1661
		 *
1662
		 * @since 8.0.0
1663
		 *
1664
		 * @param string $redirect_url Defaults to the site admin URL.
1665
		 */
1666
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1667
1668
		/**
1669
		 * Filter the URL to redirect the user back to when the authorization process
1670
		 * is complete.
1671
		 *
1672
		 * @since 8.0.0
1673
		 *
1674
		 * @param string $redirect_url Defaults to the site URL.
1675
		 */
1676
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1677
1678
		$secrets = ( new Secrets() )->generate( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1679
1680
		/**
1681
		 * Filter the type of authorization.
1682
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1683
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1684
		 *
1685
		 * @since 4.3.3
1686
		 *
1687
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1688
		 */
1689
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1690
1691
		/**
1692
		 * Filters the user connection request data for additional property addition.
1693
		 *
1694
		 * @since 8.0.0
1695
		 *
1696
		 * @param array $request_data request data.
1697
		 */
1698
		$body = apply_filters(
1699
			'jetpack_connect_request_body',
1700
			array(
1701
				'response_type'         => 'code',
1702
				'client_id'             => \Jetpack_Options::get_option( 'id' ),
1703
				'redirect_uri'          => add_query_arg(
1704
					array(
1705
						'handler'  => 'jetpack-connection-webhooks',
1706
						'action'   => 'authorize',
1707
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1708
						'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1709
					),
1710
					esc_url( $processing_url )
1711
				),
1712
				'state'                 => $user->ID,
1713
				'scope'                 => $signed_role,
1714
				'user_email'            => $user->user_email,
1715
				'user_login'            => $user->user_login,
1716
				'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...
1717
				'jp_version'            => Constants::get_constant( 'JETPACK__VERSION' ),
1718
				'auth_type'             => $auth_type,
1719
				'secret'                => $secrets['secret_1'],
1720
				'blogname'              => get_option( 'blogname' ),
1721
				'site_url'              => Urls::site_url(),
1722
				'home_url'              => Urls::home_url(),
1723
				'site_icon'             => get_site_icon_url(),
1724
				'site_lang'             => get_locale(),
1725
				'site_created'          => $this->get_assumed_site_creation_date(),
1726
				'allow_site_connection' => ! $this->has_connected_owner(),
1727
			)
1728
		);
1729
1730
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1731
1732
		$api_url = $this->api_url( 'authorize' );
1733
1734
		return add_query_arg( $body, $api_url );
1735
	}
1736
1737
	/**
1738
	 * Authorizes the user by obtaining and storing the user token.
1739
	 *
1740
	 * @param array $data The request data.
1741
	 * @return string|\WP_Error Returns a string on success.
1742
	 *                          Returns a \WP_Error on failure.
1743
	 */
1744
	public function authorize( $data = array() ) {
1745
		/**
1746
		 * Action fired when user authorization starts.
1747
		 *
1748
		 * @since 8.0.0
1749
		 */
1750
		do_action( 'jetpack_authorize_starting' );
1751
1752
		$roles = new Roles();
1753
		$role  = $roles->translate_current_user_to_role();
1754
1755
		if ( ! $role ) {
1756
			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...
1757
		}
1758
1759
		$cap = $roles->translate_role_to_cap( $role );
1760
		if ( ! $cap ) {
1761
			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...
1762
		}
1763
1764
		if ( ! empty( $data['error'] ) ) {
1765
			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...
1766
		}
1767
1768
		if ( ! isset( $data['state'] ) ) {
1769
			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...
1770
		}
1771
1772
		if ( ! ctype_digit( $data['state'] ) ) {
1773
			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...
1774
		}
1775
1776
		$current_user_id = get_current_user_id();
1777
		if ( $current_user_id !== (int) $data['state'] ) {
1778
			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...
1779
		}
1780
1781
		if ( empty( $data['code'] ) ) {
1782
			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...
1783
		}
1784
1785
		$token = $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1786
1787 View Code Duplication
		if ( is_wp_error( $token ) ) {
1788
			$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...
1789
			if ( empty( $code ) ) {
1790
				$code = 'invalid_token';
1791
			}
1792
			return new \WP_Error( $code, $token->get_error_message(), 400 );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $code.

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

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

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

Loading history...
1793
		}
1794
1795
		if ( ! $token ) {
1796
			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...
1797
		}
1798
1799
		$is_connection_owner = ! $this->has_connected_owner();
1800
1801
		$this->get_tokens()->update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_connection_owner );
1802
1803
		/**
1804
		 * Fires after user has successfully received an auth token.
1805
		 *
1806
		 * @since 3.9.0
1807
		 */
1808
		do_action( 'jetpack_user_authorized' );
1809
1810
		if ( ! $is_connection_owner ) {
1811
			/**
1812
			 * Action fired when a secondary user has been authorized.
1813
			 *
1814
			 * @since 8.0.0
1815
			 */
1816
			do_action( 'jetpack_authorize_ending_linked' );
1817
			return 'linked';
1818
		}
1819
1820
		/**
1821
		 * Action fired when the master user has been authorized.
1822
		 *
1823
		 * @since 8.0.0
1824
		 *
1825
		 * @param array $data The request data.
1826
		 */
1827
		do_action( 'jetpack_authorize_ending_authorized', $data );
1828
1829
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
1830
1831
		( new Nonce_Handler() )->reschedule();
1832
1833
		return 'authorized';
1834
	}
1835
1836
	/**
1837
	 * Disconnects from the Jetpack servers.
1838
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1839
	 */
1840
	public function disconnect_site() {
1841
1842
	}
1843
1844
	/**
1845
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1846
	 *
1847
	 * @param string $text The string to hash.
1848
	 * @return string
1849
	 */
1850
	public function sha1_base64( $text ) {
1851
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1852
	}
1853
1854
	/**
1855
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1856
	 *
1857
	 * @param string $domain The domain to check.
1858
	 *
1859
	 * @return bool|WP_Error
1860
	 */
1861
	public function is_usable_domain( $domain ) {
1862
1863
		// If it's empty, just fail out.
1864
		if ( ! $domain ) {
1865
			return new \WP_Error(
1866
				'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...
1867
				/* translators: %1$s is a domain name. */
1868
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1869
			);
1870
		}
1871
1872
		/**
1873
		 * Skips the usuable domain check when connecting a site.
1874
		 *
1875
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1876
		 *
1877
		 * @since 4.1.0
1878
		 *
1879
		 * @param bool If the check should be skipped. Default false.
1880
		 */
1881
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1882
			return true;
1883
		}
1884
1885
		// None of the explicit localhosts.
1886
		$forbidden_domains = array(
1887
			'wordpress.com',
1888
			'localhost',
1889
			'localhost.localdomain',
1890
			'127.0.0.1',
1891
			'local.wordpress.test',         // VVV pattern.
1892
			'local.wordpress-trunk.test',   // VVV pattern.
1893
			'src.wordpress-develop.test',   // VVV pattern.
1894
			'build.wordpress-develop.test', // VVV pattern.
1895
		);
1896 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1897
			return new \WP_Error(
1898
				'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...
1899
				sprintf(
1900
					/* translators: %1$s is a domain name. */
1901
					__(
1902
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1903
						'jetpack'
1904
					),
1905
					$domain
1906
				)
1907
			);
1908
		}
1909
1910
		// No .test or .local domains.
1911 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1912
			return new \WP_Error(
1913
				'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...
1914
				sprintf(
1915
					/* translators: %1$s is a domain name. */
1916
					__(
1917
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1918
						'jetpack'
1919
					),
1920
					$domain
1921
				)
1922
			);
1923
		}
1924
1925
		// No WPCOM subdomains.
1926 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1927
			return new \WP_Error(
1928
				'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...
1929
				sprintf(
1930
					/* translators: %1$s is a domain name. */
1931
					__(
1932
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1933
						'jetpack'
1934
					),
1935
					$domain
1936
				)
1937
			);
1938
		}
1939
1940
		// If PHP was compiled without support for the Filter module (very edge case).
1941
		if ( ! function_exists( 'filter_var' ) ) {
1942
			// Just pass back true for now, and let wpcom sort it out.
1943
			return true;
1944
		}
1945
1946
		return true;
1947
	}
1948
1949
	/**
1950
	 * Gets the requested token.
1951
	 *
1952
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_access_token() instead.
1953
	 *
1954
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1955
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1956
	 * @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.
1957
	 *
1958
	 * @return object|false
1959
	 *
1960
	 * @see $this->get_tokens()->get_access_token()
1961
	 */
1962
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1963
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_access_token' );
1964
		return $this->get_tokens()->get_access_token( $user_id, $token_key, $suppress_errors );
1965
	}
1966
1967
	/**
1968
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
1969
	 * since it is passed by reference to various methods.
1970
	 * Capture it here so we can verify the signature later.
1971
	 *
1972
	 * @param array $methods an array of available XMLRPC methods.
1973
	 * @return array the same array, since this method doesn't add or remove anything.
1974
	 */
1975
	public function xmlrpc_methods( $methods ) {
1976
		$this->raw_post_data = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
1977
		return $methods;
1978
	}
1979
1980
	/**
1981
	 * Resets the raw post data parameter for testing purposes.
1982
	 */
1983
	public function reset_raw_post_data() {
1984
		$this->raw_post_data = null;
1985
	}
1986
1987
	/**
1988
	 * Registering an additional method.
1989
	 *
1990
	 * @param array $methods an array of available XMLRPC methods.
1991
	 * @return array the amended array in case the method is added.
1992
	 */
1993
	public function public_xmlrpc_methods( $methods ) {
1994
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
1995
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
1996
		}
1997
		return $methods;
1998
	}
1999
2000
	/**
2001
	 * Handles a getOptions XMLRPC method call.
2002
	 *
2003
	 * @param array $args method call arguments.
2004
	 * @return an amended XMLRPC server options array.
2005
	 */
2006
	public function jetpack_get_options( $args ) {
2007
		global $wp_xmlrpc_server;
2008
2009
		$wp_xmlrpc_server->escape( $args );
2010
2011
		$username = $args[1];
2012
		$password = $args[2];
2013
2014
		$user = $wp_xmlrpc_server->login( $username, $password );
2015
		if ( ! $user ) {
2016
			return $wp_xmlrpc_server->error;
2017
		}
2018
2019
		$options   = array();
2020
		$user_data = $this->get_connected_user_data();
2021
		if ( is_array( $user_data ) ) {
2022
			$options['jetpack_user_id']         = array(
2023
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2024
				'readonly' => true,
2025
				'value'    => $user_data['ID'],
2026
			);
2027
			$options['jetpack_user_login']      = array(
2028
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2029
				'readonly' => true,
2030
				'value'    => $user_data['login'],
2031
			);
2032
			$options['jetpack_user_email']      = array(
2033
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2034
				'readonly' => true,
2035
				'value'    => $user_data['email'],
2036
			);
2037
			$options['jetpack_user_site_count'] = array(
2038
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2039
				'readonly' => true,
2040
				'value'    => $user_data['site_count'],
2041
			);
2042
		}
2043
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2044
		$args                           = stripslashes_deep( $args );
2045
		return $wp_xmlrpc_server->wp_getOptions( $args );
2046
	}
2047
2048
	/**
2049
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2050
	 *
2051
	 * @param array $options standard Core options.
2052
	 * @return array amended options.
2053
	 */
2054
	public function xmlrpc_options( $options ) {
2055
		$jetpack_client_id = false;
2056
		if ( $this->is_connected() ) {
2057
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2058
		}
2059
		$options['jetpack_version'] = array(
2060
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2061
			'readonly' => true,
2062
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2063
		);
2064
2065
		$options['jetpack_client_id'] = array(
2066
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2067
			'readonly' => true,
2068
			'value'    => $jetpack_client_id,
2069
		);
2070
		return $options;
2071
	}
2072
2073
	/**
2074
	 * Resets the saved authentication state in between testing requests.
2075
	 */
2076
	public function reset_saved_auth_state() {
2077
		$this->xmlrpc_verification = null;
2078
	}
2079
2080
	/**
2081
	 * Sign a user role with the master access token.
2082
	 * If not specified, will default to the current user.
2083
	 *
2084
	 * @access public
2085
	 *
2086
	 * @param string $role    User role.
2087
	 * @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...
2088
	 * @return string Signed user role.
2089
	 */
2090
	public function sign_role( $role, $user_id = null ) {
2091
		return $this->get_tokens()->sign_role( $role, $user_id );
2092
	}
2093
2094
	/**
2095
	 * Set the plugin instance.
2096
	 *
2097
	 * @param Plugin $plugin_instance The plugin instance.
2098
	 *
2099
	 * @return $this
2100
	 */
2101
	public function set_plugin_instance( Plugin $plugin_instance ) {
2102
		$this->plugin = $plugin_instance;
2103
2104
		return $this;
2105
	}
2106
2107
	/**
2108
	 * Retrieve the plugin management object.
2109
	 *
2110
	 * @return Plugin|null
2111
	 */
2112
	public function get_plugin() {
2113
		return $this->plugin;
2114
	}
2115
2116
	/**
2117
	 * Get all connected plugins information, excluding those disconnected by user.
2118
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2119
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2120
	 * so please make sure not to run the method too early in the code.
2121
	 *
2122
	 * @return array|WP_Error
2123
	 */
2124
	public function get_connected_plugins() {
2125
		$maybe_plugins = Plugin_Storage::get_all( true );
2126
2127
		if ( $maybe_plugins instanceof WP_Error ) {
2128
			return $maybe_plugins;
2129
		}
2130
2131
		return $maybe_plugins;
2132
	}
2133
2134
	/**
2135
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2136
	 * Note: this method does not remove any access tokens.
2137
	 *
2138
	 * @return bool
2139
	 */
2140
	public function disable_plugin() {
2141
		if ( ! $this->plugin ) {
2142
			return false;
2143
		}
2144
2145
		return $this->plugin->disable();
2146
	}
2147
2148
	/**
2149
	 * Force plugin reconnect after user-initiated disconnect.
2150
	 * After its called, the plugin will be allowed to use the connection again.
2151
	 * Note: this method does not initialize access tokens.
2152
	 *
2153
	 * @return bool
2154
	 */
2155
	public function enable_plugin() {
2156
		if ( ! $this->plugin ) {
2157
			return false;
2158
		}
2159
2160
		return $this->plugin->enable();
2161
	}
2162
2163
	/**
2164
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2165
	 * If no plugin slug was passed into the constructor, always returns true.
2166
	 *
2167
	 * @return bool
2168
	 */
2169
	public function is_plugin_enabled() {
2170
		if ( ! $this->plugin ) {
2171
			return true;
2172
		}
2173
2174
		return $this->plugin->is_enabled();
2175
	}
2176
2177
	/**
2178
	 * Perform the API request to refresh the blog token.
2179
	 * Note that we are making this request on behalf of the Jetpack master user,
2180
	 * given they were (most probably) the ones that registered the site at the first place.
2181
	 *
2182
	 * @return WP_Error|bool The result of updating the blog_token option.
2183
	 */
2184
	public function refresh_blog_token() {
2185
		( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
2186
2187
		$blog_id = \Jetpack_Options::get_option( 'id' );
2188
		if ( ! $blog_id ) {
2189
			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...
2190
		}
2191
2192
		$url     = sprintf(
2193
			'%s/%s/v%s/%s',
2194
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
2195
			'wpcom',
2196
			'2',
2197
			'sites/' . $blog_id . '/jetpack-refresh-blog-token'
2198
		);
2199
		$method  = 'POST';
2200
		$user_id = get_current_user_id();
2201
2202
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2203
2204
		if ( is_wp_error( $response ) ) {
2205
			return new WP_Error( 'refresh_blog_token_http_request_failed', $response->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with '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...
2206
		}
2207
2208
		$code   = wp_remote_retrieve_response_code( $response );
2209
		$entity = wp_remote_retrieve_body( $response );
2210
2211
		if ( $entity ) {
2212
			$json = json_decode( $entity );
2213
		} else {
2214
			$json = false;
2215
		}
2216
2217 View Code Duplication
		if ( 200 !== $code ) {
2218
			if ( empty( $json->code ) ) {
2219
				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...
2220
			}
2221
2222
			/* translators: Error description string. */
2223
			$error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->message ) : '';
2224
2225
			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...
2226
		}
2227
2228
		if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
2229
			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...
2230
		}
2231
2232
		return $this->get_tokens()->update_blog_token( (string) $json->jetpack_secret );
2233
	}
2234
2235
	/**
2236
	 * Disconnect the user from WP.com, and initiate the reconnect process.
2237
	 *
2238
	 * @return bool
2239
	 */
2240
	public function refresh_user_token() {
2241
		( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2242
		$this->disconnect_user( null, true );
2243
		return true;
2244
	}
2245
2246
	/**
2247
	 * Fetches a signed token.
2248
	 *
2249
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_signed_token() instead.
2250
	 *
2251
	 * @param object $token the token.
2252
	 * @return WP_Error|string a signed token
2253
	 */
2254
	public function get_signed_token( $token ) {
2255
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_signed_token' );
2256
		return $this->get_tokens()->get_signed_token( $token );
2257
	}
2258
2259
	/**
2260
	 * If the site-level connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2261
	 *
2262
	 * @param array $stats The Heartbeat stats array.
2263
	 * @return array $stats
2264
	 */
2265
	public function add_stats_to_heartbeat( $stats ) {
2266
2267
		if ( ! $this->is_connected() ) {
2268
			return $stats;
2269
		}
2270
2271
		$active_plugins_using_connection = Plugin_Storage::get_all();
2272
		foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
2273
			if ( 'jetpack' !== $plugin_slug ) {
2274
				$stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2275
				$stats[ $stats_group ][] = $plugin_slug;
2276
			}
2277
		}
2278
		return $stats;
2279
	}
2280
}
2281