Completed
Push — try/refactor-secrets-and-token... ( 313ee5 )
by
unknown
381:48 queued 371:37
created

Manager::alternate_xmlrpc()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 24
rs 9.536
c 0
b 0
f 0
1
<?php
2
/**
3
 * The Jetpack Connection manager class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Heartbeat;
12
use Automattic\Jetpack\Roles;
13
use Automattic\Jetpack\Status;
14
use Automattic\Jetpack\Tracking;
15
use WP_Error;
16
use WP_User;
17
18
/**
19
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
20
 * and Jetpack.
21
 */
22
class Manager {
23
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
24
25
	/**
26
	 * Constant used to fetch the master user token. Deprecated.
27
	 *
28
	 * @deprecated 9.0.0
29
	 * @see Manager::CONNECTION_OWNER
30
	 * @var boolean
31
	 */
32
	const JETPACK_MASTER_USER = true; //phpcs:ignore Jetpack.Constants.MasterUserConstant.ShouldNotBeUsed
33
34
	/**
35
	 * For internal use only. If you need to get the connection owner, use the provided methods
36
	 * get_connection_owner_id, get_connection_owner and is_connection_owner
37
	 *
38
	 * @todo Add private visibility once PHP 7.1 is the minimum supported verion.
39
	 *
40
	 * @var boolean
41
	 */
42
	const CONNECTION_OWNER = true;
43
44
	/**
45
	 * A copy of the raw POST data for signature verification purposes.
46
	 *
47
	 * @var String
48
	 */
49
	protected $raw_post_data;
50
51
	/**
52
	 * Verification data needs to be stored to properly verify everything.
53
	 *
54
	 * @var Object
55
	 */
56
	private $xmlrpc_verification = null;
57
58
	/**
59
	 * Plugin management object.
60
	 *
61
	 * @var Plugin
62
	 */
63
	private $plugin = null;
64
65
	/**
66
	 * Initialize the object.
67
	 * Make sure to call the "Configure" first.
68
	 *
69
	 * @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...
70
	 *
71
	 * @see \Automattic\Jetpack\Config
72
	 */
73
	public function __construct( $plugin_slug = null ) {
74
		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...
75
			$this->set_plugin_instance( new Plugin( $plugin_slug ) );
76
		}
77
	}
78
79
	/**
80
	 * Initializes required listeners. This is done separately from the constructors
81
	 * because some objects sometimes need to instantiate separate objects of this class.
82
	 *
83
	 * @todo Implement a proper nonce verification.
84
	 */
85
	public static function configure() {
86
		$manager = new self();
87
88
		add_filter(
89
			'jetpack_constant_default_value',
90
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
91
			10,
92
			2
93
		);
94
95
		$manager->setup_xmlrpc_handlers(
96
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
97
			$manager->is_active(),
98
			$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...
99
		);
100
101
		$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...
102
103
		if ( $manager->is_active() ) {
104
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
105
		}
106
107
		add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
108
109
		add_action( 'jetpack_clean_nonces', array( $manager, 'clean_nonces' ) );
110
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
111
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
112
		}
113
114
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
115
116
		add_filter( 'map_meta_cap', array( $manager, 'jetpack_connection_custom_caps' ), 1, 4 );
117
118
		Heartbeat::init();
119
		add_filter( 'jetpack_heartbeat_stats_array', array( $manager, 'add_stats_to_heartbeat' ) );
120
121
		Webhooks::init( $manager );
122
	}
123
124
	/**
125
	 * Sets up the XMLRPC request handlers.
126
	 *
127
	 * @param array                  $request_params incoming request parameters.
128
	 * @param Boolean                $is_active whether the connection is currently active.
129
	 * @param Boolean                $is_signed whether the signature check has been successful.
130
	 * @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...
131
	 */
132
	public function setup_xmlrpc_handlers(
133
		$request_params,
134
		$is_active,
135
		$is_signed,
136
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
137
	) {
138
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
139
140
		if (
141
			! isset( $request_params['for'] )
142
			|| 'jetpack' !== $request_params['for']
143
		) {
144
			return false;
145
		}
146
147
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
148
		if (
149
			isset( $request_params['jetpack'] )
150
			&& 'comms' === $request_params['jetpack']
151
		) {
152
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
153
				// Use the real constant here for WordPress' sake.
154
				define( 'XMLRPC_REQUEST', true );
155
			}
156
157
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
158
159
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
160
		}
161
162
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
163
			return false;
164
		}
165
		// Display errors can cause the XML to be not well formed.
166
		@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...
167
168
		if ( $xmlrpc_server ) {
169
			$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...
170
		} else {
171
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
172
		}
173
174
		$this->require_jetpack_authentication();
175
176
		if ( $is_active ) {
177
			// Hack to preserve $HTTP_RAW_POST_DATA.
178
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
179
180
			if ( $is_signed ) {
181
				// The actual API methods.
182
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
183
			} else {
184
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
185
				// active Jetpack connection, so that additional users can link their account.
186
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
187
			}
188
		} else {
189
			// The bootstrap API methods.
190
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
191
192
			if ( $is_signed ) {
193
				// The jetpack Provision method is available for blog-token-signed requests.
194
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
195
			} else {
196
				new XMLRPC_Connector( $this );
197
			}
198
		}
199
200
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
201
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
202
		return true;
203
	}
204
205
	/**
206
	 * Initializes the REST API connector on the init hook.
207
	 */
208
	public function initialize_rest_api_registration_connector() {
209
		new REST_Connector( $this );
210
	}
211
212
	/**
213
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
214
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
215
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
216
	 * which is accessible via a different URI. Most of the below is copied directly
217
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
218
	 *
219
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
220
	 */
221
	public function alternate_xmlrpc() {
222
		// Some browser-embedded clients send cookies. We don't want them.
223
		$_COOKIE = array();
224
225
		include_once ABSPATH . 'wp-admin/includes/admin.php';
226
		include_once ABSPATH . WPINC . '/class-IXR.php';
227
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
228
229
		/**
230
		 * Filters the class used for handling XML-RPC requests.
231
		 *
232
		 * @since 3.1.0
233
		 *
234
		 * @param string $class The name of the XML-RPC server class.
235
		 */
236
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
237
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
238
239
		// Fire off the request.
240
		nocache_headers();
241
		$wp_xmlrpc_server->serve_request();
242
243
		exit;
244
	}
245
246
	/**
247
	 * Removes all XML-RPC methods that are not `jetpack.*`.
248
	 * Only used in our alternate XML-RPC endpoint, where we want to
249
	 * ensure that Core and other plugins' methods are not exposed.
250
	 *
251
	 * @param array $methods a list of registered WordPress XMLRPC methods.
252
	 * @return array filtered $methods
253
	 */
254
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
255
		$jetpack_methods = array();
256
257
		foreach ( $methods as $method => $callback ) {
258
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
259
				$jetpack_methods[ $method ] = $callback;
260
			}
261
		}
262
263
		return $jetpack_methods;
264
	}
265
266
	/**
267
	 * Removes all other authentication methods not to allow other
268
	 * methods to validate unauthenticated requests.
269
	 */
270
	public function require_jetpack_authentication() {
271
		// Don't let anyone authenticate.
272
		$_COOKIE = array();
273
		remove_all_filters( 'authenticate' );
274
		remove_all_actions( 'wp_login_failed' );
275
276
		if ( $this->is_active() ) {
277
			// Allow Jetpack authentication.
278
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
279
		}
280
	}
281
282
	/**
283
	 * Authenticates XML-RPC and other requests from the Jetpack Server
284
	 *
285
	 * @param WP_User|Mixed $user user object if authenticated.
286
	 * @param String        $username username.
287
	 * @param String        $password password string.
288
	 * @return WP_User|Mixed authenticated user or error.
289
	 */
290
	public function authenticate_jetpack( $user, $username, $password ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
291
		if ( is_a( $user, '\\WP_User' ) ) {
292
			return $user;
293
		}
294
295
		$token_details = $this->verify_xml_rpc_signature();
296
297
		if ( ! $token_details ) {
298
			return $user;
299
		}
300
301
		if ( 'user' !== $token_details['type'] ) {
302
			return $user;
303
		}
304
305
		if ( ! $token_details['user_id'] ) {
306
			return $user;
307
		}
308
309
		nocache_headers();
310
311
		return new \WP_User( $token_details['user_id'] );
312
	}
313
314
	/**
315
	 * Verifies the signature of the current request.
316
	 *
317
	 * @return false|array
318
	 */
319
	public function verify_xml_rpc_signature() {
320
		if ( is_null( $this->xmlrpc_verification ) ) {
321
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
322
323
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
324
				/**
325
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
326
				 *
327
				 * @since 7.5.0
328
				 *
329
				 * @param WP_Error $signature_verification_error The verification error
330
				 */
331
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
332
333
				Error_Handler::get_instance()->report_error( $this->xmlrpc_verification );
334
335
			}
336
		}
337
338
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
339
	}
340
341
	/**
342
	 * Verifies the signature of the current request.
343
	 *
344
	 * This function has side effects and should not be used. Instead,
345
	 * use the memoized version `->verify_xml_rpc_signature()`.
346
	 *
347
	 * @internal
348
	 * @todo Refactor to use proper nonce verification.
349
	 */
350
	private function internal_verify_xml_rpc_signature() {
351
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
352
		// It's not for us.
353
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
354
			return false;
355
		}
356
357
		$signature_details = array(
358
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
359
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
360
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
361
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
362
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
363
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
364
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
365
		);
366
367
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
368
		@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...
369
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
370
371
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
372
373
		if (
374
			empty( $token_key )
375
		||
376
			empty( $version ) || (string) $jetpack_api_version !== $version ) {
377
			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...
378
		}
379
380
		if ( '0' === $user_id ) {
381
			$token_type = 'blog';
382
			$user_id    = 0;
383
		} else {
384
			$token_type = 'user';
385
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
386
				return new \WP_Error(
387
					'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...
388
					'Malformed user_id in request',
389
					compact( 'signature_details' )
390
				);
391
			}
392
			$user_id = (int) $user_id;
393
394
			$user = new \WP_User( $user_id );
395
			if ( ! $user || ! $user->exists() ) {
396
				return new \WP_Error(
397
					'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...
398
					sprintf( 'User %d does not exist', $user_id ),
399
					compact( 'signature_details' )
400
				);
401
			}
402
		}
403
404
		$token = Tokens::get_access_token( $user_id, $token_key, false );
405
		if ( is_wp_error( $token ) ) {
406
			$token->add_data( compact( 'signature_details' ) );
407
			return $token;
408
		} elseif ( ! $token ) {
409
			return new \WP_Error(
410
				'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...
411
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
412
				compact( 'signature_details' )
413
			);
414
		}
415
416
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
417
		// phpcs:disable WordPress.Security.NonceVerification.Missing
418
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
419
			$post_data   = $_POST;
420
			$file_hashes = array();
421
			foreach ( $post_data as $post_data_key => $post_data_value ) {
422
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
423
					continue;
424
				}
425
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
426
				$file_hashes[ $post_data_key ] = $post_data_value;
427
			}
428
429
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
430
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
431
				$post_data[ $post_data_key ] = $post_data_value;
432
			}
433
434
			ksort( $post_data );
435
436
			$body = http_build_query( stripslashes_deep( $post_data ) );
437
		} elseif ( is_null( $this->raw_post_data ) ) {
438
			$body = file_get_contents( 'php://input' );
439
		} else {
440
			$body = null;
441
		}
442
		// phpcs:enable
443
444
		$signature = $jetpack_signature->sign_current_request(
445
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
446
		);
447
448
		$signature_details['url'] = $jetpack_signature->current_request_url;
449
450
		if ( ! $signature ) {
451
			return new \WP_Error(
452
				'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...
453
				'Unknown signature error',
454
				compact( 'signature_details' )
455
			);
456
		} elseif ( is_wp_error( $signature ) ) {
457
			return $signature;
458
		}
459
460
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
461
		$timestamp = (int) $_GET['timestamp'];
462
		$nonce     = stripslashes( (string) $_GET['nonce'] );
463
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
464
465
		// Use up the nonce regardless of whether the signature matches.
466
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
467
			return new \WP_Error(
468
				'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...
469
				'Could not add nonce',
470
				compact( 'signature_details' )
471
			);
472
		}
473
474
		// Be careful about what you do with this debugging data.
475
		// If a malicious requester has access to the expected signature,
476
		// bad things might be possible.
477
		$signature_details['expected'] = $signature;
478
479
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
480
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
481
			return new \WP_Error(
482
				'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...
483
				'Signature mismatch',
484
				compact( 'signature_details' )
485
			);
486
		}
487
488
		/**
489
		 * Action for additional token checking.
490
		 *
491
		 * @since 7.7.0
492
		 *
493
		 * @param array $post_data request data.
494
		 * @param array $token_data token data.
495
		 */
496
		return apply_filters(
497
			'jetpack_signature_check_token',
498
			array(
499
				'type'      => $token_type,
500
				'token_key' => $token_key,
501
				'user_id'   => $token->external_user_id,
502
			),
503
			$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...
504
			$this->raw_post_data
505
		);
506
	}
507
508
	/**
509
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI.
510
	 *
511
	 * @return Boolean is the site connected?
512
	 */
513
	public function is_active() {
514
		if ( ( new Status() )->is_no_user_testing_mode() ) {
515
			return $this->is_connected();
516
		}
517
		return (bool) Tokens::get_access_token( self::CONNECTION_OWNER );
0 ignored issues
show
Documentation introduced by
self::CONNECTION_OWNER 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...
518
	}
519
520
	/**
521
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
522
	 *
523
	 * @access public
524
	 * @deprecated 9.2.0 Use is_connected instead
525
	 * @see Manager::is_connected
526
	 *
527
	 * @return bool
528
	 */
529
	public function is_registered() {
530
		_deprecated_function( __METHOD__, 'jetpack-9.2' );
531
		return $this->is_connected();
532
	}
533
534
	/**
535
	 * Returns true if the site has both a token and a blog id, which indicates a site has been connected.
536
	 *
537
	 * @access public
538
	 * @since 9.2.0
539
	 *
540
	 * @return bool
541
	 */
542
	public function is_connected() {
543
		$has_blog_id    = (bool) \Jetpack_Options::get_option( 'id' );
544
		$has_blog_token = (bool) Tokens::get_access_token( false );
545
		return $has_blog_id && $has_blog_token;
546
	}
547
548
	/**
549
	 * Returns true if the site has at least one connected administrator.
550
	 *
551
	 * @access public
552
	 * @since 9.2.0
553
	 *
554
	 * @return bool
555
	 */
556
	public function has_connected_admin() {
557
		return (bool) count( $this->get_connected_users( 'manage_options' ) );
0 ignored issues
show
Deprecated Code introduced by
The method Automattic\Jetpack\Conne...::get_connected_users() has been deprecated with message: 9.5 Use Automattic\Jetpack\Connection\Tokens::get_connected_users() instead.

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

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

Loading history...
558
	}
559
560
	/**
561
	 * Returns true if the site has any connected user.
562
	 *
563
	 * @access public
564
	 * @since 9.2.0
565
	 *
566
	 * @return bool
567
	 */
568
	public function has_connected_user() {
569
		return (bool) count( $this->get_connected_users() );
0 ignored issues
show
Deprecated Code introduced by
The method Automattic\Jetpack\Conne...::get_connected_users() has been deprecated with message: 9.5 Use Automattic\Jetpack\Connection\Tokens::get_connected_users() instead.

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

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

Loading history...
570
	}
571
572
	/**
573
	 * Returns true if the site has a connected Blog owner (master_user).
574
	 *
575
	 * @access public
576
	 * @since 9.2.0
577
	 *
578
	 * @return bool
579
	 */
580
	public function has_connected_owner() {
581
		return (bool) $this->get_connection_owner_id();
582
	}
583
584
	/**
585
	 * Checks to see if the connection owner of the site is missing.
586
	 *
587
	 * @return bool
588
	 */
589
	public function is_missing_connection_owner() {
590
		$connection_owner = $this->get_connection_owner_id();
591
		if ( ! get_user_by( 'id', $connection_owner ) ) {
592
			return true;
593
		}
594
595
		return false;
596
	}
597
598
	/**
599
	 * Returns true if the user with the specified identifier is connected to
600
	 * WordPress.com.
601
	 *
602
	 * @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...
603
	 * @return bool Boolean is the user connected?
604
	 */
605
	public function is_user_connected( $user_id = false ) {
606
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
607
		if ( ! $user_id ) {
608
			return false;
609
		}
610
611
		return (bool) Tokens::get_access_token( $user_id );
612
	}
613
614
	/**
615
	 * Returns the local user ID of the connection owner.
616
	 *
617
	 * @return bool|int Returns the ID of the connection owner or False if no connection owner found.
618
	 */
619
	public function get_connection_owner_id() {
620
		$owner = $this->get_connection_owner();
621
		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...
622
	}
623
624
	/**
625
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
626
	 * Able to select by specific capability.
627
	 *
628
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens::get_connected_users() instead.
629
	 *
630
	 * @param string $capability The capability of the user.
631
	 * @return array Array of WP_User objects if found.
632
	 */
633
	public function get_connected_users( $capability = 'any' ) {
634
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens::get_connected_users' );
635
		return Tokens::get_connected_users( $capability );
636
	}
637
638
	/**
639
	 * Get the wpcom user data of the current|specified connected user.
640
	 *
641
	 * @todo Refactor to properly load the XMLRPC client independently.
642
	 *
643
	 * @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...
644
	 * @return Object the user object.
645
	 */
646
	public function get_connected_user_data( $user_id = null ) {
647
		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...
648
			$user_id = get_current_user_id();
649
		}
650
651
		$transient_key    = "jetpack_connected_user_data_$user_id";
652
		$cached_user_data = get_transient( $transient_key );
653
654
		if ( $cached_user_data ) {
655
			return $cached_user_data;
656
		}
657
658
		$xml = new \Jetpack_IXR_Client(
659
			array(
660
				'user_id' => $user_id,
661
			)
662
		);
663
		$xml->query( 'wpcom.getUser' );
664
		if ( ! $xml->isError() ) {
665
			$user_data = $xml->getResponse();
666
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
667
			return $user_data;
668
		}
669
670
		return false;
671
	}
672
673
	/**
674
	 * Returns a user object of the connection owner.
675
	 *
676
	 * @return WP_User|false False if no connection owner found.
677
	 */
678
	public function get_connection_owner() {
679
680
		$user_id = \Jetpack_Options::get_option( 'master_user' );
681
682
		if ( ! $user_id ) {
683
			return false;
684
		}
685
686
		// Make sure user is connected.
687
		$user_token = Tokens::get_access_token( $user_id );
688
689
		$connection_owner = false;
690
691
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
692
			$connection_owner = get_userdata( $user_token->external_user_id );
693
		}
694
695
		return $connection_owner;
696
	}
697
698
	/**
699
	 * Returns true if the provided user is the Jetpack connection owner.
700
	 * If user ID is not specified, the current user will be used.
701
	 *
702
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
703
	 * @return Boolean True the user the connection owner, false otherwise.
704
	 */
705
	public function is_connection_owner( $user_id = false ) {
706
		if ( ! $user_id ) {
707
			$user_id = get_current_user_id();
708
		}
709
710
		return ( (int) $user_id ) === $this->get_connection_owner_id();
711
	}
712
713
	/**
714
	 * Connects the user with a specified ID to a WordPress.com user using the
715
	 * remote login flow.
716
	 *
717
	 * @access public
718
	 *
719
	 * @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...
720
	 * @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...
721
	 *                              admin_url().
722
	 * @return WP_Error only in case of a failed user lookup.
723
	 */
724
	public function connect_user( $user_id = null, $redirect_url = null ) {
725
		$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...
726
		if ( null === $user_id ) {
727
			$user = wp_get_current_user();
728
		} else {
729
			$user = get_user_by( 'ID', $user_id );
730
		}
731
732
		if ( empty( $user ) ) {
733
			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...
734
		}
735
736
		if ( null === $redirect_url ) {
737
			$redirect_url = admin_url();
738
		}
739
740
		// Using wp_redirect intentionally because we're redirecting outside.
741
		wp_redirect( $this->get_authorization_url( $user, $redirect_url ) ); // phpcs:ignore WordPress.Security.SafeRedirect
742
		exit();
743
	}
744
745
	/**
746
	 * Unlinks the current user from the linked WordPress.com user.
747
	 *
748
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens::disconnect_user() instead.
749
	 *
750
	 * @access public
751
	 * @static
752
	 *
753
	 * @todo Refactor to properly load the XMLRPC client independently.
754
	 *
755
	 * @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...
756
	 * @param bool    $can_overwrite_primary_user Allow for the primary user to be disconnected.
757
	 * @return Boolean Whether the disconnection of the user was successful.
758
	 */
759
	public static function disconnect_user( $user_id = null, $can_overwrite_primary_user = false ) {
760
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens::disconnect_user' );
761
		return Tokens::disconnect_user( $user_id, $can_overwrite_primary_user );
762
	}
763
764
	/**
765
	 * Returns the requested Jetpack API URL.
766
	 *
767
	 * @param String $relative_url the relative API path.
768
	 * @return String API URL.
769
	 */
770
	public function api_url( $relative_url ) {
771
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
772
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
773
774
		/**
775
		 * Filters whether the connection manager should use the iframe authorization
776
		 * flow instead of the regular redirect-based flow.
777
		 *
778
		 * @since 8.3.0
779
		 *
780
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
781
		 */
782
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
783
784
		// Do not modify anything that is not related to authorize requests.
785
		if ( 'authorize' === $relative_url && $iframe_flow ) {
786
			$relative_url = 'authorize_iframe';
787
		}
788
789
		/**
790
		 * Filters the API URL that Jetpack uses for server communication.
791
		 *
792
		 * @since 8.0.0
793
		 *
794
		 * @param String $url the generated URL.
795
		 * @param String $relative_url the relative URL that was passed as an argument.
796
		 * @param String $api_base the API base string that is being used.
797
		 * @param String $api_version the API version string that is being used.
798
		 */
799
		return apply_filters(
800
			'jetpack_api_url',
801
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
802
			$relative_url,
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $relative_url.

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

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

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

Loading history...
803
			$api_base,
804
			$api_version
805
		);
806
	}
807
808
	/**
809
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
810
	 *
811
	 * @return String XMLRPC API URL.
812
	 */
813
	public function xmlrpc_api_url() {
814
		$base = preg_replace(
815
			'#(https?://[^?/]+)(/?.*)?$#',
816
			'\\1',
817
			Constants::get_constant( 'JETPACK__API_BASE' )
818
		);
819
		return untrailingslashit( $base ) . '/xmlrpc.php';
820
	}
821
822
	/**
823
	 * Attempts Jetpack registration which sets up the site for connection. Should
824
	 * remain public because the call to action comes from the current site, not from
825
	 * WordPress.com.
826
	 *
827
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
828
	 * @return true|WP_Error The error object.
829
	 */
830
	public function register( $api_endpoint = 'register' ) {
831
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
832
		$secrets = Secrets::generate( 'register', get_current_user_id(), 600 );
833
834
		if ( false === $secrets ) {
835
			return new WP_Error( 'cannot_save_secrets', __( 'Jetpack experienced an issue trying to save options (cannot_save_secrets). We suggest that you contact your hosting provider, and ask them for help checking that the options table is writable on your site.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_save_secrets'.

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

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

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

Loading history...
836
		}
837
838
		if (
839
			empty( $secrets['secret_1'] ) ||
840
			empty( $secrets['secret_2'] ) ||
841
			empty( $secrets['exp'] )
842
		) {
843
			return new \WP_Error( 'missing_secrets' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_secrets'.

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

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

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

Loading history...
844
		}
845
846
		// Better to try (and fail) to set a higher timeout than this system
847
		// supports than to have register fail for more users than it should.
848
		$timeout = $this->set_min_time_limit( 60 ) / 2;
849
850
		$gmt_offset = get_option( 'gmt_offset' );
851
		if ( ! $gmt_offset ) {
852
			$gmt_offset = 0;
853
		}
854
855
		$stats_options = get_option( 'stats_options' );
856
		$stats_id      = isset( $stats_options['blog_id'] )
857
			? $stats_options['blog_id']
858
			: null;
859
860
		/**
861
		 * Filters the request body for additional property addition.
862
		 *
863
		 * @since 7.7.0
864
		 *
865
		 * @param array $post_data request data.
866
		 * @param Array $token_data token data.
867
		 */
868
		$body = apply_filters(
869
			'jetpack_register_request_body',
870
			array(
871
				'siteurl'            => site_url(),
872
				'home'               => home_url(),
873
				'gmt_offset'         => $gmt_offset,
874
				'timezone_string'    => (string) get_option( 'timezone_string' ),
875
				'site_name'          => (string) get_option( 'blogname' ),
876
				'secret_1'           => $secrets['secret_1'],
877
				'secret_2'           => $secrets['secret_2'],
878
				'site_lang'          => get_locale(),
879
				'timeout'            => $timeout,
880
				'stats_id'           => $stats_id,
881
				'state'              => get_current_user_id(),
882
				'site_created'       => $this->get_assumed_site_creation_date(),
883
				'jetpack_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
884
				'ABSPATH'            => Constants::get_constant( 'ABSPATH' ),
885
				'current_user_email' => wp_get_current_user()->user_email,
886
				'connect_plugin'     => $this->get_plugin() ? $this->get_plugin()->get_slug() : null,
887
			)
888
		);
889
890
		$args = array(
891
			'method'  => 'POST',
892
			'body'    => $body,
893
			'headers' => array(
894
				'Accept' => 'application/json',
895
			),
896
			'timeout' => $timeout,
897
		);
898
899
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
900
901
		// TODO: fix URLs for bad hosts.
902
		$response = Client::_wp_remote_request(
903
			$this->api_url( $api_endpoint ),
904
			$args,
905
			true
906
		);
907
908
		// Make sure the response is valid and does not contain any Jetpack errors.
909
		$registration_details = $this->validate_remote_register_response( $response );
910
911
		if ( is_wp_error( $registration_details ) ) {
912
			return $registration_details;
913
		} elseif ( ! $registration_details ) {
914
			return new \WP_Error(
915
				'unknown_error',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_error'.

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

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

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

Loading history...
916
				'Unknown error registering your Jetpack site.',
917
				wp_remote_retrieve_response_code( $response )
918
			);
919
		}
920
921
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
922
			return new \WP_Error(
923
				'jetpack_secret',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_secret'.

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

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

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

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