Completed
Push — update/wp-requirements-wp57 ( 343d2f...374f74 )
by Jeremy
64:01 queued 53:47
created

Manager::is_active()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * The Jetpack Connection manager class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Heartbeat;
12
use Automattic\Jetpack\Roles;
13
use Automattic\Jetpack\Status;
14
use Automattic\Jetpack\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
		$user_id = empty( $user_id ) ? get_current_user_id() : (int) $user_id;
744
745
		$result = $this->get_tokens()->disconnect_user( $user_id, $can_overwrite_primary_user );
746
747
		if ( $result ) {
748
			$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
749
			$xml->query( 'jetpack.unlink_user', $user_id );
750
751
			// Delete cached connected user data.
752
			$transient_key = "jetpack_connected_user_data_$user_id";
753
			delete_transient( $transient_key );
754
755
			/**
756
			 * Fires after the current user has been unlinked from WordPress.com.
757
			 *
758
			 * @since 4.1.0
759
			 *
760
			 * @param int $user_id The current user's ID.
761
			 */
762
			do_action( 'jetpack_unlinked_user', $user_id );
763
		}
764
		return $result;
765
	}
766
767
	/**
768
	 * Returns the requested Jetpack API URL.
769
	 *
770
	 * @param String $relative_url the relative API path.
771
	 * @return String API URL.
772
	 */
773
	public function api_url( $relative_url ) {
774
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
775
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
776
777
		/**
778
		 * Filters whether the connection manager should use the iframe authorization
779
		 * flow instead of the regular redirect-based flow.
780
		 *
781
		 * @since 8.3.0
782
		 *
783
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
784
		 */
785
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
786
787
		// Do not modify anything that is not related to authorize requests.
788
		if ( 'authorize' === $relative_url && $iframe_flow ) {
789
			$relative_url = 'authorize_iframe';
790
		}
791
792
		/**
793
		 * Filters the API URL that Jetpack uses for server communication.
794
		 *
795
		 * @since 8.0.0
796
		 *
797
		 * @param String $url the generated URL.
798
		 * @param String $relative_url the relative URL that was passed as an argument.
799
		 * @param String $api_base the API base string that is being used.
800
		 * @param String $api_version the API version string that is being used.
801
		 */
802
		return apply_filters(
803
			'jetpack_api_url',
804
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
805
			$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...
806
			$api_base,
807
			$api_version
808
		);
809
	}
810
811
	/**
812
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
813
	 *
814
	 * @return String XMLRPC API URL.
815
	 */
816
	public function xmlrpc_api_url() {
817
		$base = preg_replace(
818
			'#(https?://[^?/]+)(/?.*)?$#',
819
			'\\1',
820
			Constants::get_constant( 'JETPACK__API_BASE' )
821
		);
822
		return untrailingslashit( $base ) . '/xmlrpc.php';
823
	}
824
825
	/**
826
	 * Attempts Jetpack registration which sets up the site for connection. Should
827
	 * remain public because the call to action comes from the current site, not from
828
	 * WordPress.com.
829
	 *
830
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
831
	 * @return true|WP_Error The error object.
832
	 */
833
	public function register( $api_endpoint = 'register' ) {
834
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
835
		$secrets = ( new Secrets() )->generate( 'register', get_current_user_id(), 600 );
836
837
		if ( false === $secrets ) {
838
			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...
839
		}
840
841
		if (
842
			empty( $secrets['secret_1'] ) ||
843
			empty( $secrets['secret_2'] ) ||
844
			empty( $secrets['exp'] )
845
		) {
846
			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...
847
		}
848
849
		// Better to try (and fail) to set a higher timeout than this system
850
		// supports than to have register fail for more users than it should.
851
		$timeout = $this->set_min_time_limit( 60 ) / 2;
852
853
		$gmt_offset = get_option( 'gmt_offset' );
854
		if ( ! $gmt_offset ) {
855
			$gmt_offset = 0;
856
		}
857
858
		$stats_options = get_option( 'stats_options' );
859
		$stats_id      = isset( $stats_options['blog_id'] )
860
			? $stats_options['blog_id']
861
			: null;
862
863
		/**
864
		 * Filters the request body for additional property addition.
865
		 *
866
		 * @since 7.7.0
867
		 *
868
		 * @param array $post_data request data.
869
		 * @param Array $token_data token data.
870
		 */
871
		$body = apply_filters(
872
			'jetpack_register_request_body',
873
			array(
874
				'siteurl'            => site_url(),
875
				'home'               => home_url(),
876
				'gmt_offset'         => $gmt_offset,
877
				'timezone_string'    => (string) get_option( 'timezone_string' ),
878
				'site_name'          => (string) get_option( 'blogname' ),
879
				'secret_1'           => $secrets['secret_1'],
880
				'secret_2'           => $secrets['secret_2'],
881
				'site_lang'          => get_locale(),
882
				'timeout'            => $timeout,
883
				'stats_id'           => $stats_id,
884
				'state'              => get_current_user_id(),
885
				'site_created'       => $this->get_assumed_site_creation_date(),
886
				'jetpack_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
887
				'ABSPATH'            => Constants::get_constant( 'ABSPATH' ),
888
				'current_user_email' => wp_get_current_user()->user_email,
889
				'connect_plugin'     => $this->get_plugin() ? $this->get_plugin()->get_slug() : null,
890
			)
891
		);
892
893
		$args = array(
894
			'method'  => 'POST',
895
			'body'    => $body,
896
			'headers' => array(
897
				'Accept' => 'application/json',
898
			),
899
			'timeout' => $timeout,
900
		);
901
902
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
903
904
		// TODO: fix URLs for bad hosts.
905
		$response = Client::_wp_remote_request(
906
			$this->api_url( $api_endpoint ),
907
			$args,
908
			true
909
		);
910
911
		// Make sure the response is valid and does not contain any Jetpack errors.
912
		$registration_details = $this->validate_remote_register_response( $response );
913
914
		if ( is_wp_error( $registration_details ) ) {
915
			return $registration_details;
916
		} elseif ( ! $registration_details ) {
917
			return new \WP_Error(
918
				'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...
919
				'Unknown error registering your Jetpack site.',
920
				wp_remote_retrieve_response_code( $response )
921
			);
922
		}
923
924
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
925
			return new \WP_Error(
926
				'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...
927
				'Unable to validate registration of your Jetpack site.',
928
				wp_remote_retrieve_response_code( $response )
929
			);
930
		}
931
932
		if ( isset( $registration_details->jetpack_public ) ) {
933
			$jetpack_public = (int) $registration_details->jetpack_public;
934
		} else {
935
			$jetpack_public = false;
936
		}
937
938
		\Jetpack_Options::update_options(
939
			array(
940
				'id'     => (int) $registration_details->jetpack_id,
941
				'public' => $jetpack_public,
942
			)
943
		);
944
945
		$this->get_tokens()->update_blog_token( (string) $registration_details->jetpack_secret );
946
947
		/**
948
		 * Fires when a site is registered on WordPress.com.
949
		 *
950
		 * @since 3.7.0
951
		 *
952
		 * @param int $json->jetpack_id Jetpack Blog ID.
953
		 * @param string $json->jetpack_secret Jetpack Blog Token.
954
		 * @param int|bool $jetpack_public Is the site public.
955
		 */
956
		do_action(
957
			'jetpack_site_registered',
958
			$registration_details->jetpack_id,
959
			$registration_details->jetpack_secret,
960
			$jetpack_public
961
		);
962
963
		if ( isset( $registration_details->token ) ) {
964
			/**
965
			 * Fires when a user token is sent along with the registration data.
966
			 *
967
			 * @since 7.6.0
968
			 *
969
			 * @param object $token the administrator token for the newly registered site.
970
			 */
971
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
972
		}
973
974
		return true;
975
	}
976
977
	/**
978
	 * Takes the response from the Jetpack register new site endpoint and
979
	 * verifies it worked properly.
980
	 *
981
	 * @since 2.6
982
	 *
983
	 * @param Mixed $response the response object, or the error object.
984
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
985
	 **/
986
	protected function validate_remote_register_response( $response ) {
987
		if ( is_wp_error( $response ) ) {
988
			return new \WP_Error(
989
				'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...
990
				$response->get_error_message()
991
			);
992
		}
993
994
		$code   = wp_remote_retrieve_response_code( $response );
995
		$entity = wp_remote_retrieve_body( $response );
996
997
		if ( $entity ) {
998
			$registration_response = json_decode( $entity );
999
		} else {
1000
			$registration_response = false;
1001
		}
1002
1003
		$code_type = (int) ( $code / 100 );
1004
		if ( 5 === $code_type ) {
1005
			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...
1006
		} elseif ( 408 === $code ) {
1007
			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...
1008
		} elseif ( ! empty( $registration_response->error ) ) {
1009
			if (
1010
				'xml_rpc-32700' === $registration_response->error
1011
				&& ! function_exists( 'xml_parser_create' )
1012
			) {
1013
				$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' );
1014
			} else {
1015
				$error_description = isset( $registration_response->error_description )
1016
					? (string) $registration_response->error_description
1017
					: '';
1018
			}
1019
1020
			return new \WP_Error(
1021
				(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...
1022
				$error_description,
1023
				$code
1024
			);
1025
		} elseif ( 200 !== $code ) {
1026
			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...
1027
		}
1028
1029
		// Jetpack ID error block.
1030
		if ( empty( $registration_response->jetpack_id ) ) {
1031
			return new \WP_Error(
1032
				'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...
1033
				/* translators: %s is an error message string */
1034
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1035
				$entity
1036
			);
1037
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1038
			return new \WP_Error(
1039
				'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...
1040
				/* translators: %s is an error message string */
1041
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1042
				$entity
1043
			);
1044 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1045
			return new \WP_Error(
1046
				'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...
1047
				/* translators: %s is an error message string */
1048
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1049
				$entity
1050
			);
1051
		}
1052
1053
		return $registration_response;
1054
	}
1055
1056
	/**
1057
	 * Adds a used nonce to a list of known nonces.
1058
	 *
1059
	 * @param int    $timestamp the current request timestamp.
1060
	 * @param string $nonce the nonce value.
1061
	 * @return bool whether the nonce is unique or not.
1062
	 */
1063
	public function add_nonce( $timestamp, $nonce ) {
1064
		global $wpdb;
1065
		static $nonces_used_this_request = array();
1066
1067
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
1068
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
1069
		}
1070
1071
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
1072
		$timestamp = (int) $timestamp;
1073
		$nonce     = esc_sql( $nonce );
1074
1075
		// Raw query so we can avoid races: add_option will also update.
1076
		$show_errors = $wpdb->show_errors( false );
1077
1078
		$old_nonce = $wpdb->get_row(
1079
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1080
		);
1081
1082
		if ( is_null( $old_nonce ) ) {
1083
			$return = $wpdb->query(
1084
				$wpdb->prepare(
1085
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1086
					"jetpack_nonce_{$timestamp}_{$nonce}",
1087
					time(),
1088
					'no'
1089
				)
1090
			);
1091
		} else {
1092
			$return = false;
1093
		}
1094
1095
		$wpdb->show_errors( $show_errors );
1096
1097
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1098
1099
		return $return;
1100
	}
1101
1102
	/**
1103
	 * Cleans nonces that were saved when calling ::add_nonce.
1104
	 *
1105
	 * @todo Properly prepare the query before executing it.
1106
	 *
1107
	 * @param bool $all whether to clean even non-expired nonces.
1108
	 */
1109
	public function clean_nonces( $all = false ) {
1110
		global $wpdb;
1111
1112
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1113
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1114
1115
		if ( true !== $all ) {
1116
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1117
			$sql_args[] = time() - 3600;
1118
		}
1119
1120
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1121
1122
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1123
1124
		for ( $i = 0; $i < 1000; $i++ ) {
1125
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1126
				break;
1127
			}
1128
		}
1129
	}
1130
1131
	/**
1132
	 * Sets the Connection custom capabilities.
1133
	 *
1134
	 * @param string[] $caps    Array of the user's capabilities.
1135
	 * @param string   $cap     Capability name.
1136
	 * @param int      $user_id The user ID.
1137
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1138
	 */
1139
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1140
		$is_offline_mode = ( new Status() )->is_offline_mode();
1141
		switch ( $cap ) {
1142
			case 'jetpack_connect':
1143
			case 'jetpack_reconnect':
1144
				if ( $is_offline_mode ) {
1145
					$caps = array( 'do_not_allow' );
1146
					break;
1147
				}
1148
				// Pass through. If it's not offline mode, these should match disconnect.
1149
				// Let users disconnect if it's offline mode, just in case things glitch.
1150
			case 'jetpack_disconnect':
1151
				/**
1152
				 * Filters the jetpack_disconnect capability.
1153
				 *
1154
				 * @since 8.7.0
1155
				 *
1156
				 * @param array An array containing the capability name.
1157
				 */
1158
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1159
				break;
1160
			case 'jetpack_connect_user':
1161
				if ( $is_offline_mode ) {
1162
					$caps = array( 'do_not_allow' );
1163
					break;
1164
				}
1165
				// With user-less connections in mind, non-admin users can connect their account only if a connection owner exists.
1166
				$caps = $this->has_connected_owner() ? array( 'read' ) : array( 'manage_options' );
1167
				break;
1168
		}
1169
		return $caps;
1170
	}
1171
1172
	/**
1173
	 * Builds the timeout limit for queries talking with the wpcom servers.
1174
	 *
1175
	 * Based on local php max_execution_time in php.ini
1176
	 *
1177
	 * @since 5.4
1178
	 * @return int
1179
	 **/
1180
	public function get_max_execution_time() {
1181
		$timeout = (int) ini_get( 'max_execution_time' );
1182
1183
		// Ensure exec time set in php.ini.
1184
		if ( ! $timeout ) {
1185
			$timeout = 30;
1186
		}
1187
		return $timeout;
1188
	}
1189
1190
	/**
1191
	 * Sets a minimum request timeout, and returns the current timeout
1192
	 *
1193
	 * @since 5.4
1194
	 * @param Integer $min_timeout the minimum timeout value.
1195
	 **/
1196 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1197
		$timeout = $this->get_max_execution_time();
1198
		if ( $timeout < $min_timeout ) {
1199
			$timeout = $min_timeout;
1200
			set_time_limit( $timeout );
1201
		}
1202
		return $timeout;
1203
	}
1204
1205
	/**
1206
	 * Get our assumed site creation date.
1207
	 * Calculated based on the earlier date of either:
1208
	 * - Earliest admin user registration date.
1209
	 * - Earliest date of post of any post type.
1210
	 *
1211
	 * @since 7.2.0
1212
	 *
1213
	 * @return string Assumed site creation date and time.
1214
	 */
1215
	public function get_assumed_site_creation_date() {
1216
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1217
		if ( ! empty( $cached_date ) ) {
1218
			return $cached_date;
1219
		}
1220
1221
		$earliest_registered_users  = get_users(
1222
			array(
1223
				'role'    => 'administrator',
1224
				'orderby' => 'user_registered',
1225
				'order'   => 'ASC',
1226
				'fields'  => array( 'user_registered' ),
1227
				'number'  => 1,
1228
			)
1229
		);
1230
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1231
1232
		$earliest_posts = get_posts(
1233
			array(
1234
				'posts_per_page' => 1,
1235
				'post_type'      => 'any',
1236
				'post_status'    => 'any',
1237
				'orderby'        => 'date',
1238
				'order'          => 'ASC',
1239
			)
1240
		);
1241
1242
		// If there are no posts at all, we'll count only on user registration date.
1243
		if ( $earliest_posts ) {
1244
			$earliest_post_date = $earliest_posts[0]->post_date;
1245
		} else {
1246
			$earliest_post_date = PHP_INT_MAX;
1247
		}
1248
1249
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1250
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1251
1252
		return $assumed_date;
1253
	}
1254
1255
	/**
1256
	 * Adds the activation source string as a parameter to passed arguments.
1257
	 *
1258
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1259
	 *
1260
	 * @param array $args arguments that need to have the source added.
1261
	 * @return array $amended arguments.
1262
	 */
1263 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1264
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1265
1266
		if ( $activation_source_name ) {
1267
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1268
			$args['_as'] = urlencode( $activation_source_name );
1269
		}
1270
1271
		if ( $activation_source_keyword ) {
1272
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1273
			$args['_ak'] = urlencode( $activation_source_keyword );
1274
		}
1275
1276
		return $args;
1277
	}
1278
1279
	/**
1280
	 * Generates two secret tokens and the end of life timestamp for them.
1281
	 *
1282
	 * @param String  $action  The action name.
1283
	 * @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...
1284
	 * @param Integer $exp     Expiration time in seconds.
1285
	 */
1286
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1287
		return ( new Secrets() )->generate( $action, $user_id, $exp );
1288
	}
1289
1290
	/**
1291
	 * Returns two secret tokens and the end of life timestamp for them.
1292
	 *
1293
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->get() instead.
1294
	 *
1295
	 * @param String  $action  The action name.
1296
	 * @param Integer $user_id The user identifier.
1297
	 * @return string|array an array of secrets or an error string.
1298
	 */
1299
	public function get_secrets( $action, $user_id ) {
1300
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->get' );
1301
		return ( new Secrets() )->get( $action, $user_id );
1302
	}
1303
1304
	/**
1305
	 * Deletes secret tokens in case they, for example, have expired.
1306
	 *
1307
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->delete() instead.
1308
	 *
1309
	 * @param String  $action  The action name.
1310
	 * @param Integer $user_id The user identifier.
1311
	 */
1312
	public function delete_secrets( $action, $user_id ) {
1313
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->delete' );
1314
		( new Secrets() )->delete( $action, $user_id );
1315
	}
1316
1317
	/**
1318
	 * Deletes all connection tokens and transients from the local Jetpack site.
1319
	 * If the plugin object has been provided in the constructor, the function first checks
1320
	 * whether it's the only active connection.
1321
	 * If there are any other connections, the function will do nothing and return `false`
1322
	 * (unless `$ignore_connected_plugins` is set to `true`).
1323
	 *
1324
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1325
	 *
1326
	 * @return bool True if disconnected successfully, false otherwise.
1327
	 */
1328
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1329
		// refuse to delete if we're not the last Jetpack plugin installed.
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_delete_all_tokens', true ) ) {
1341
			return false;
1342
		}
1343
1344
		\Jetpack_Options::delete_option(
1345
			array(
1346
				'master_user',
1347
				'time_diff',
1348
				'fallback_no_verify_ssl_certs',
1349
			)
1350
		);
1351
1352
		( new Secrets() )->delete_all();
1353
		$this->get_tokens()->delete_all();
1354
1355
		// Delete cached connected user data.
1356
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1357
		delete_transient( $transient_key );
1358
1359
		// Delete all XML-RPC errors.
1360
		Error_Handler::get_instance()->delete_all_errors();
1361
1362
		return true;
1363
	}
1364
1365
	/**
1366
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1367
	 * If the plugin object has been provided in the constructor, the function first check
1368
	 * whether it's the only active connection.
1369
	 * If there are any other connections, the function will do nothing and return `false`
1370
	 * (unless `$ignore_connected_plugins` is set to `true`).
1371
	 *
1372
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1373
	 *
1374
	 * @return bool True if disconnected successfully, false otherwise.
1375
	 */
1376
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1377 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1378
			return false;
1379
		}
1380
1381
		/**
1382
		 * Fires upon the disconnect attempt.
1383
		 * Return `false` to prevent the disconnect.
1384
		 *
1385
		 * @since 8.7.0
1386
		 */
1387
		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...
1388
			return false;
1389
		}
1390
1391
		$xml = new \Jetpack_IXR_Client();
1392
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1393
1394
		return true;
1395
	}
1396
1397
	/**
1398
	 * Disconnect the plugin and remove the tokens.
1399
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1400
	 * This is a proxy method to simplify the Connection package API.
1401
	 *
1402
	 * @see Manager::disable_plugin()
1403
	 * @see Manager::disconnect_site_wpcom()
1404
	 * @see Manager::delete_all_connection_tokens()
1405
	 *
1406
	 * @return bool
1407
	 */
1408
	public function remove_connection() {
1409
		$this->disable_plugin();
1410
		$this->disconnect_site_wpcom();
1411
		$this->delete_all_connection_tokens();
1412
1413
		return true;
1414
	}
1415
1416
	/**
1417
	 * Completely clearing up the connection, and initiating reconnect.
1418
	 *
1419
	 * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
1420
	 */
1421
	public function reconnect() {
1422
		( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
1423
1424
		$this->disconnect_site_wpcom( true );
1425
		$this->delete_all_connection_tokens( true );
1426
1427
		return $this->register();
1428
	}
1429
1430
	/**
1431
	 * Validate the tokens, and refresh the invalid ones.
1432
	 *
1433
	 * @return string|true|WP_Error True if connection restored or string indicating what's to be done next. A `WP_Error` object otherwise.
1434
	 */
1435
	public function restore() {
1436
1437
		$validate_tokens_response = $this->get_tokens()->validate();
1438
1439
		$blog_token_healthy = $validate_tokens_response['blog_token']['is_healthy'];
1440
		$user_token_healthy = $validate_tokens_response['user_token']['is_healthy'];
1441
1442
		// Tokens are both valid, or both invalid. We can't fix the problem we don't see, so the full reconnection is needed.
1443
		if ( $blog_token_healthy === $user_token_healthy ) {
1444
			$result = $this->reconnect();
1445
			return ( true === $result ) ? 'authorize' : $result;
1446
		}
1447
1448
		if ( ! $blog_token_healthy ) {
1449
			return $this->refresh_blog_token();
1450
		}
1451
1452
		if ( ! $user_token_healthy ) {
1453
			return ( true === $this->refresh_user_token() ) ? 'authorize' : false;
1454
		}
1455
1456
		return false;
1457
	}
1458
1459
	/**
1460
	 * Responds to a WordPress.com call to register the current site.
1461
	 * Should be changed to protected.
1462
	 *
1463
	 * @param array $registration_data Array of [ secret_1, user_id ].
1464
	 */
1465
	public function handle_registration( array $registration_data ) {
1466
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1467
		if ( empty( $registration_user_id ) ) {
1468
			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...
1469
		}
1470
1471
		return ( new Secrets() )->verify( 'register', $registration_secret_1, (int) $registration_user_id );
1472
	}
1473
1474
	/**
1475
	 * Perform the API request to validate the blog and user tokens.
1476
	 *
1477
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->validate_tokens() instead.
1478
	 *
1479
	 * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
1480
	 *
1481
	 * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
1482
	 */
1483
	public function validate_tokens( $user_id = null ) {
1484
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->validate' );
1485
		return $this->get_tokens()->validate( $user_id );
1486
	}
1487
1488
	/**
1489
	 * Verify a Previously Generated Secret.
1490
	 *
1491
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->verify() instead.
1492
	 *
1493
	 * @param string $action   The type of secret to verify.
1494
	 * @param string $secret_1 The secret string to compare to what is stored.
1495
	 * @param int    $user_id  The user ID of the owner of the secret.
1496
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1497
	 */
1498
	public function verify_secrets( $action, $secret_1, $user_id ) {
1499
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->verify' );
1500
		return ( new Secrets() )->verify( $action, $secret_1, $user_id );
1501
	}
1502
1503
	/**
1504
	 * Responds to a WordPress.com call to authorize the current user.
1505
	 * Should be changed to protected.
1506
	 */
1507
	public function handle_authorization() {
1508
1509
	}
1510
1511
	/**
1512
	 * Obtains the auth token.
1513
	 *
1514
	 * @param array $data The request data.
1515
	 * @return object|\WP_Error Returns the auth token on success.
1516
	 *                          Returns a \WP_Error on failure.
1517
	 */
1518
	public function get_token( $data ) {
1519
		return $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1520
	}
1521
1522
	/**
1523
	 * Builds a URL to the Jetpack connection auth page.
1524
	 *
1525
	 * @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...
1526
	 * @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...
1527
	 * @return string Connect URL.
1528
	 */
1529
	public function get_authorization_url( $user = null, $redirect = null ) {
1530
1531
		if ( empty( $user ) ) {
1532
			$user = wp_get_current_user();
1533
		}
1534
1535
		$roles       = new Roles();
1536
		$role        = $roles->translate_user_to_role( $user );
1537
		$signed_role = $this->get_tokens()->sign_role( $role );
1538
1539
		/**
1540
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1541
		 * data processing.
1542
		 *
1543
		 * @since 8.0.0
1544
		 *
1545
		 * @param string $redirect_url Defaults to the site admin URL.
1546
		 */
1547
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1548
1549
		/**
1550
		 * Filter the URL to redirect the user back to when the authorization process
1551
		 * is complete.
1552
		 *
1553
		 * @since 8.0.0
1554
		 *
1555
		 * @param string $redirect_url Defaults to the site URL.
1556
		 */
1557
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1558
1559
		$secrets = ( new Secrets() )->generate( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1560
1561
		/**
1562
		 * Filter the type of authorization.
1563
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1564
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1565
		 *
1566
		 * @since 4.3.3
1567
		 *
1568
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1569
		 */
1570
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1571
1572
		/**
1573
		 * Filters the user connection request data for additional property addition.
1574
		 *
1575
		 * @since 8.0.0
1576
		 *
1577
		 * @param array $request_data request data.
1578
		 */
1579
		$body = apply_filters(
1580
			'jetpack_connect_request_body',
1581
			array(
1582
				'response_type' => 'code',
1583
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1584
				'redirect_uri'  => add_query_arg(
1585
					array(
1586
						'handler'  => 'jetpack-connection-webhooks',
1587
						'action'   => 'authorize',
1588
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1589
						'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1590
					),
1591
					esc_url( $processing_url )
1592
				),
1593
				'state'         => $user->ID,
1594
				'scope'         => $signed_role,
1595
				'user_email'    => $user->user_email,
1596
				'user_login'    => $user->user_login,
1597
				'is_active'     => $this->is_active(),
1598
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1599
				'auth_type'     => $auth_type,
1600
				'secret'        => $secrets['secret_1'],
1601
				'blogname'      => get_option( 'blogname' ),
1602
				'site_url'      => site_url(),
1603
				'home_url'      => home_url(),
1604
				'site_icon'     => get_site_icon_url(),
1605
				'site_lang'     => get_locale(),
1606
				'site_created'  => $this->get_assumed_site_creation_date(),
1607
			)
1608
		);
1609
1610
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1611
1612
		$api_url = $this->api_url( 'authorize' );
1613
1614
		return add_query_arg( $body, $api_url );
1615
	}
1616
1617
	/**
1618
	 * Authorizes the user by obtaining and storing the user token.
1619
	 *
1620
	 * @param array $data The request data.
1621
	 * @return string|\WP_Error Returns a string on success.
1622
	 *                          Returns a \WP_Error on failure.
1623
	 */
1624
	public function authorize( $data = array() ) {
1625
		/**
1626
		 * Action fired when user authorization starts.
1627
		 *
1628
		 * @since 8.0.0
1629
		 */
1630
		do_action( 'jetpack_authorize_starting' );
1631
1632
		$roles = new Roles();
1633
		$role  = $roles->translate_current_user_to_role();
1634
1635
		if ( ! $role ) {
1636
			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...
1637
		}
1638
1639
		$cap = $roles->translate_role_to_cap( $role );
1640
		if ( ! $cap ) {
1641
			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...
1642
		}
1643
1644
		if ( ! empty( $data['error'] ) ) {
1645
			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...
1646
		}
1647
1648
		if ( ! isset( $data['state'] ) ) {
1649
			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...
1650
		}
1651
1652
		if ( ! ctype_digit( $data['state'] ) ) {
1653
			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...
1654
		}
1655
1656
		$current_user_id = get_current_user_id();
1657
		if ( $current_user_id !== (int) $data['state'] ) {
1658
			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...
1659
		}
1660
1661
		if ( empty( $data['code'] ) ) {
1662
			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...
1663
		}
1664
1665
		$token = $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1666
1667 View Code Duplication
		if ( is_wp_error( $token ) ) {
1668
			$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...
1669
			if ( empty( $code ) ) {
1670
				$code = 'invalid_token';
1671
			}
1672
			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...
1673
		}
1674
1675
		if ( ! $token ) {
1676
			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...
1677
		}
1678
1679
		$is_connection_owner = ! $this->has_connected_owner();
1680
1681
		$this->get_tokens()->update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_connection_owner );
1682
1683
		/**
1684
		 * Fires after user has successfully received an auth token.
1685
		 *
1686
		 * @since 3.9.0
1687
		 */
1688
		do_action( 'jetpack_user_authorized' );
1689
1690
		if ( ! $is_connection_owner ) {
1691
			/**
1692
			 * Action fired when a secondary user has been authorized.
1693
			 *
1694
			 * @since 8.0.0
1695
			 */
1696
			do_action( 'jetpack_authorize_ending_linked' );
1697
			return 'linked';
1698
		}
1699
1700
		/**
1701
		 * Action fired when the master user has been authorized.
1702
		 *
1703
		 * @since 8.0.0
1704
		 *
1705
		 * @param array $data The request data.
1706
		 */
1707
		do_action( 'jetpack_authorize_ending_authorized', $data );
1708
1709
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
1710
1711
		// Start nonce cleaner.
1712
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
1713
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
1714
1715
		return 'authorized';
1716
	}
1717
1718
	/**
1719
	 * Disconnects from the Jetpack servers.
1720
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1721
	 */
1722
	public function disconnect_site() {
1723
1724
	}
1725
1726
	/**
1727
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1728
	 *
1729
	 * @param string $text The string to hash.
1730
	 * @return string
1731
	 */
1732
	public function sha1_base64( $text ) {
1733
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1734
	}
1735
1736
	/**
1737
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1738
	 *
1739
	 * @param string $domain The domain to check.
1740
	 *
1741
	 * @return bool|WP_Error
1742
	 */
1743
	public function is_usable_domain( $domain ) {
1744
1745
		// If it's empty, just fail out.
1746
		if ( ! $domain ) {
1747
			return new \WP_Error(
1748
				'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...
1749
				/* translators: %1$s is a domain name. */
1750
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1751
			);
1752
		}
1753
1754
		/**
1755
		 * Skips the usuable domain check when connecting a site.
1756
		 *
1757
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1758
		 *
1759
		 * @since 4.1.0
1760
		 *
1761
		 * @param bool If the check should be skipped. Default false.
1762
		 */
1763
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1764
			return true;
1765
		}
1766
1767
		// None of the explicit localhosts.
1768
		$forbidden_domains = array(
1769
			'wordpress.com',
1770
			'localhost',
1771
			'localhost.localdomain',
1772
			'127.0.0.1',
1773
			'local.wordpress.test',         // VVV pattern.
1774
			'local.wordpress-trunk.test',   // VVV pattern.
1775
			'src.wordpress-develop.test',   // VVV pattern.
1776
			'build.wordpress-develop.test', // VVV pattern.
1777
		);
1778 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1779
			return new \WP_Error(
1780
				'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...
1781
				sprintf(
1782
					/* translators: %1$s is a domain name. */
1783
					__(
1784
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1785
						'jetpack'
1786
					),
1787
					$domain
1788
				)
1789
			);
1790
		}
1791
1792
		// No .test or .local domains.
1793 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1794
			return new \WP_Error(
1795
				'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...
1796
				sprintf(
1797
					/* translators: %1$s is a domain name. */
1798
					__(
1799
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1800
						'jetpack'
1801
					),
1802
					$domain
1803
				)
1804
			);
1805
		}
1806
1807
		// No WPCOM subdomains.
1808 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1809
			return new \WP_Error(
1810
				'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...
1811
				sprintf(
1812
					/* translators: %1$s is a domain name. */
1813
					__(
1814
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1815
						'jetpack'
1816
					),
1817
					$domain
1818
				)
1819
			);
1820
		}
1821
1822
		// If PHP was compiled without support for the Filter module (very edge case).
1823
		if ( ! function_exists( 'filter_var' ) ) {
1824
			// Just pass back true for now, and let wpcom sort it out.
1825
			return true;
1826
		}
1827
1828
		return true;
1829
	}
1830
1831
	/**
1832
	 * Gets the requested token.
1833
	 *
1834
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_access_token() instead.
1835
	 *
1836
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1837
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1838
	 * @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.
1839
	 *
1840
	 * @return object|false
1841
	 *
1842
	 * @see $this->get_tokens()->get_access_token()
1843
	 */
1844
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1845
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_access_token' );
1846
		return $this->get_tokens()->get_access_token( $user_id, $token_key, $suppress_errors );
1847
	}
1848
1849
	/**
1850
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
1851
	 * since it is passed by reference to various methods.
1852
	 * Capture it here so we can verify the signature later.
1853
	 *
1854
	 * @param array $methods an array of available XMLRPC methods.
1855
	 * @return array the same array, since this method doesn't add or remove anything.
1856
	 */
1857
	public function xmlrpc_methods( $methods ) {
1858
		$this->raw_post_data = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
1859
		return $methods;
1860
	}
1861
1862
	/**
1863
	 * Resets the raw post data parameter for testing purposes.
1864
	 */
1865
	public function reset_raw_post_data() {
1866
		$this->raw_post_data = null;
1867
	}
1868
1869
	/**
1870
	 * Registering an additional method.
1871
	 *
1872
	 * @param array $methods an array of available XMLRPC methods.
1873
	 * @return array the amended array in case the method is added.
1874
	 */
1875
	public function public_xmlrpc_methods( $methods ) {
1876
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
1877
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
1878
		}
1879
		return $methods;
1880
	}
1881
1882
	/**
1883
	 * Handles a getOptions XMLRPC method call.
1884
	 *
1885
	 * @param array $args method call arguments.
1886
	 * @return an amended XMLRPC server options array.
1887
	 */
1888
	public function jetpack_get_options( $args ) {
1889
		global $wp_xmlrpc_server;
1890
1891
		$wp_xmlrpc_server->escape( $args );
1892
1893
		$username = $args[1];
1894
		$password = $args[2];
1895
1896
		$user = $wp_xmlrpc_server->login( $username, $password );
1897
		if ( ! $user ) {
1898
			return $wp_xmlrpc_server->error;
1899
		}
1900
1901
		$options   = array();
1902
		$user_data = $this->get_connected_user_data();
1903
		if ( is_array( $user_data ) ) {
1904
			$options['jetpack_user_id']         = array(
1905
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
1906
				'readonly' => true,
1907
				'value'    => $user_data['ID'],
1908
			);
1909
			$options['jetpack_user_login']      = array(
1910
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
1911
				'readonly' => true,
1912
				'value'    => $user_data['login'],
1913
			);
1914
			$options['jetpack_user_email']      = array(
1915
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
1916
				'readonly' => true,
1917
				'value'    => $user_data['email'],
1918
			);
1919
			$options['jetpack_user_site_count'] = array(
1920
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
1921
				'readonly' => true,
1922
				'value'    => $user_data['site_count'],
1923
			);
1924
		}
1925
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
1926
		$args                           = stripslashes_deep( $args );
1927
		return $wp_xmlrpc_server->wp_getOptions( $args );
1928
	}
1929
1930
	/**
1931
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
1932
	 *
1933
	 * @param array $options standard Core options.
1934
	 * @return array amended options.
1935
	 */
1936
	public function xmlrpc_options( $options ) {
1937
		$jetpack_client_id = false;
1938
		if ( $this->is_active() ) {
1939
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
1940
		}
1941
		$options['jetpack_version'] = array(
1942
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
1943
			'readonly' => true,
1944
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
1945
		);
1946
1947
		$options['jetpack_client_id'] = array(
1948
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
1949
			'readonly' => true,
1950
			'value'    => $jetpack_client_id,
1951
		);
1952
		return $options;
1953
	}
1954
1955
	/**
1956
	 * Resets the saved authentication state in between testing requests.
1957
	 */
1958
	public function reset_saved_auth_state() {
1959
		$this->xmlrpc_verification = null;
1960
	}
1961
1962
	/**
1963
	 * Sign a user role with the master access token.
1964
	 * If not specified, will default to the current user.
1965
	 *
1966
	 * @access public
1967
	 *
1968
	 * @param string $role    User role.
1969
	 * @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...
1970
	 * @return string Signed user role.
1971
	 */
1972
	public function sign_role( $role, $user_id = null ) {
1973
		return $this->get_tokens()->sign_role( $role, $user_id );
1974
	}
1975
1976
	/**
1977
	 * Set the plugin instance.
1978
	 *
1979
	 * @param Plugin $plugin_instance The plugin instance.
1980
	 *
1981
	 * @return $this
1982
	 */
1983
	public function set_plugin_instance( Plugin $plugin_instance ) {
1984
		$this->plugin = $plugin_instance;
1985
1986
		return $this;
1987
	}
1988
1989
	/**
1990
	 * Retrieve the plugin management object.
1991
	 *
1992
	 * @return Plugin
1993
	 */
1994
	public function get_plugin() {
1995
		return $this->plugin;
1996
	}
1997
1998
	/**
1999
	 * Get all connected plugins information, excluding those disconnected by user.
2000
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2001
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2002
	 * so please make sure not to run the method too early in the code.
2003
	 *
2004
	 * @return array|WP_Error
2005
	 */
2006
	public function get_connected_plugins() {
2007
		$maybe_plugins = Plugin_Storage::get_all( true );
2008
2009
		if ( $maybe_plugins instanceof WP_Error ) {
2010
			return $maybe_plugins;
2011
		}
2012
2013
		return $maybe_plugins;
2014
	}
2015
2016
	/**
2017
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2018
	 * Note: this method does not remove any access tokens.
2019
	 *
2020
	 * @return bool
2021
	 */
2022
	public function disable_plugin() {
2023
		if ( ! $this->plugin ) {
2024
			return false;
2025
		}
2026
2027
		return $this->plugin->disable();
2028
	}
2029
2030
	/**
2031
	 * Force plugin reconnect after user-initiated disconnect.
2032
	 * After its called, the plugin will be allowed to use the connection again.
2033
	 * Note: this method does not initialize access tokens.
2034
	 *
2035
	 * @return bool
2036
	 */
2037
	public function enable_plugin() {
2038
		if ( ! $this->plugin ) {
2039
			return false;
2040
		}
2041
2042
		return $this->plugin->enable();
2043
	}
2044
2045
	/**
2046
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2047
	 * If no plugin slug was passed into the constructor, always returns true.
2048
	 *
2049
	 * @return bool
2050
	 */
2051
	public function is_plugin_enabled() {
2052
		if ( ! $this->plugin ) {
2053
			return true;
2054
		}
2055
2056
		return $this->plugin->is_enabled();
2057
	}
2058
2059
	/**
2060
	 * Perform the API request to refresh the blog token.
2061
	 * Note that we are making this request on behalf of the Jetpack master user,
2062
	 * given they were (most probably) the ones that registered the site at the first place.
2063
	 *
2064
	 * @return WP_Error|bool The result of updating the blog_token option.
2065
	 */
2066
	/**
2067
	 * Perform the API request to refresh the blog token.
2068
	 * Note that we are making this request on behalf of the Jetpack master user,
2069
	 * given they were (most probably) the ones that registered the site at the first place.
2070
	 *
2071
	 * @return WP_Error|bool The result of updating the blog_token option.
2072
	 */
2073
	public function refresh_blog_token() {
2074
		( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
2075
2076
		$blog_id = \Jetpack_Options::get_option( 'id' );
2077
		if ( ! $blog_id ) {
2078
			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...
2079
		}
2080
2081
		$url     = sprintf(
2082
			'%s/%s/v%s/%s',
2083
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
2084
			'wpcom',
2085
			'2',
2086
			'sites/' . $blog_id . '/jetpack-refresh-blog-token'
2087
		);
2088
		$method  = 'POST';
2089
		$user_id = get_current_user_id();
2090
2091
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2092
2093
		if ( is_wp_error( $response ) ) {
2094
			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...
2095
		}
2096
2097
		$code   = wp_remote_retrieve_response_code( $response );
2098
		$entity = wp_remote_retrieve_body( $response );
2099
2100
		if ( $entity ) {
2101
			$json = json_decode( $entity );
2102
		} else {
2103
			$json = false;
2104
		}
2105
2106 View Code Duplication
		if ( 200 !== $code ) {
2107
			if ( empty( $json->code ) ) {
2108
				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...
2109
			}
2110
2111
			/* translators: Error description string. */
2112
			$error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->message ) : '';
2113
2114
			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...
2115
		}
2116
2117
		if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
2118
			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...
2119
		}
2120
2121
		return $this->get_tokens()->update_blog_token( (string) $json->jetpack_secret );
2122
	}
2123
2124
	/**
2125
	 * Disconnect the user from WP.com, and initiate the reconnect process.
2126
	 *
2127
	 * @return bool
2128
	 */
2129
	public function refresh_user_token() {
2130
		( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2131
		$this->disconnect_user( null, true );
2132
		return true;
2133
	}
2134
2135
	/**
2136
	 * Fetches a signed token.
2137
	 *
2138
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_signed_token() instead.
2139
	 *
2140
	 * @param object $token the token.
2141
	 * @return WP_Error|string a signed token
2142
	 */
2143
	public function get_signed_token( $token ) {
2144
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_signed_token' );
2145
		return $this->get_tokens()->get_signed_token( $token );
2146
	}
2147
2148
	/**
2149
	 * If connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2150
	 *
2151
	 * @param array $stats The Heartbeat stats array.
2152
	 * @return array $stats
2153
	 */
2154
	public function add_stats_to_heartbeat( $stats ) {
2155
2156
		if ( ! $this->is_active() ) {
2157
			return $stats;
2158
		}
2159
2160
		$active_plugins_using_connection = Plugin_Storage::get_all();
2161
		foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
2162
			if ( 'jetpack' !== $plugin_slug ) {
2163
				$stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2164
				$stats[ $stats_group ][] = $plugin_slug;
2165
			}
2166
		}
2167
		return $stats;
2168
	}
2169
}
2170