Completed
Push — try/refactor-secrets-and-token... ( ad6cd9...9cdaa1 )
by
unknown
837:53 queued 825:50
created

Manager::setup_xmlrpc_handlers()   C

Complexity

Conditions 11
Paths 28

Size

Total Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
nc 28
nop 4
dl 0
loc 72
rs 6.4642
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * The Jetpack Connection manager class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Heartbeat;
12
use Automattic\Jetpack\Roles;
13
use Automattic\Jetpack\Status;
14
use Automattic\Jetpack\Tracking;
15
use WP_Error;
16
use WP_User;
17
18
/**
19
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
20
 * and Jetpack.
21
 */
22
class Manager {
23
	/**
24
	 * A copy of the raw POST data for signature verification purposes.
25
	 *
26
	 * @var String
27
	 */
28
	protected $raw_post_data;
29
30
	/**
31
	 * Verification data needs to be stored to properly verify everything.
32
	 *
33
	 * @var Object
34
	 */
35
	private $xmlrpc_verification = null;
36
37
	/**
38
	 * Plugin management object.
39
	 *
40
	 * @var Plugin
41
	 */
42
	private $plugin = null;
43
44
	/**
45
	 * Initialize the object.
46
	 * Make sure to call the "Configure" first.
47
	 *
48
	 * @param string $plugin_slug Slug of the plugin using the connection (optional, but encouraged).
0 ignored issues
show
Documentation introduced by
Should the type for parameter $plugin_slug not be string|null?

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

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

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

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

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

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

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

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

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

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

An additional type check may prevent trouble.

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

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

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

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

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

Loading history...
1341
			return false;
1342
		}
1343
1344
		$xml = new \Jetpack_IXR_Client();
1345
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1346
1347
		return true;
1348
	}
1349
1350
	/**
1351
	 * Disconnect the plugin and remove the tokens.
1352
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1353
	 * This is a proxy method to simplify the Connection package API.
1354
	 *
1355
	 * @see Manager::disable_plugin()
1356
	 * @see Manager::disconnect_site_wpcom()
1357
	 * @see Manager::delete_all_connection_tokens()
1358
	 *
1359
	 * @return bool
1360
	 */
1361
	public function remove_connection() {
1362
		$this->disable_plugin();
1363
		$this->disconnect_site_wpcom();
1364
		$this->delete_all_connection_tokens();
1365
1366
		return true;
1367
	}
1368
1369
	/**
1370
	 * Completely clearing up the connection, and initiating reconnect.
1371
	 *
1372
	 * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
1373
	 */
1374
	public function reconnect() {
1375
		( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
1376
1377
		$this->disconnect_site_wpcom( true );
1378
		$this->delete_all_connection_tokens( true );
1379
1380
		return $this->register();
1381
	}
1382
1383
	/**
1384
	 * Validate the tokens, and refresh the invalid ones.
1385
	 *
1386
	 * @return string|true|WP_Error True if connection restored or string indicating what's to be done next. A `WP_Error` object otherwise.
1387
	 */
1388
	public function restore() {
1389
1390
		$validate_tokens_response = $this->get_tokens()->validate();
1391
1392
		$blog_token_healthy = $validate_tokens_response['blog_token']['is_healthy'];
1393
		$user_token_healthy = $validate_tokens_response['user_token']['is_healthy'];
1394
1395
		// Tokens are both valid, or both invalid. We can't fix the problem we don't see, so the full reconnection is needed.
1396
		if ( $blog_token_healthy === $user_token_healthy ) {
1397
			$result = $this->reconnect();
1398
			return ( true === $result ) ? 'authorize' : $result;
1399
		}
1400
1401
		if ( ! $blog_token_healthy ) {
1402
			return $this->refresh_blog_token();
1403
		}
1404
1405
		if ( ! $user_token_healthy ) {
1406
			return ( true === $this->refresh_user_token() ) ? 'authorize' : false;
1407
		}
1408
1409
		return false;
1410
	}
1411
1412
	/**
1413
	 * Responds to a WordPress.com call to register the current site.
1414
	 * Should be changed to protected.
1415
	 *
1416
	 * @param array $registration_data Array of [ secret_1, user_id ].
1417
	 */
1418
	public function handle_registration( array $registration_data ) {
1419
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1420
		if ( empty( $registration_user_id ) ) {
1421
			return new \WP_Error( 'registration_state_invalid', __( 'Invalid Registration State', 'jetpack' ), 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'registration_state_invalid'.

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

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

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

Loading history...
1422
		}
1423
1424
		return ( new Secrets() )->verify( 'register', $registration_secret_1, (int) $registration_user_id );
1425
	}
1426
1427
	/**
1428
	 * Perform the API request to validate the blog and user tokens.
1429
	 *
1430
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->validate_tokens() instead.
1431
	 *
1432
	 * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
1433
	 *
1434
	 * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
1435
	 */
1436
	public function validate_tokens( $user_id = null ) {
1437
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->validate' );
1438
		return $this->get_tokens()->validate( $user_id );
1439
	}
1440
1441
	/**
1442
	 * Verify a Previously Generated Secret.
1443
	 *
1444
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->verify() instead.
1445
	 *
1446
	 * @param string $action   The type of secret to verify.
1447
	 * @param string $secret_1 The secret string to compare to what is stored.
1448
	 * @param int    $user_id  The user ID of the owner of the secret.
1449
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1450
	 */
1451
	public function verify_secrets( $action, $secret_1, $user_id ) {
1452
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->verify' );
1453
		return ( new Secrets() )->verify( $action, $secret_1, $user_id );
1454
	}
1455
1456
	/**
1457
	 * Responds to a WordPress.com call to authorize the current user.
1458
	 * Should be changed to protected.
1459
	 */
1460
	public function handle_authorization() {
1461
1462
	}
1463
1464
	/**
1465
	 * Obtains the auth token.
1466
	 *
1467
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get() instead.
1468
	 *
1469
	 * @param array $data The request data.
1470
	 * @return object|\WP_Error Returns the auth token on success.
1471
	 *                          Returns a \WP_Error on failure.
1472
	 */
1473
	public function get_token( $data ) {
1474
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get' );
1475
		return $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1476
	}
1477
1478
	/**
1479
	 * Builds a URL to the Jetpack connection auth page.
1480
	 *
1481
	 * @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...
1482
	 * @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...
1483
	 * @return string Connect URL.
1484
	 */
1485
	public function get_authorization_url( $user = null, $redirect = null ) {
1486
1487
		if ( empty( $user ) ) {
1488
			$user = wp_get_current_user();
1489
		}
1490
1491
		$roles       = new Roles();
1492
		$role        = $roles->translate_user_to_role( $user );
1493
		$signed_role = $this->get_tokens()->sign_role( $role );
1494
1495
		/**
1496
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1497
		 * data processing.
1498
		 *
1499
		 * @since 8.0.0
1500
		 *
1501
		 * @param string $redirect_url Defaults to the site admin URL.
1502
		 */
1503
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1504
1505
		/**
1506
		 * Filter the URL to redirect the user back to when the authorization process
1507
		 * is complete.
1508
		 *
1509
		 * @since 8.0.0
1510
		 *
1511
		 * @param string $redirect_url Defaults to the site URL.
1512
		 */
1513
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1514
1515
		$secrets = ( new Secrets() )->generate( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1516
1517
		/**
1518
		 * Filter the type of authorization.
1519
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1520
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1521
		 *
1522
		 * @since 4.3.3
1523
		 *
1524
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1525
		 */
1526
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1527
1528
		/**
1529
		 * Filters the user connection request data for additional property addition.
1530
		 *
1531
		 * @since 8.0.0
1532
		 *
1533
		 * @param array $request_data request data.
1534
		 */
1535
		$body = apply_filters(
1536
			'jetpack_connect_request_body',
1537
			array(
1538
				'response_type' => 'code',
1539
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1540
				'redirect_uri'  => add_query_arg(
1541
					array(
1542
						'handler'  => 'jetpack-connection-webhooks',
1543
						'action'   => 'authorize',
1544
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1545
						'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1546
					),
1547
					esc_url( $processing_url )
1548
				),
1549
				'state'         => $user->ID,
1550
				'scope'         => $signed_role,
1551
				'user_email'    => $user->user_email,
1552
				'user_login'    => $user->user_login,
1553
				'is_active'     => $this->is_active(),
1554
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1555
				'auth_type'     => $auth_type,
1556
				'secret'        => $secrets['secret_1'],
1557
				'blogname'      => get_option( 'blogname' ),
1558
				'site_url'      => site_url(),
1559
				'home_url'      => home_url(),
1560
				'site_icon'     => get_site_icon_url(),
1561
				'site_lang'     => get_locale(),
1562
				'site_created'  => $this->get_assumed_site_creation_date(),
1563
			)
1564
		);
1565
1566
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1567
1568
		$api_url = $this->api_url( 'authorize' );
1569
1570
		return add_query_arg( $body, $api_url );
1571
	}
1572
1573
	/**
1574
	 * Authorizes the user by obtaining and storing the user token.
1575
	 *
1576
	 * @param array $data The request data.
1577
	 * @return string|\WP_Error Returns a string on success.
1578
	 *                          Returns a \WP_Error on failure.
1579
	 */
1580
	public function authorize( $data = array() ) {
1581
		/**
1582
		 * Action fired when user authorization starts.
1583
		 *
1584
		 * @since 8.0.0
1585
		 */
1586
		do_action( 'jetpack_authorize_starting' );
1587
1588
		$roles = new Roles();
1589
		$role  = $roles->translate_current_user_to_role();
1590
1591
		if ( ! $role ) {
1592
			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...
1593
		}
1594
1595
		$cap = $roles->translate_role_to_cap( $role );
1596
		if ( ! $cap ) {
1597
			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...
1598
		}
1599
1600
		if ( ! empty( $data['error'] ) ) {
1601
			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...
1602
		}
1603
1604
		if ( ! isset( $data['state'] ) ) {
1605
			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...
1606
		}
1607
1608
		if ( ! ctype_digit( $data['state'] ) ) {
1609
			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...
1610
		}
1611
1612
		$current_user_id = get_current_user_id();
1613
		if ( $current_user_id !== (int) $data['state'] ) {
1614
			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...
1615
		}
1616
1617
		if ( empty( $data['code'] ) ) {
1618
			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...
1619
		}
1620
1621
		$token = $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1622
1623 View Code Duplication
		if ( is_wp_error( $token ) ) {
1624
			$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...
1625
			if ( empty( $code ) ) {
1626
				$code = 'invalid_token';
1627
			}
1628
			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...
1629
		}
1630
1631
		if ( ! $token ) {
1632
			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...
1633
		}
1634
1635
		$is_connection_owner = ! $this->has_connected_owner();
1636
1637
		$this->get_tokens()->update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_connection_owner );
1638
1639
		/**
1640
		 * Fires after user has successfully received an auth token.
1641
		 *
1642
		 * @since 3.9.0
1643
		 */
1644
		do_action( 'jetpack_user_authorized' );
1645
1646
		if ( ! $is_connection_owner ) {
1647
			/**
1648
			 * Action fired when a secondary user has been authorized.
1649
			 *
1650
			 * @since 8.0.0
1651
			 */
1652
			do_action( 'jetpack_authorize_ending_linked' );
1653
			return 'linked';
1654
		}
1655
1656
		/**
1657
		 * Action fired when the master user has been authorized.
1658
		 *
1659
		 * @since 8.0.0
1660
		 *
1661
		 * @param array $data The request data.
1662
		 */
1663
		do_action( 'jetpack_authorize_ending_authorized', $data );
1664
1665
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
1666
1667
		// Start nonce cleaner.
1668
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
1669
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
1670
1671
		return 'authorized';
1672
	}
1673
1674
	/**
1675
	 * Disconnects from the Jetpack servers.
1676
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1677
	 */
1678
	public function disconnect_site() {
1679
1680
	}
1681
1682
	/**
1683
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1684
	 *
1685
	 * @param string $text The string to hash.
1686
	 * @return string
1687
	 */
1688
	public function sha1_base64( $text ) {
1689
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1690
	}
1691
1692
	/**
1693
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1694
	 *
1695
	 * @param string $domain The domain to check.
1696
	 *
1697
	 * @return bool|WP_Error
1698
	 */
1699
	public function is_usable_domain( $domain ) {
1700
1701
		// If it's empty, just fail out.
1702
		if ( ! $domain ) {
1703
			return new \WP_Error(
1704
				'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...
1705
				/* translators: %1$s is a domain name. */
1706
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1707
			);
1708
		}
1709
1710
		/**
1711
		 * Skips the usuable domain check when connecting a site.
1712
		 *
1713
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1714
		 *
1715
		 * @since 4.1.0
1716
		 *
1717
		 * @param bool If the check should be skipped. Default false.
1718
		 */
1719
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1720
			return true;
1721
		}
1722
1723
		// None of the explicit localhosts.
1724
		$forbidden_domains = array(
1725
			'wordpress.com',
1726
			'localhost',
1727
			'localhost.localdomain',
1728
			'127.0.0.1',
1729
			'local.wordpress.test',         // VVV pattern.
1730
			'local.wordpress-trunk.test',   // VVV pattern.
1731
			'src.wordpress-develop.test',   // VVV pattern.
1732
			'build.wordpress-develop.test', // VVV pattern.
1733
		);
1734 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1735
			return new \WP_Error(
1736
				'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...
1737
				sprintf(
1738
					/* translators: %1$s is a domain name. */
1739
					__(
1740
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1741
						'jetpack'
1742
					),
1743
					$domain
1744
				)
1745
			);
1746
		}
1747
1748
		// No .test or .local domains.
1749 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1750
			return new \WP_Error(
1751
				'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...
1752
				sprintf(
1753
					/* translators: %1$s is a domain name. */
1754
					__(
1755
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1756
						'jetpack'
1757
					),
1758
					$domain
1759
				)
1760
			);
1761
		}
1762
1763
		// No WPCOM subdomains.
1764 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1765
			return new \WP_Error(
1766
				'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...
1767
				sprintf(
1768
					/* translators: %1$s is a domain name. */
1769
					__(
1770
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1771
						'jetpack'
1772
					),
1773
					$domain
1774
				)
1775
			);
1776
		}
1777
1778
		// If PHP was compiled without support for the Filter module (very edge case).
1779
		if ( ! function_exists( 'filter_var' ) ) {
1780
			// Just pass back true for now, and let wpcom sort it out.
1781
			return true;
1782
		}
1783
1784
		return true;
1785
	}
1786
1787
	/**
1788
	 * Gets the requested token.
1789
	 *
1790
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_access_token() instead.
1791
	 *
1792
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1793
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1794
	 * @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.
1795
	 *
1796
	 * @return object|false
1797
	 *
1798
	 * @see $this->get_tokens()->get_access_token()
1799
	 */
1800
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1801
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_access_token' );
1802
		return $this->get_tokens()->get_access_token( $user_id, $token_key, $suppress_errors );
1803
	}
1804
1805
	/**
1806
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
1807
	 * since it is passed by reference to various methods.
1808
	 * Capture it here so we can verify the signature later.
1809
	 *
1810
	 * @param array $methods an array of available XMLRPC methods.
1811
	 * @return array the same array, since this method doesn't add or remove anything.
1812
	 */
1813
	public function xmlrpc_methods( $methods ) {
1814
		$this->raw_post_data = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
1815
		return $methods;
1816
	}
1817
1818
	/**
1819
	 * Resets the raw post data parameter for testing purposes.
1820
	 */
1821
	public function reset_raw_post_data() {
1822
		$this->raw_post_data = null;
1823
	}
1824
1825
	/**
1826
	 * Registering an additional method.
1827
	 *
1828
	 * @param array $methods an array of available XMLRPC methods.
1829
	 * @return array the amended array in case the method is added.
1830
	 */
1831
	public function public_xmlrpc_methods( $methods ) {
1832
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
1833
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
1834
		}
1835
		return $methods;
1836
	}
1837
1838
	/**
1839
	 * Handles a getOptions XMLRPC method call.
1840
	 *
1841
	 * @param array $args method call arguments.
1842
	 * @return an amended XMLRPC server options array.
1843
	 */
1844
	public function jetpack_get_options( $args ) {
1845
		global $wp_xmlrpc_server;
1846
1847
		$wp_xmlrpc_server->escape( $args );
1848
1849
		$username = $args[1];
1850
		$password = $args[2];
1851
1852
		$user = $wp_xmlrpc_server->login( $username, $password );
1853
		if ( ! $user ) {
1854
			return $wp_xmlrpc_server->error;
1855
		}
1856
1857
		$options   = array();
1858
		$user_data = $this->get_connected_user_data();
1859
		if ( is_array( $user_data ) ) {
1860
			$options['jetpack_user_id']         = array(
1861
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
1862
				'readonly' => true,
1863
				'value'    => $user_data['ID'],
1864
			);
1865
			$options['jetpack_user_login']      = array(
1866
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
1867
				'readonly' => true,
1868
				'value'    => $user_data['login'],
1869
			);
1870
			$options['jetpack_user_email']      = array(
1871
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
1872
				'readonly' => true,
1873
				'value'    => $user_data['email'],
1874
			);
1875
			$options['jetpack_user_site_count'] = array(
1876
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
1877
				'readonly' => true,
1878
				'value'    => $user_data['site_count'],
1879
			);
1880
		}
1881
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
1882
		$args                           = stripslashes_deep( $args );
1883
		return $wp_xmlrpc_server->wp_getOptions( $args );
1884
	}
1885
1886
	/**
1887
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
1888
	 *
1889
	 * @param array $options standard Core options.
1890
	 * @return array amended options.
1891
	 */
1892
	public function xmlrpc_options( $options ) {
1893
		$jetpack_client_id = false;
1894
		if ( $this->is_active() ) {
1895
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
1896
		}
1897
		$options['jetpack_version'] = array(
1898
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
1899
			'readonly' => true,
1900
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
1901
		);
1902
1903
		$options['jetpack_client_id'] = array(
1904
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
1905
			'readonly' => true,
1906
			'value'    => $jetpack_client_id,
1907
		);
1908
		return $options;
1909
	}
1910
1911
	/**
1912
	 * Resets the saved authentication state in between testing requests.
1913
	 */
1914
	public function reset_saved_auth_state() {
1915
		$this->xmlrpc_verification = null;
1916
	}
1917
1918
	/**
1919
	 * Sign a user role with the master access token.
1920
	 * If not specified, will default to the current user.
1921
	 *
1922
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->sign_role() instead.
1923
	 *
1924
	 * @access public
1925
	 *
1926
	 * @param string $role    User role.
1927
	 * @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...
1928
	 * @return string Signed user role.
1929
	 */
1930
	public function sign_role( $role, $user_id = null ) {
1931
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->sign_role' );
1932
		return $this->get_tokens()->sign_role( $role, $user_id );
1933
	}
1934
1935
	/**
1936
	 * Set the plugin instance.
1937
	 *
1938
	 * @param Plugin $plugin_instance The plugin instance.
1939
	 *
1940
	 * @return $this
1941
	 */
1942
	public function set_plugin_instance( Plugin $plugin_instance ) {
1943
		$this->plugin = $plugin_instance;
1944
1945
		return $this;
1946
	}
1947
1948
	/**
1949
	 * Retrieve the plugin management object.
1950
	 *
1951
	 * @return Plugin
1952
	 */
1953
	public function get_plugin() {
1954
		return $this->plugin;
1955
	}
1956
1957
	/**
1958
	 * Get all connected plugins information, excluding those disconnected by user.
1959
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
1960
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
1961
	 * so please make sure not to run the method too early in the code.
1962
	 *
1963
	 * @return array|WP_Error
1964
	 */
1965
	public function get_connected_plugins() {
1966
		$maybe_plugins = Plugin_Storage::get_all( true );
1967
1968
		if ( $maybe_plugins instanceof WP_Error ) {
1969
			return $maybe_plugins;
1970
		}
1971
1972
		return $maybe_plugins;
1973
	}
1974
1975
	/**
1976
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
1977
	 * Note: this method does not remove any access tokens.
1978
	 *
1979
	 * @return bool
1980
	 */
1981
	public function disable_plugin() {
1982
		if ( ! $this->plugin ) {
1983
			return false;
1984
		}
1985
1986
		return $this->plugin->disable();
1987
	}
1988
1989
	/**
1990
	 * Force plugin reconnect after user-initiated disconnect.
1991
	 * After its called, the plugin will be allowed to use the connection again.
1992
	 * Note: this method does not initialize access tokens.
1993
	 *
1994
	 * @return bool
1995
	 */
1996
	public function enable_plugin() {
1997
		if ( ! $this->plugin ) {
1998
			return false;
1999
		}
2000
2001
		return $this->plugin->enable();
2002
	}
2003
2004
	/**
2005
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2006
	 * If no plugin slug was passed into the constructor, always returns true.
2007
	 *
2008
	 * @return bool
2009
	 */
2010
	public function is_plugin_enabled() {
2011
		if ( ! $this->plugin ) {
2012
			return true;
2013
		}
2014
2015
		return $this->plugin->is_enabled();
2016
	}
2017
2018
	/**
2019
	 * Perform the API request to refresh the blog token.
2020
	 * Note that we are making this request on behalf of the Jetpack master user,
2021
	 * given they were (most probably) the ones that registered the site at the first place.
2022
	 *
2023
	 * @return WP_Error|bool The result of updating the blog_token option.
2024
	 */
2025
	/**
2026
	 * Perform the API request to refresh the blog token.
2027
	 * Note that we are making this request on behalf of the Jetpack master user,
2028
	 * given they were (most probably) the ones that registered the site at the first place.
2029
	 *
2030
	 * @return WP_Error|bool The result of updating the blog_token option.
2031
	 */
2032
	public function refresh_blog_token() {
2033
		( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
2034
2035
		$blog_id = \Jetpack_Options::get_option( 'id' );
2036
		if ( ! $blog_id ) {
2037
			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...
2038
		}
2039
2040
		$url     = sprintf(
2041
			'%s/%s/v%s/%s',
2042
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
2043
			'wpcom',
2044
			'2',
2045
			'sites/' . $blog_id . '/jetpack-refresh-blog-token'
2046
		);
2047
		$method  = 'POST';
2048
		$user_id = get_current_user_id();
2049
2050
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2051
2052
		if ( is_wp_error( $response ) ) {
2053
			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...
2054
		}
2055
2056
		$code   = wp_remote_retrieve_response_code( $response );
2057
		$entity = wp_remote_retrieve_body( $response );
2058
2059
		if ( $entity ) {
2060
			$json = json_decode( $entity );
2061
		} else {
2062
			$json = false;
2063
		}
2064
2065 View Code Duplication
		if ( 200 !== $code ) {
2066
			if ( empty( $json->code ) ) {
2067
				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...
2068
			}
2069
2070
			/* translators: Error description string. */
2071
			$error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->message ) : '';
2072
2073
			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...
2074
		}
2075
2076
		if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
2077
			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...
2078
		}
2079
2080
		return $this->get_tokens()->update_blog_token( 'blog_token', (string) $json->jetpack_secret );
0 ignored issues
show
Unused Code introduced by
The call to Tokens::update_blog_token() has too many arguments starting with (string) $json->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...
2081
	}
2082
2083
	/**
2084
	 * Disconnect the user from WP.com, and initiate the reconnect process.
2085
	 *
2086
	 * @return bool
2087
	 */
2088
	public function refresh_user_token() {
2089
		( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2090
		$this->disconnect_user( null, true );
2091
		return true;
2092
	}
2093
2094
	/**
2095
	 * Fetches a signed token.
2096
	 *
2097
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_signed_token() instead.
2098
	 *
2099
	 * @param object $token the token.
2100
	 * @return WP_Error|string a signed token
2101
	 */
2102
	public function get_signed_token( $token ) {
2103
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_signed_token' );
2104
		return $this->get_tokens()->get_signed_token( $token );
2105
	}
2106
2107
	/**
2108
	 * If connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2109
	 *
2110
	 * @param array $stats The Heartbeat stats array.
2111
	 * @return array $stats
2112
	 */
2113
	public function add_stats_to_heartbeat( $stats ) {
2114
2115
		if ( ! $this->is_active() ) {
2116
			return $stats;
2117
		}
2118
2119
		$active_plugins_using_connection = Plugin_Storage::get_all();
2120
		foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
2121
			if ( 'jetpack' !== $plugin_slug ) {
2122
				$stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2123
				$stats[ $stats_group ][] = $plugin_slug;
2124
			}
2125
		}
2126
		return $stats;
2127
	}
2128
}
2129