Completed
Push — try/search-config-via-wpadmin ( cb094f...014825 )
by
unknown
74:32 queued 64:33
created

Manager::apply_activation_source_to_args()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15

Duplication

Lines 15
Ratio 100 %

Importance

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

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

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

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

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

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

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

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

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

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

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

An additional type check may prevent trouble.

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

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

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

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

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

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

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

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

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
508
	}
509
510
	/**
511
	 * Obtains an instance of the Tokens class.
512
	 *
513
	 * @return Tokens the Tokens object
514
	 */
515
	public function get_tokens() {
516
		return new Tokens();
517
	}
518
519
	/**
520
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
521
	 *
522
	 * @access public
523
	 * @deprecated 9.2.0 Use is_connected instead
524
	 * @see Manager::is_connected
525
	 *
526
	 * @return bool
527
	 */
528
	public function is_registered() {
529
		_deprecated_function( __METHOD__, 'jetpack-9.2' );
530
		return $this->is_connected();
531
	}
532
533
	/**
534
	 * Returns true if the site has both a token and a blog id, which indicates a site has been connected.
535
	 *
536
	 * @access public
537
	 * @since 9.2.0
538
	 *
539
	 * @return bool
540
	 */
541
	public function is_connected() {
542
		$has_blog_id    = (bool) \Jetpack_Options::get_option( 'id' );
543
		$has_blog_token = (bool) $this->get_tokens()->get_access_token();
544
		return $has_blog_id && $has_blog_token;
545
	}
546
547
	/**
548
	 * Returns true if the site has at least one connected administrator.
549
	 *
550
	 * @access public
551
	 * @since 9.2.0
552
	 *
553
	 * @return bool
554
	 */
555
	public function has_connected_admin() {
556
		return (bool) count( $this->get_connected_users( 'manage_options' ) );
557
	}
558
559
	/**
560
	 * Returns true if the site has any connected user.
561
	 *
562
	 * @access public
563
	 * @since 9.2.0
564
	 *
565
	 * @return bool
566
	 */
567
	public function has_connected_user() {
568
		return (bool) count( $this->get_connected_users() );
569
	}
570
571
	/**
572
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
573
	 * Able to select by specific capability.
574
	 *
575
	 * @param string $capability The capability of the user.
576
	 * @return array Array of WP_User objects if found.
577
	 */
578
	public function get_connected_users( $capability = 'any' ) {
579
		return $this->get_tokens()->get_connected_users( $capability );
580
	}
581
582
	/**
583
	 * Returns true if the site has a connected Blog owner (master_user).
584
	 *
585
	 * @access public
586
	 * @since 9.2.0
587
	 *
588
	 * @return bool
589
	 */
590
	public function has_connected_owner() {
591
		return (bool) $this->get_connection_owner_id();
592
	}
593
594
	/**
595
	 * Returns true if the site is connected only at a site level.
596
	 *
597
	 * Note that we are explicitly checking for the existence of the master_user option in order to account for cases where we don't have any user tokens (user-level connection) but the master_user option is set, which could be the result of a problematic user connection.
598
	 *
599
	 * @access public
600
	 * @since 9.6.0
601
	 * @deprecated 9.8.0
602
	 *
603
	 * @return bool
604
	 */
605
	public function is_userless() {
606
		_deprecated_function( __METHOD__, 'jetpack-9.8.0', 'Automattic\\Jetpack\\Connection\\Manager::is_site_connection' );
607
		return $this->is_site_connection();
608
	}
609
610
	/**
611
	 * Returns true if the site is connected only at a site level.
612
	 *
613
	 * Note that we are explicitly checking for the existence of the master_user option in order to account for cases where we don't have any user tokens (user-level connection) but the master_user option is set, which could be the result of a problematic user connection.
614
	 *
615
	 * @access public
616
	 * @since 9.8.0
617
	 *
618
	 * @return bool
619
	 */
620
	public function is_site_connection() {
621
		return $this->is_connected() && ! $this->has_connected_user() && ! \Jetpack_Options::get_option( 'master_user' );
622
	}
623
624
	/**
625
	 * Checks to see if the connection owner of the site is missing.
626
	 *
627
	 * @return bool
628
	 */
629
	public function is_missing_connection_owner() {
630
		$connection_owner = $this->get_connection_owner_id();
631
		if ( ! get_user_by( 'id', $connection_owner ) ) {
632
			return true;
633
		}
634
635
		return false;
636
	}
637
638
	/**
639
	 * Returns true if the user with the specified identifier is connected to
640
	 * WordPress.com.
641
	 *
642
	 * @param int $user_id the user identifier. Default is the current user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be false|integer?

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

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

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

Loading history...
643
	 * @return bool Boolean is the user connected?
644
	 */
645
	public function is_user_connected( $user_id = false ) {
646
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
647
		if ( ! $user_id ) {
648
			return false;
649
		}
650
651
		return (bool) $this->get_tokens()->get_access_token( $user_id );
652
	}
653
654
	/**
655
	 * Returns the local user ID of the connection owner.
656
	 *
657
	 * @return bool|int Returns the ID of the connection owner or False if no connection owner found.
658
	 */
659
	public function get_connection_owner_id() {
660
		$owner = $this->get_connection_owner();
661
		return $owner instanceof \WP_User ? $owner->ID : false;
0 ignored issues
show
Bug introduced by
The class WP_User does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
662
	}
663
664
	/**
665
	 * Get the wpcom user data of the current|specified connected user.
666
	 *
667
	 * @todo Refactor to properly load the XMLRPC client independently.
668
	 *
669
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
670
	 * @return Object the user object.
671
	 */
672
	public function get_connected_user_data( $user_id = null ) {
673
		if ( ! $user_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user_id of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

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

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
674
			$user_id = get_current_user_id();
675
		}
676
677
		$transient_key    = "jetpack_connected_user_data_$user_id";
678
		$cached_user_data = get_transient( $transient_key );
679
680
		if ( $cached_user_data ) {
681
			return $cached_user_data;
682
		}
683
684
		$xml = new \Jetpack_IXR_Client(
685
			array(
686
				'user_id' => $user_id,
687
			)
688
		);
689
		$xml->query( 'wpcom.getUser' );
690
		if ( ! $xml->isError() ) {
691
			$user_data = $xml->getResponse();
692
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
693
			return $user_data;
694
		}
695
696
		return false;
697
	}
698
699
	/**
700
	 * Returns a user object of the connection owner.
701
	 *
702
	 * @return WP_User|false False if no connection owner found.
703
	 */
704
	public function get_connection_owner() {
705
706
		$user_id = \Jetpack_Options::get_option( 'master_user' );
707
708
		if ( ! $user_id ) {
709
			return false;
710
		}
711
712
		// Make sure user is connected.
713
		$user_token = $this->get_tokens()->get_access_token( $user_id );
714
715
		$connection_owner = false;
716
717
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
718
			$connection_owner = get_userdata( $user_token->external_user_id );
719
		}
720
721
		return $connection_owner;
722
	}
723
724
	/**
725
	 * Returns true if the provided user is the Jetpack connection owner.
726
	 * If user ID is not specified, the current user will be used.
727
	 *
728
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
729
	 * @return Boolean True the user the connection owner, false otherwise.
730
	 */
731
	public function is_connection_owner( $user_id = false ) {
732
		if ( ! $user_id ) {
733
			$user_id = get_current_user_id();
734
		}
735
736
		return ( (int) $user_id ) === $this->get_connection_owner_id();
737
	}
738
739
	/**
740
	 * Connects the user with a specified ID to a WordPress.com user using the
741
	 * remote login flow.
742
	 *
743
	 * @access public
744
	 *
745
	 * @param Integer $user_id (optional) the user identifier, defaults to current user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
746
	 * @param String  $redirect_url the URL to redirect the user to for processing, defaults to
0 ignored issues
show
Documentation introduced by
Should the type for parameter $redirect_url not be string|null?

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

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

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

Loading history...
747
	 *                              admin_url().
748
	 * @return WP_Error only in case of a failed user lookup.
749
	 */
750
	public function connect_user( $user_id = null, $redirect_url = null ) {
751
		$user = null;
0 ignored issues
show
Unused Code introduced by
$user is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
752
		if ( null === $user_id ) {
753
			$user = wp_get_current_user();
754
		} else {
755
			$user = get_user_by( 'ID', $user_id );
756
		}
757
758
		if ( empty( $user ) ) {
759
			return new \WP_Error( 'user_not_found', 'Attempting to connect a non-existent user.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_not_found'.

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

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

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

Loading history...
760
		}
761
762
		if ( null === $redirect_url ) {
763
			$redirect_url = admin_url();
764
		}
765
766
		// Using wp_redirect intentionally because we're redirecting outside.
767
		wp_redirect( $this->get_authorization_url( $user, $redirect_url ) ); // phpcs:ignore WordPress.Security.SafeRedirect
768
		exit();
769
	}
770
771
	/**
772
	 * Unlinks the current user from the linked WordPress.com user.
773
	 *
774
	 * @access public
775
	 * @static
776
	 *
777
	 * @todo Refactor to properly load the XMLRPC client independently.
778
	 *
779
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

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

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

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

Loading history...
1675
				'jp_version'            => Constants::get_constant( 'JETPACK__VERSION' ),
1676
				'auth_type'             => $auth_type,
1677
				'secret'                => $secrets['secret_1'],
1678
				'blogname'              => get_option( 'blogname' ),
1679
				'site_url'              => site_url(),
1680
				'home_url'              => home_url(),
1681
				'site_icon'             => get_site_icon_url(),
1682
				'site_lang'             => get_locale(),
1683
				'site_created'          => $this->get_assumed_site_creation_date(),
1684
				'allow_site_connection' => ! $this->has_connected_owner(),
1685
			)
1686
		);
1687
1688
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1689
1690
		$api_url = $this->api_url( 'authorize' );
1691
1692
		return add_query_arg( $body, $api_url );
1693
	}
1694
1695
	/**
1696
	 * Authorizes the user by obtaining and storing the user token.
1697
	 *
1698
	 * @param array $data The request data.
1699
	 * @return string|\WP_Error Returns a string on success.
1700
	 *                          Returns a \WP_Error on failure.
1701
	 */
1702
	public function authorize( $data = array() ) {
1703
		/**
1704
		 * Action fired when user authorization starts.
1705
		 *
1706
		 * @since 8.0.0
1707
		 */
1708
		do_action( 'jetpack_authorize_starting' );
1709
1710
		$roles = new Roles();
1711
		$role  = $roles->translate_current_user_to_role();
1712
1713
		if ( ! $role ) {
1714
			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...
1715
		}
1716
1717
		$cap = $roles->translate_role_to_cap( $role );
1718
		if ( ! $cap ) {
1719
			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...
1720
		}
1721
1722
		if ( ! empty( $data['error'] ) ) {
1723
			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...
1724
		}
1725
1726
		if ( ! isset( $data['state'] ) ) {
1727
			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...
1728
		}
1729
1730
		if ( ! ctype_digit( $data['state'] ) ) {
1731
			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...
1732
		}
1733
1734
		$current_user_id = get_current_user_id();
1735
		if ( $current_user_id !== (int) $data['state'] ) {
1736
			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...
1737
		}
1738
1739
		if ( empty( $data['code'] ) ) {
1740
			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...
1741
		}
1742
1743
		$token = $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1744
1745 View Code Duplication
		if ( is_wp_error( $token ) ) {
1746
			$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...
1747
			if ( empty( $code ) ) {
1748
				$code = 'invalid_token';
1749
			}
1750
			return new \WP_Error( $code, $token->get_error_message(), 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $code.

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

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

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

Loading history...
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

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

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

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

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

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

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

Loading history...
2148
		}
2149
2150
		$url     = sprintf(
2151
			'%s/%s/v%s/%s',
2152
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
2153
			'wpcom',
2154
			'2',
2155
			'sites/' . $blog_id . '/jetpack-refresh-blog-token'
2156
		);
2157
		$method  = 'POST';
2158
		$user_id = get_current_user_id();
2159
2160
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2161
2162
		if ( is_wp_error( $response ) ) {
2163
			return new WP_Error( 'refresh_blog_token_http_request_failed', $response->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

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

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

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

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

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

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

Loading history...
2164
		}
2165
2166
		$code   = wp_remote_retrieve_response_code( $response );
2167
		$entity = wp_remote_retrieve_body( $response );
2168
2169
		if ( $entity ) {
2170
			$json = json_decode( $entity );
2171
		} else {
2172
			$json = false;
2173
		}
2174
2175 View Code Duplication
		if ( 200 !== $code ) {
2176
			if ( empty( $json->code ) ) {
2177
				return new WP_Error( 'unknown', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown'.

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

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

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

Loading history...
2178
			}
2179
2180
			/* translators: Error description string. */
2181
			$error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->message ) : '';
2182
2183
			return new WP_Error( (string) $json->code, $error_description, $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with (string) $json->code.

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

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

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

Loading history...
2184
		}
2185
2186
		if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
2187
			return new WP_Error( 'jetpack_secret', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'jetpack_secret'.

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

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

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

Loading history...
2188
		}
2189
2190
		return $this->get_tokens()->update_blog_token( (string) $json->jetpack_secret );
2191
	}
2192
2193
	/**
2194
	 * Disconnect the user from WP.com, and initiate the reconnect process.
2195
	 *
2196
	 * @return bool
2197
	 */
2198
	public function refresh_user_token() {
2199
		( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2200
		$this->disconnect_user( null, true );
2201
		return true;
2202
	}
2203
2204
	/**
2205
	 * Fetches a signed token.
2206
	 *
2207
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_signed_token() instead.
2208
	 *
2209
	 * @param object $token the token.
2210
	 * @return WP_Error|string a signed token
2211
	 */
2212
	public function get_signed_token( $token ) {
2213
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_signed_token' );
2214
		return $this->get_tokens()->get_signed_token( $token );
2215
	}
2216
2217
	/**
2218
	 * If the site-level connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2219
	 *
2220
	 * @param array $stats The Heartbeat stats array.
2221
	 * @return array $stats
2222
	 */
2223
	public function add_stats_to_heartbeat( $stats ) {
2224
2225
		if ( ! $this->is_connected() ) {
2226
			return $stats;
2227
		}
2228
2229
		$active_plugins_using_connection = Plugin_Storage::get_all();
2230
		foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
2231
			if ( 'jetpack' !== $plugin_slug ) {
2232
				$stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2233
				$stats[ $stats_group ][] = $plugin_slug;
2234
			}
2235
		}
2236
		return $stats;
2237
	}
2238
}
2239