Completed
Push — add/missing_connection_owner_h... ( 083f52 )
by
unknown
72:06 queued 63:43
created

Manager   F

Complexity

Total Complexity 347

Size/Duplication

Total Lines 2787
Duplicated Lines 4.95 %

Coupling/Cohesion

Components 2
Dependencies 17

Importance

Changes 0
Metric Value
dl 138
loc 2787
rs 0.8
c 0
b 0
f 0
wmc 347
lcom 2
cbo 17

76 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 3
A configure() 0 37 3
C setup_xmlrpc_handlers() 0 72 11
A initialize_rest_api_registration_connector() 0 3 1
A alternate_xmlrpc() 0 24 1
A remove_non_jetpack_xmlrpc_methods() 0 11 3
A require_jetpack_authentication() 0 11 2
A authenticate_jetpack() 0 23 5
A verify_xml_rpc_signature() 0 21 4
F internal_verify_xml_rpc_signature() 0 157 28
A is_active() 0 6 2
A is_registered() 0 4 1
A is_connected() 0 5 2
A has_connected_admin() 0 3 1
A has_connected_user() 0 3 1
A get_connected_user_data() 26 26 4
A get_connection_owner() 0 19 5
A is_connection_owner() 0 7 2
A connect_user() 0 20 4
B disconnect_user() 0 38 6
A api_url() 0 37 3
A xmlrpc_api_url() 0 8 1
C register() 0 142 14
C validate_remote_register_response() 8 69 13
A add_nonce() 0 38 3
A clean_nonces() 0 21 4
B jetpack_connection_custom_caps() 0 31 7
A get_max_execution_time() 0 9 2
A set_min_time_limit() 8 8 2
A get_assumed_site_creation_date() 0 39 3
A apply_activation_source_to_args() 15 15 3
A get_secret_callable() 0 12 2
A secret_callable_method() 0 3 1
A generate_secrets() 0 32 5
A get_secrets() 0 18 3
A delete_secrets() 0 11 2
A delete_all_connection_tokens() 3 37 5
A disconnect_site_wpcom() 3 20 5
A remove_connection() 0 7 1
A reconnect() 0 8 1
B restore() 0 20 6
A can_restore() 0 20 5
B validate_tokens() 0 30 7
A handle_registration() 0 8 2
D verify_secrets() 0 136 15
A handle_authorization() 0 3 1
F get_token() 10 134 22
A increase_timeout() 0 3 1
B get_authorization_url() 0 86 2
C authorize() 7 93 12
A disconnect_site() 0 3 1
A sha1_base64() 0 3 1
B is_usable_domain() 39 87 7
F get_access_token() 4 99 31
A xmlrpc_methods() 0 4 1
A reset_raw_post_data() 0 3 1
A public_xmlrpc_methods() 0 6 2
A jetpack_get_options() 0 41 3
A xmlrpc_options() 0 18 2
A reset_saved_auth_state() 0 3 1
A sign_role() 0 16 5
A set_plugin_instance() 0 5 1
A get_plugin() 0 3 1
A get_connected_plugins() 0 9 2
A disable_plugin() 0 7 2
A enable_plugin() 0 7 2
A is_plugin_enabled() 0 7 2
B refresh_blog_token() 10 50 9
A refresh_user_token() 0 7 1
B get_signed_token() 5 48 5
A has_connected_owner() 0 3 1
A is_missing_connection_owner() 0 3 1
A is_user_connected() 0 8 3
A get_connection_owner_id() 0 4 2
B get_connected_users() 0 25 8
B add_stats_to_heartbeat() 0 32 10

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Manager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Manager, and based on these observations, apply Extract Interface, too.

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
529
	}
530
531
	/**
532
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
533
	 *
534
	 * @access public
535
	 * @deprecated 9.2.0 Use is_connected instead
536
	 * @see Manager::is_connected
537
	 *
538
	 * @return bool
539
	 */
540
	public function is_registered() {
541
		_deprecated_function( __METHOD__, 'jetpack-9.2' );
542
		return $this->is_connected();
543
	}
544
545
	/**
546
	 * Returns true if the site has both a token and a blog id, which indicates a site has been connected.
547
	 *
548
	 * @access public
549
	 * @since 9.2.0
550
	 *
551
	 * @return bool
552
	 */
553
	public function is_connected() {
554
		$has_blog_id    = (bool) \Jetpack_Options::get_option( 'id' );
555
		$has_blog_token = (bool) $this->get_access_token( false );
556
		return $has_blog_id && $has_blog_token;
557
	}
558
559
	/**
560
	 * Returns true if the site has at least one connected administrator.
561
	 *
562
	 * @access public
563
	 * @since 9.2.0
564
	 *
565
	 * @return bool
566
	 */
567
	public function has_connected_admin() {
568
		return (bool) count( $this->get_connected_users( 'manage_options' ) );
569
	}
570
571
	/**
572
	 * Returns true if the site has any connected user.
573
	 *
574
	 * @access public
575
	 * @since 9.2.0
576
	 *
577
	 * @return bool
578
	 */
579
	public function has_connected_user() {
580
		return (bool) count( $this->get_connected_users() );
581
	}
582
583
	/**
584
	 * Returns true if the site has a connected Blog owner (master_user).
585
	 *
586
	 * @access public
587
	 * @since 9.2.0
588
	 *
589
	 * @return bool
590
	 */
591
	public function has_connected_owner() {
592
		return (bool) $this->get_connection_owner_id();
593
	}
594
595
	/**
596
	 * Checks to see if the connection owner of the site is missing.
597
	 *
598
	 * @return bool
599
	 */
600
	public function is_missing_connection_owner() {
601
		return ! $this->has_connected_owner();
602
	}
603
604
	/**
605
	 * Returns true if the user with the specified identifier is connected to
606
	 * WordPress.com.
607
	 *
608
	 * @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...
609
	 * @return bool Boolean is the user connected?
610
	 */
611
	public function is_user_connected( $user_id = false ) {
612
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
613
		if ( ! $user_id ) {
614
			return false;
615
		}
616
617
		return (bool) $this->get_access_token( $user_id );
618
	}
619
620
	/**
621
	 * Returns the local user ID of the connection owner.
622
	 *
623
	 * @return bool|int Returns the ID of the connection owner or False if no connection owner found.
624
	 */
625
	public function get_connection_owner_id() {
626
		$owner = $this->get_connection_owner();
627
		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...
628
	}
629
630
	/**
631
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
632
	 * Able to select by specific capability.
633
	 *
634
	 * @param string $capability The capability of the user.
635
	 * @return array Array of WP_User objects if found.
636
	 */
637
	public function get_connected_users( $capability = 'any' ) {
638
		$connected_users = array();
639
		$user_tokens     = \Jetpack_Options::get_option( 'user_tokens' );
640
641
		if ( ! is_array( $user_tokens ) || empty( $user_tokens ) ) {
642
			return $connected_users;
643
		}
644
		$connected_user_ids = array_keys( $user_tokens );
645
646
		if ( ! empty( $connected_user_ids ) ) {
647
			foreach ( $connected_user_ids as $id ) {
648
				// Check for capability.
649
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
650
					continue;
651
				}
652
653
				$user_data = get_userdata( $id );
654
				if ( $user_data instanceof \WP_User ) {
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...
655
					$connected_users[] = $user_data;
656
				}
657
			}
658
		}
659
660
		return $connected_users;
661
	}
662
663
	/**
664
	 * Get the wpcom user data of the current|specified connected user.
665
	 *
666
	 * @todo Refactor to properly load the XMLRPC client independently.
667
	 *
668
	 * @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...
669
	 * @return Object the user object.
670
	 */
671 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
672
		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...
673
			$user_id = get_current_user_id();
674
		}
675
676
		$transient_key    = "jetpack_connected_user_data_$user_id";
677
		$cached_user_data = get_transient( $transient_key );
678
679
		if ( $cached_user_data ) {
680
			return $cached_user_data;
681
		}
682
683
		$xml = new \Jetpack_IXR_Client(
684
			array(
685
				'user_id' => $user_id,
686
			)
687
		);
688
		$xml->query( 'wpcom.getUser' );
689
		if ( ! $xml->isError() ) {
690
			$user_data = $xml->getResponse();
691
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
692
			return $user_data;
693
		}
694
695
		return false;
696
	}
697
698
	/**
699
	 * Returns a user object of the connection owner.
700
	 *
701
	 * @return WP_User|false False if no connection owner found.
702
	 */
703
	public function get_connection_owner() {
704
705
		$user_id = \Jetpack_Options::get_option( 'master_user' );
706
707
		if ( ! $user_id ) {
708
			return false;
709
		}
710
711
		// Make sure user is connected.
712
		$user_token = $this->get_access_token( $user_id );
713
714
		$connection_owner = false;
715
716
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
717
			$connection_owner = get_userdata( $user_token->external_user_id );
718
		}
719
720
		return $connection_owner;
721
	}
722
723
	/**
724
	 * Returns true if the provided user is the Jetpack connection owner.
725
	 * If user ID is not specified, the current user will be used.
726
	 *
727
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
728
	 * @return Boolean True the user the connection owner, false otherwise.
729
	 */
730
	public function is_connection_owner( $user_id = false ) {
731
		if ( ! $user_id ) {
732
			$user_id = get_current_user_id();
733
		}
734
735
		return ( (int) $user_id ) === $this->get_connection_owner_id();
736
	}
737
738
	/**
739
	 * Connects the user with a specified ID to a WordPress.com user using the
740
	 * remote login flow.
741
	 *
742
	 * @access public
743
	 *
744
	 * @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...
745
	 * @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...
746
	 *                              admin_url().
747
	 * @return WP_Error only in case of a failed user lookup.
748
	 */
749
	public function connect_user( $user_id = null, $redirect_url = null ) {
750
		$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...
751
		if ( null === $user_id ) {
752
			$user = wp_get_current_user();
753
		} else {
754
			$user = get_user_by( 'ID', $user_id );
755
		}
756
757
		if ( empty( $user ) ) {
758
			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...
759
		}
760
761
		if ( null === $redirect_url ) {
762
			$redirect_url = admin_url();
0 ignored issues
show
Unused Code introduced by
$redirect_url 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...
763
		}
764
765
		// Using wp_redirect intentionally because we're redirecting outside.
766
		wp_redirect( $this->get_authorization_url( $user ) ); // phpcs:ignore WordPress.Security.SafeRedirect
767
		exit();
768
	}
769
770
	/**
771
	 * Unlinks the current user from the linked WordPress.com user.
772
	 *
773
	 * @access public
774
	 * @static
775
	 *
776
	 * @todo Refactor to properly load the XMLRPC client independently.
777
	 *
778
	 * @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...
779
	 * @param bool    $can_overwrite_primary_user Allow for the primary user to be disconnected.
780
	 * @return Boolean Whether the disconnection of the user was successful.
781
	 */
782
	public static function disconnect_user( $user_id = null, $can_overwrite_primary_user = false ) {
783
		$tokens = Jetpack_Options::get_option( 'user_tokens' );
784
		if ( ! $tokens ) {
785
			return false;
786
		}
787
788
		$user_id = empty( $user_id ) ? get_current_user_id() : (int) $user_id;
789
790
		if ( Jetpack_Options::get_option( 'master_user' ) === $user_id && ! $can_overwrite_primary_user ) {
791
			return false;
792
		}
793
794
		if ( ! isset( $tokens[ $user_id ] ) ) {
795
			return false;
796
		}
797
798
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
799
		$xml->query( 'jetpack.unlink_user', $user_id );
800
801
		unset( $tokens[ $user_id ] );
802
803
		Jetpack_Options::update_option( 'user_tokens', $tokens );
804
805
		// Delete cached connected user data.
806
		$transient_key = "jetpack_connected_user_data_$user_id";
807
		delete_transient( $transient_key );
808
809
		/**
810
		 * Fires after the current user has been unlinked from WordPress.com.
811
		 *
812
		 * @since 4.1.0
813
		 *
814
		 * @param int $user_id The current user's ID.
815
		 */
816
		do_action( 'jetpack_unlinked_user', $user_id );
817
818
		return true;
819
	}
820
821
	/**
822
	 * Returns the requested Jetpack API URL.
823
	 *
824
	 * @param String $relative_url the relative API path.
825
	 * @return String API URL.
826
	 */
827
	public function api_url( $relative_url ) {
828
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
829
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
830
831
		/**
832
		 * Filters whether the connection manager should use the iframe authorization
833
		 * flow instead of the regular redirect-based flow.
834
		 *
835
		 * @since 8.3.0
836
		 *
837
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
838
		 */
839
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
840
841
		// Do not modify anything that is not related to authorize requests.
842
		if ( 'authorize' === $relative_url && $iframe_flow ) {
843
			$relative_url = 'authorize_iframe';
844
		}
845
846
		/**
847
		 * Filters the API URL that Jetpack uses for server communication.
848
		 *
849
		 * @since 8.0.0
850
		 *
851
		 * @param String $url the generated URL.
852
		 * @param String $relative_url the relative URL that was passed as an argument.
853
		 * @param String $api_base the API base string that is being used.
854
		 * @param String $api_version the API version string that is being used.
855
		 */
856
		return apply_filters(
857
			'jetpack_api_url',
858
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
859
			$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...
860
			$api_base,
861
			$api_version
862
		);
863
	}
864
865
	/**
866
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
867
	 *
868
	 * @return String XMLRPC API URL.
869
	 */
870
	public function xmlrpc_api_url() {
871
		$base = preg_replace(
872
			'#(https?://[^?/]+)(/?.*)?$#',
873
			'\\1',
874
			Constants::get_constant( 'JETPACK__API_BASE' )
875
		);
876
		return untrailingslashit( $base ) . '/xmlrpc.php';
877
	}
878
879
	/**
880
	 * Attempts Jetpack registration which sets up the site for connection. Should
881
	 * remain public because the call to action comes from the current site, not from
882
	 * WordPress.com.
883
	 *
884
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
885
	 * @return true|WP_Error The error object.
886
	 */
887
	public function register( $api_endpoint = 'register' ) {
888
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
889
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
890
891
		if ( false === $secrets ) {
892
			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...
893
		}
894
895
		if (
896
			empty( $secrets['secret_1'] ) ||
897
			empty( $secrets['secret_2'] ) ||
898
			empty( $secrets['exp'] )
899
		) {
900
			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...
901
		}
902
903
		// Better to try (and fail) to set a higher timeout than this system
904
		// supports than to have register fail for more users than it should.
905
		$timeout = $this->set_min_time_limit( 60 ) / 2;
906
907
		$gmt_offset = get_option( 'gmt_offset' );
908
		if ( ! $gmt_offset ) {
909
			$gmt_offset = 0;
910
		}
911
912
		$stats_options = get_option( 'stats_options' );
913
		$stats_id      = isset( $stats_options['blog_id'] )
914
			? $stats_options['blog_id']
915
			: null;
916
917
		/**
918
		 * Filters the request body for additional property addition.
919
		 *
920
		 * @since 7.7.0
921
		 *
922
		 * @param array $post_data request data.
923
		 * @param Array $token_data token data.
924
		 */
925
		$body = apply_filters(
926
			'jetpack_register_request_body',
927
			array(
928
				'siteurl'            => site_url(),
929
				'home'               => home_url(),
930
				'gmt_offset'         => $gmt_offset,
931
				'timezone_string'    => (string) get_option( 'timezone_string' ),
932
				'site_name'          => (string) get_option( 'blogname' ),
933
				'secret_1'           => $secrets['secret_1'],
934
				'secret_2'           => $secrets['secret_2'],
935
				'site_lang'          => get_locale(),
936
				'timeout'            => $timeout,
937
				'stats_id'           => $stats_id,
938
				'state'              => get_current_user_id(),
939
				'site_created'       => $this->get_assumed_site_creation_date(),
940
				'jetpack_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
941
				'ABSPATH'            => Constants::get_constant( 'ABSPATH' ),
942
				'current_user_email' => wp_get_current_user()->user_email,
943
				'connect_plugin'     => $this->get_plugin() ? $this->get_plugin()->get_slug() : null,
944
			)
945
		);
946
947
		$args = array(
948
			'method'  => 'POST',
949
			'body'    => $body,
950
			'headers' => array(
951
				'Accept' => 'application/json',
952
			),
953
			'timeout' => $timeout,
954
		);
955
956
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
957
958
		// TODO: fix URLs for bad hosts.
959
		$response = Client::_wp_remote_request(
960
			$this->api_url( $api_endpoint ),
961
			$args,
962
			true
963
		);
964
965
		// Make sure the response is valid and does not contain any Jetpack errors.
966
		$registration_details = $this->validate_remote_register_response( $response );
967
968
		if ( is_wp_error( $registration_details ) ) {
969
			return $registration_details;
970
		} elseif ( ! $registration_details ) {
971
			return new \WP_Error(
972
				'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...
973
				'Unknown error registering your Jetpack site.',
974
				wp_remote_retrieve_response_code( $response )
975
			);
976
		}
977
978
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
979
			return new \WP_Error(
980
				'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...
981
				'Unable to validate registration of your Jetpack site.',
982
				wp_remote_retrieve_response_code( $response )
983
			);
984
		}
985
986
		if ( isset( $registration_details->jetpack_public ) ) {
987
			$jetpack_public = (int) $registration_details->jetpack_public;
988
		} else {
989
			$jetpack_public = false;
990
		}
991
992
		\Jetpack_Options::update_options(
993
			array(
994
				'id'         => (int) $registration_details->jetpack_id,
995
				'blog_token' => (string) $registration_details->jetpack_secret,
996
				'public'     => $jetpack_public,
997
			)
998
		);
999
1000
		/**
1001
		 * Fires when a site is registered on WordPress.com.
1002
		 *
1003
		 * @since 3.7.0
1004
		 *
1005
		 * @param int $json->jetpack_id Jetpack Blog ID.
1006
		 * @param string $json->jetpack_secret Jetpack Blog Token.
1007
		 * @param int|bool $jetpack_public Is the site public.
1008
		 */
1009
		do_action(
1010
			'jetpack_site_registered',
1011
			$registration_details->jetpack_id,
1012
			$registration_details->jetpack_secret,
1013
			$jetpack_public
1014
		);
1015
1016
		if ( isset( $registration_details->token ) ) {
1017
			/**
1018
			 * Fires when a user token is sent along with the registration data.
1019
			 *
1020
			 * @since 7.6.0
1021
			 *
1022
			 * @param object $token the administrator token for the newly registered site.
1023
			 */
1024
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
1025
		}
1026
1027
		return true;
1028
	}
1029
1030
	/**
1031
	 * Takes the response from the Jetpack register new site endpoint and
1032
	 * verifies it worked properly.
1033
	 *
1034
	 * @since 2.6
1035
	 *
1036
	 * @param Mixed $response the response object, or the error object.
1037
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
1038
	 **/
1039
	protected function validate_remote_register_response( $response ) {
1040
		if ( is_wp_error( $response ) ) {
1041
			return new \WP_Error(
1042
				'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...
1043
				$response->get_error_message()
1044
			);
1045
		}
1046
1047
		$code   = wp_remote_retrieve_response_code( $response );
1048
		$entity = wp_remote_retrieve_body( $response );
1049
1050
		if ( $entity ) {
1051
			$registration_response = json_decode( $entity );
1052
		} else {
1053
			$registration_response = false;
1054
		}
1055
1056
		$code_type = (int) ( $code / 100 );
1057
		if ( 5 === $code_type ) {
1058
			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...
1059
		} elseif ( 408 === $code ) {
1060
			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...
1061
		} elseif ( ! empty( $registration_response->error ) ) {
1062
			if (
1063
				'xml_rpc-32700' === $registration_response->error
1064
				&& ! function_exists( 'xml_parser_create' )
1065
			) {
1066
				$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' );
1067
			} else {
1068
				$error_description = isset( $registration_response->error_description )
1069
					? (string) $registration_response->error_description
1070
					: '';
1071
			}
1072
1073
			return new \WP_Error(
1074
				(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...
1075
				$error_description,
1076
				$code
1077
			);
1078
		} elseif ( 200 !== $code ) {
1079
			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...
1080
		}
1081
1082
		// Jetpack ID error block.
1083
		if ( empty( $registration_response->jetpack_id ) ) {
1084
			return new \WP_Error(
1085
				'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...
1086
				/* translators: %s is an error message string */
1087
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1088
				$entity
1089
			);
1090
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1091
			return new \WP_Error(
1092
				'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...
1093
				/* translators: %s is an error message string */
1094
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1095
				$entity
1096
			);
1097 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1098
			return new \WP_Error(
1099
				'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...
1100
				/* translators: %s is an error message string */
1101
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1102
				$entity
1103
			);
1104
		}
1105
1106
		return $registration_response;
1107
	}
1108
1109
	/**
1110
	 * Adds a used nonce to a list of known nonces.
1111
	 *
1112
	 * @param int    $timestamp the current request timestamp.
1113
	 * @param string $nonce the nonce value.
1114
	 * @return bool whether the nonce is unique or not.
1115
	 */
1116
	public function add_nonce( $timestamp, $nonce ) {
1117
		global $wpdb;
1118
		static $nonces_used_this_request = array();
1119
1120
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
1121
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
1122
		}
1123
1124
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
1125
		$timestamp = (int) $timestamp;
1126
		$nonce     = esc_sql( $nonce );
1127
1128
		// Raw query so we can avoid races: add_option will also update.
1129
		$show_errors = $wpdb->show_errors( false );
1130
1131
		$old_nonce = $wpdb->get_row(
1132
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1133
		);
1134
1135
		if ( is_null( $old_nonce ) ) {
1136
			$return = $wpdb->query(
1137
				$wpdb->prepare(
1138
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1139
					"jetpack_nonce_{$timestamp}_{$nonce}",
1140
					time(),
1141
					'no'
1142
				)
1143
			);
1144
		} else {
1145
			$return = false;
1146
		}
1147
1148
		$wpdb->show_errors( $show_errors );
1149
1150
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1151
1152
		return $return;
1153
	}
1154
1155
	/**
1156
	 * Cleans nonces that were saved when calling ::add_nonce.
1157
	 *
1158
	 * @todo Properly prepare the query before executing it.
1159
	 *
1160
	 * @param bool $all whether to clean even non-expired nonces.
1161
	 */
1162
	public function clean_nonces( $all = false ) {
1163
		global $wpdb;
1164
1165
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1166
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1167
1168
		if ( true !== $all ) {
1169
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1170
			$sql_args[] = time() - 3600;
1171
		}
1172
1173
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1174
1175
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1176
1177
		for ( $i = 0; $i < 1000; $i++ ) {
1178
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1179
				break;
1180
			}
1181
		}
1182
	}
1183
1184
	/**
1185
	 * Sets the Connection custom capabilities.
1186
	 *
1187
	 * @param string[] $caps    Array of the user's capabilities.
1188
	 * @param string   $cap     Capability name.
1189
	 * @param int      $user_id The user ID.
1190
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1191
	 */
1192
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1193
		$is_offline_mode = ( new Status() )->is_offline_mode();
1194
		switch ( $cap ) {
1195
			case 'jetpack_connect':
1196
			case 'jetpack_reconnect':
1197
				if ( $is_offline_mode ) {
1198
					$caps = array( 'do_not_allow' );
1199
					break;
1200
				}
1201
				// Pass through. If it's not offline mode, these should match disconnect.
1202
				// Let users disconnect if it's offline mode, just in case things glitch.
1203
			case 'jetpack_disconnect':
1204
				/**
1205
				 * Filters the jetpack_disconnect capability.
1206
				 *
1207
				 * @since 8.7.0
1208
				 *
1209
				 * @param array An array containing the capability name.
1210
				 */
1211
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1212
				break;
1213
			case 'jetpack_connect_user':
1214
				if ( $is_offline_mode ) {
1215
					$caps = array( 'do_not_allow' );
1216
					break;
1217
				}
1218
				$caps = array( 'read' );
1219
				break;
1220
		}
1221
		return $caps;
1222
	}
1223
1224
	/**
1225
	 * Builds the timeout limit for queries talking with the wpcom servers.
1226
	 *
1227
	 * Based on local php max_execution_time in php.ini
1228
	 *
1229
	 * @since 5.4
1230
	 * @return int
1231
	 **/
1232
	public function get_max_execution_time() {
1233
		$timeout = (int) ini_get( 'max_execution_time' );
1234
1235
		// Ensure exec time set in php.ini.
1236
		if ( ! $timeout ) {
1237
			$timeout = 30;
1238
		}
1239
		return $timeout;
1240
	}
1241
1242
	/**
1243
	 * Sets a minimum request timeout, and returns the current timeout
1244
	 *
1245
	 * @since 5.4
1246
	 * @param Integer $min_timeout the minimum timeout value.
1247
	 **/
1248 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1249
		$timeout = $this->get_max_execution_time();
1250
		if ( $timeout < $min_timeout ) {
1251
			$timeout = $min_timeout;
1252
			set_time_limit( $timeout );
1253
		}
1254
		return $timeout;
1255
	}
1256
1257
	/**
1258
	 * Get our assumed site creation date.
1259
	 * Calculated based on the earlier date of either:
1260
	 * - Earliest admin user registration date.
1261
	 * - Earliest date of post of any post type.
1262
	 *
1263
	 * @since 7.2.0
1264
	 *
1265
	 * @return string Assumed site creation date and time.
1266
	 */
1267
	public function get_assumed_site_creation_date() {
1268
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1269
		if ( ! empty( $cached_date ) ) {
1270
			return $cached_date;
1271
		}
1272
1273
		$earliest_registered_users  = get_users(
1274
			array(
1275
				'role'    => 'administrator',
1276
				'orderby' => 'user_registered',
1277
				'order'   => 'ASC',
1278
				'fields'  => array( 'user_registered' ),
1279
				'number'  => 1,
1280
			)
1281
		);
1282
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1283
1284
		$earliest_posts = get_posts(
1285
			array(
1286
				'posts_per_page' => 1,
1287
				'post_type'      => 'any',
1288
				'post_status'    => 'any',
1289
				'orderby'        => 'date',
1290
				'order'          => 'ASC',
1291
			)
1292
		);
1293
1294
		// If there are no posts at all, we'll count only on user registration date.
1295
		if ( $earliest_posts ) {
1296
			$earliest_post_date = $earliest_posts[0]->post_date;
1297
		} else {
1298
			$earliest_post_date = PHP_INT_MAX;
1299
		}
1300
1301
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1302
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1303
1304
		return $assumed_date;
1305
	}
1306
1307
	/**
1308
	 * Adds the activation source string as a parameter to passed arguments.
1309
	 *
1310
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1311
	 *
1312
	 * @param array $args arguments that need to have the source added.
1313
	 * @return array $amended arguments.
1314
	 */
1315 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1316
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1317
1318
		if ( $activation_source_name ) {
1319
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1320
			$args['_as'] = urlencode( $activation_source_name );
1321
		}
1322
1323
		if ( $activation_source_keyword ) {
1324
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1325
			$args['_ak'] = urlencode( $activation_source_keyword );
1326
		}
1327
1328
		return $args;
1329
	}
1330
1331
	/**
1332
	 * Returns the callable that would be used to generate secrets.
1333
	 *
1334
	 * @return Callable a function that returns a secure string to be used as a secret.
1335
	 */
1336
	protected function get_secret_callable() {
1337
		if ( ! isset( $this->secret_callable ) ) {
1338
			/**
1339
			 * Allows modification of the callable that is used to generate connection secrets.
1340
			 *
1341
			 * @param Callable a function or method that returns a secret string.
1342
			 */
1343
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', array( $this, 'secret_callable_method' ) );
1344
		}
1345
1346
		return $this->secret_callable;
1347
	}
1348
1349
	/**
1350
	 * Runs the wp_generate_password function with the required parameters. This is the
1351
	 * default implementation of the secret callable, can be overridden using the
1352
	 * jetpack_connection_secret_generator filter.
1353
	 *
1354
	 * @return String $secret value.
1355
	 */
1356
	private function secret_callable_method() {
1357
		return wp_generate_password( 32, false );
1358
	}
1359
1360
	/**
1361
	 * Generates two secret tokens and the end of life timestamp for them.
1362
	 *
1363
	 * @param String  $action  The action name.
1364
	 * @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...
1365
	 * @param Integer $exp     Expiration time in seconds.
1366
	 */
1367
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1368
		if ( false === $user_id ) {
1369
			$user_id = get_current_user_id();
1370
		}
1371
1372
		$callable = $this->get_secret_callable();
1373
1374
		$secrets = \Jetpack_Options::get_raw_option(
1375
			self::SECRETS_OPTION_NAME,
1376
			array()
1377
		);
1378
1379
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1380
1381
		if (
1382
			isset( $secrets[ $secret_name ] ) &&
1383
			$secrets[ $secret_name ]['exp'] > time()
1384
		) {
1385
			return $secrets[ $secret_name ];
1386
		}
1387
1388
		$secret_value = array(
1389
			'secret_1' => call_user_func( $callable ),
1390
			'secret_2' => call_user_func( $callable ),
1391
			'exp'      => time() + $exp,
1392
		);
1393
1394
		$secrets[ $secret_name ] = $secret_value;
1395
1396
		$res = Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1397
		return $res ? $secrets[ $secret_name ] : false;
1398
	}
1399
1400
	/**
1401
	 * Returns two secret tokens and the end of life timestamp for them.
1402
	 *
1403
	 * @param String  $action  The action name.
1404
	 * @param Integer $user_id The user identifier.
1405
	 * @return string|array an array of secrets or an error string.
1406
	 */
1407
	public function get_secrets( $action, $user_id ) {
1408
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1409
		$secrets     = \Jetpack_Options::get_raw_option(
1410
			self::SECRETS_OPTION_NAME,
1411
			array()
1412
		);
1413
1414
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1415
			return self::SECRETS_MISSING;
1416
		}
1417
1418
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1419
			$this->delete_secrets( $action, $user_id );
1420
			return self::SECRETS_EXPIRED;
1421
		}
1422
1423
		return $secrets[ $secret_name ];
1424
	}
1425
1426
	/**
1427
	 * Deletes secret tokens in case they, for example, have expired.
1428
	 *
1429
	 * @param String  $action  The action name.
1430
	 * @param Integer $user_id The user identifier.
1431
	 */
1432
	public function delete_secrets( $action, $user_id ) {
1433
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1434
		$secrets     = \Jetpack_Options::get_raw_option(
1435
			self::SECRETS_OPTION_NAME,
1436
			array()
1437
		);
1438
		if ( isset( $secrets[ $secret_name ] ) ) {
1439
			unset( $secrets[ $secret_name ] );
1440
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1441
		}
1442
	}
1443
1444
	/**
1445
	 * Deletes all connection tokens and transients from the local Jetpack site.
1446
	 * If the plugin object has been provided in the constructor, the function first checks
1447
	 * whether it's the only active connection.
1448
	 * If there are any other connections, the function will do nothing and return `false`
1449
	 * (unless `$ignore_connected_plugins` is set to `true`).
1450
	 *
1451
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1452
	 *
1453
	 * @return bool True if disconnected successfully, false otherwise.
1454
	 */
1455
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1456 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1457
			return false;
1458
		}
1459
1460
		/**
1461
		 * Fires upon the disconnect attempt.
1462
		 * Return `false` to prevent the disconnect.
1463
		 *
1464
		 * @since 8.7.0
1465
		 */
1466
		if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', 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...
1467
			return false;
1468
		}
1469
1470
		\Jetpack_Options::delete_option(
1471
			array(
1472
				'blog_token',
1473
				'user_token',
1474
				'user_tokens',
1475
				'master_user',
1476
				'time_diff',
1477
				'fallback_no_verify_ssl_certs',
1478
			)
1479
		);
1480
1481
		\Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
1482
1483
		// Delete cached connected user data.
1484
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1485
		delete_transient( $transient_key );
1486
1487
		// Delete all XML-RPC errors.
1488
		Error_Handler::get_instance()->delete_all_errors();
1489
1490
		return true;
1491
	}
1492
1493
	/**
1494
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1495
	 * If the plugin object has been provided in the constructor, the function first check
1496
	 * whether it's the only active connection.
1497
	 * If there are any other connections, the function will do nothing and return `false`
1498
	 * (unless `$ignore_connected_plugins` is set to `true`).
1499
	 *
1500
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1501
	 *
1502
	 * @return bool True if disconnected successfully, false otherwise.
1503
	 */
1504
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1505 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1506
			return false;
1507
		}
1508
1509
		/**
1510
		 * Fires upon the disconnect attempt.
1511
		 * Return `false` to prevent the disconnect.
1512
		 *
1513
		 * @since 8.7.0
1514
		 */
1515
		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...
1516
			return false;
1517
		}
1518
1519
		$xml = new \Jetpack_IXR_Client();
1520
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1521
1522
		return true;
1523
	}
1524
1525
	/**
1526
	 * Disconnect the plugin and remove the tokens.
1527
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1528
	 * This is a proxy method to simplify the Connection package API.
1529
	 *
1530
	 * @see Manager::disable_plugin()
1531
	 * @see Manager::disconnect_site_wpcom()
1532
	 * @see Manager::delete_all_connection_tokens()
1533
	 *
1534
	 * @return bool
1535
	 */
1536
	public function remove_connection() {
1537
		$this->disable_plugin();
1538
		$this->disconnect_site_wpcom();
1539
		$this->delete_all_connection_tokens();
1540
1541
		return true;
1542
	}
1543
1544
	/**
1545
	 * Completely clearing up the connection, and initiating reconnect.
1546
	 *
1547
	 * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
1548
	 */
1549
	public function reconnect() {
1550
		( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
1551
1552
		$this->disconnect_site_wpcom( true );
1553
		$this->delete_all_connection_tokens( true );
1554
1555
		return $this->register();
1556
	}
1557
1558
	/**
1559
	 * Validate the tokens, and refresh the invalid ones.
1560
	 *
1561
	 * @return string|true|WP_Error True if connection restored or string indicating what's to be done next. A `WP_Error` object otherwise.
1562
	 */
1563
	public function restore() {
1564
		$invalid_tokens = array();
1565
		$can_restore    = $this->can_restore( $invalid_tokens );
1566
1567
		// Tokens are valid. We can't fix the problem we don't see, so the full reconnection is needed.
1568
		if ( ! $can_restore ) {
1569
			$result = $this->reconnect();
1570
			return true === $result ? 'authorize' : $result;
1571
		}
1572
1573
		if ( in_array( 'blog', $invalid_tokens, true ) ) {
1574
			return self::refresh_blog_token();
1575
		}
1576
1577
		if ( in_array( 'user', $invalid_tokens, true ) ) {
1578
			return true === self::refresh_user_token() ? 'authorize' : false;
1579
		}
1580
1581
		return false;
1582
	}
1583
1584
	/**
1585
	 * Determine whether we can restore the connection, or the full reconnect is needed.
1586
	 *
1587
	 * @param array $invalid_tokens The array the invalid tokens are stored in, provided by reference.
1588
	 *
1589
	 * @return bool `True` if the connection can be restored, `false` otherwise.
1590
	 */
1591
	public function can_restore( &$invalid_tokens ) {
1592
		$invalid_tokens = array();
1593
1594
		$validated_tokens = $this->validate_tokens();
1595
1596
		if ( ! is_array( $validated_tokens ) || count( array_diff_key( array_flip( array( 'blog_token', 'user_token' ) ), $validated_tokens ) ) ) {
1597
			return false;
1598
		}
1599
1600
		if ( empty( $validated_tokens['blog_token']['is_healthy'] ) ) {
1601
			$invalid_tokens[] = 'blog';
1602
		}
1603
1604
		if ( empty( $validated_tokens['user_token']['is_healthy'] ) ) {
1605
			$invalid_tokens[] = 'user';
1606
		}
1607
1608
		// If both tokens are invalid, we can't restore the connection.
1609
		return 1 === count( $invalid_tokens );
1610
	}
1611
1612
	/**
1613
	 * Perform the API request to validate the blog and user tokens.
1614
	 *
1615
	 * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
1616
	 *
1617
	 * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
1618
	 */
1619
	public function validate_tokens( $user_id = null ) {
1620
		$blog_id = Jetpack_Options::get_option( 'id' );
1621
		if ( ! $blog_id ) {
1622
			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...
1623
		}
1624
		$url = sprintf(
1625
			'%s/%s/v%s/%s',
1626
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
1627
			'wpcom',
1628
			'2',
1629
			'sites/' . $blog_id . '/jetpack-token-health'
1630
		);
1631
1632
		$user_token = $this->get_access_token( $user_id ? $user_id : get_current_user_id() );
1633
		$blog_token = $this->get_access_token();
1634
		$method     = 'POST';
1635
		$body       = array(
1636
			'user_token' => $this->get_signed_token( $user_token ),
0 ignored issues
show
Security Bug introduced by
It seems like $user_token defined by $this->get_access_token(... get_current_user_id()) on line 1632 can also be of type false; however, Automattic\Jetpack\Conne...ger::get_signed_token() does only seem to accept object, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
1637
			'blog_token' => $this->get_signed_token( $blog_token ),
0 ignored issues
show
Security Bug introduced by
It seems like $blog_token defined by $this->get_access_token() on line 1633 can also be of type false; however, Automattic\Jetpack\Conne...ger::get_signed_token() does only seem to accept object, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
1638
		);
1639
		$response   = Client::_wp_remote_request( $url, compact( 'body', 'method' ) );
1640
1641
		if ( is_wp_error( $response ) || ! wp_remote_retrieve_body( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
1642
			return false;
1643
		}
1644
1645
		$body = json_decode( wp_remote_retrieve_body( $response ), true );
1646
1647
		return $body ? $body : false;
1648
	}
1649
1650
	/**
1651
	 * Responds to a WordPress.com call to register the current site.
1652
	 * Should be changed to protected.
1653
	 *
1654
	 * @param array $registration_data Array of [ secret_1, user_id ].
1655
	 */
1656
	public function handle_registration( array $registration_data ) {
1657
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1658
		if ( empty( $registration_user_id ) ) {
1659
			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...
1660
		}
1661
1662
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1663
	}
1664
1665
	/**
1666
	 * Verify a Previously Generated Secret.
1667
	 *
1668
	 * @param string $action   The type of secret to verify.
1669
	 * @param string $secret_1 The secret string to compare to what is stored.
1670
	 * @param int    $user_id  The user ID of the owner of the secret.
1671
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1672
	 */
1673
	public function verify_secrets( $action, $secret_1, $user_id ) {
1674
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1675
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1676
			return new \WP_Error( 'unknown_verification_action', 'Unknown Verification Action', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_verification_action'.

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

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

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

Loading history...
1677
		}
1678
1679
		$user = get_user_by( 'id', $user_id );
1680
1681
		/**
1682
		 * We've begun verifying the previously generated secret.
1683
		 *
1684
		 * @since 7.5.0
1685
		 *
1686
		 * @param string   $action The type of secret to verify.
1687
		 * @param \WP_User $user The user object.
1688
		 */
1689
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1690
1691
		$return_error = function ( \WP_Error $error ) use ( $action, $user ) {
1692
			/**
1693
			 * Verifying of the previously generated secret has failed.
1694
			 *
1695
			 * @since 7.5.0
1696
			 *
1697
			 * @param string    $action  The type of secret to verify.
1698
			 * @param \WP_User  $user The user object.
1699
			 * @param \WP_Error $error The error object.
1700
			 */
1701
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1702
1703
			return $error;
1704
		};
1705
1706
		$stored_secrets = $this->get_secrets( $action, $user_id );
1707
		$this->delete_secrets( $action, $user_id );
1708
1709
		$error = null;
1710
		if ( empty( $secret_1 ) ) {
1711
			$error = $return_error(
1712
				new \WP_Error(
1713
					'verify_secret_1_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secret_1_missing'.

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...
1714
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1715
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1716
					400
1717
				)
1718
			);
1719
		} elseif ( ! is_string( $secret_1 ) ) {
1720
			$error = $return_error(
1721
				new \WP_Error(
1722
					'verify_secret_1_malformed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secret_1_malformed'.

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

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

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

Loading history...
1723
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1724
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1725
					400
1726
				)
1727
			);
1728
		} elseif ( empty( $user_id ) ) {
1729
			// $user_id is passed around during registration as "state".
1730
			$error = $return_error(
1731
				new \WP_Error(
1732
					'state_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'state_missing'.

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...
1733
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1734
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1735
					400
1736
				)
1737
			);
1738
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1739
			$error = $return_error(
1740
				new \WP_Error(
1741
					'state_malformed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'state_malformed'.

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...
1742
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1743
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1744
					400
1745
				)
1746
			);
1747
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1748
			$error = $return_error(
1749
				new \WP_Error(
1750
					'verify_secrets_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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...
1751
					__( 'Verification secrets not found', 'jetpack' ),
1752
					400
1753
				)
1754
			);
1755
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1756
			$error = $return_error(
1757
				new \WP_Error(
1758
					'verify_secrets_expired',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

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...
1759
					__( 'Verification took too long', 'jetpack' ),
1760
					400
1761
				)
1762
			);
1763
		} elseif ( ! $stored_secrets ) {
1764
			$error = $return_error(
1765
				new \WP_Error(
1766
					'verify_secrets_empty',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_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...
1767
					__( 'Verification secrets are empty', 'jetpack' ),
1768
					400
1769
				)
1770
			);
1771
		} elseif ( is_wp_error( $stored_secrets ) ) {
1772
			$stored_secrets->add_data( 400 );
0 ignored issues
show
Bug introduced by
The method add_data cannot be called on $stored_secrets (of type string|array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1773
			$error = $return_error( $stored_secrets );
1774
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1775
			$error = $return_error(
1776
				new \WP_Error(
1777
					'verify_secrets_incomplete',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_incomplete'.

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...
1778
					__( 'Verification secrets are incomplete', 'jetpack' ),
1779
					400
1780
				)
1781
			);
1782
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1783
			$error = $return_error(
1784
				new \WP_Error(
1785
					'verify_secrets_mismatch',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_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...
1786
					__( 'Secret mismatch', 'jetpack' ),
1787
					400
1788
				)
1789
			);
1790
		}
1791
1792
		// Something went wrong during the checks, returning the error.
1793
		if ( ! empty( $error ) ) {
1794
			return $error;
1795
		}
1796
1797
		/**
1798
		 * We've succeeded at verifying the previously generated secret.
1799
		 *
1800
		 * @since 7.5.0
1801
		 *
1802
		 * @param string   $action The type of secret to verify.
1803
		 * @param \WP_User $user The user object.
1804
		 */
1805
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1806
1807
		return $stored_secrets['secret_2'];
1808
	}
1809
1810
	/**
1811
	 * Responds to a WordPress.com call to authorize the current user.
1812
	 * Should be changed to protected.
1813
	 */
1814
	public function handle_authorization() {
1815
1816
	}
1817
1818
	/**
1819
	 * Obtains the auth token.
1820
	 *
1821
	 * @param array $data The request data.
1822
	 * @return object|\WP_Error Returns the auth token on success.
1823
	 *                          Returns a \WP_Error on failure.
1824
	 */
1825
	public function get_token( $data ) {
1826
		$roles = new Roles();
1827
		$role  = $roles->translate_current_user_to_role();
1828
1829
		if ( ! $role ) {
1830
			return new \WP_Error( 'role', __( 'An administrator for this blog must set up the Jetpack connection.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with '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...
1831
		}
1832
1833
		$client_secret = $this->get_access_token();
1834
		if ( ! $client_secret ) {
1835
			return new \WP_Error( 'client_secret', __( 'You need to register your Jetpack before connecting it.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'client_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...
1836
		}
1837
1838
		/**
1839
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1840
		 * data processing.
1841
		 *
1842
		 * @since 8.0.0
1843
		 *
1844
		 * @param string $redirect_url Defaults to the site admin URL.
1845
		 */
1846
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1847
1848
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1849
1850
		/**
1851
		* Filter the URL to redirect the user back to when the authentication process
1852
		* is complete.
1853
		*
1854
		* @since 8.0.0
1855
		*
1856
		* @param string $redirect_url Defaults to the site URL.
1857
		*/
1858
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1859
1860
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1861
			? $data['redirect_uri']
1862
			: add_query_arg(
1863
				array(
1864
					'action'   => 'authorize',
1865
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1866
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1867
				),
1868
				esc_url( $processing_url )
1869
			);
1870
1871
		/**
1872
		 * Filters the token request data.
1873
		 *
1874
		 * @since 8.0.0
1875
		 *
1876
		 * @param array $request_data request data.
1877
		 */
1878
		$body = apply_filters(
1879
			'jetpack_token_request_body',
1880
			array(
1881
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1882
				'client_secret' => $client_secret->secret,
1883
				'grant_type'    => 'authorization_code',
1884
				'code'          => $data['code'],
1885
				'redirect_uri'  => $redirect_uri,
1886
			)
1887
		);
1888
1889
		$args = array(
1890
			'method'  => 'POST',
1891
			'body'    => $body,
1892
			'headers' => array(
1893
				'Accept' => 'application/json',
1894
			),
1895
		);
1896
1897
		add_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1898
		$response = Client::_wp_remote_request( $this->api_url( 'token' ), $args );
1899
		remove_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1900
1901
		if ( is_wp_error( $response ) ) {
1902
			return new \WP_Error( 'token_http_request_failed', $response->get_error_message() );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with '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...
1903
		}
1904
1905
		$code   = wp_remote_retrieve_response_code( $response );
1906
		$entity = wp_remote_retrieve_body( $response );
1907
1908
		if ( $entity ) {
1909
			$json = json_decode( $entity );
1910
		} else {
1911
			$json = false;
1912
		}
1913
1914 View Code Duplication
		if ( 200 !== $code || ! empty( $json->error ) ) {
1915
			if ( empty( $json->error ) ) {
1916
				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...
1917
			}
1918
1919
			/* translators: Error description string. */
1920
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1921
1922
			return new \WP_Error( (string) $json->error, $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->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...
1923
		}
1924
1925
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1926
			return new \WP_Error( 'access_token', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'access_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...
1927
		}
1928
1929
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1930
			return new \WP_Error( 'token_type', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_type'.

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...
1931
		}
1932
1933
		if ( empty( $json->scope ) ) {
1934
			return new \WP_Error( 'scope', 'No Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1935
		}
1936
1937
		// TODO: get rid of the error silencer.
1938
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1939
		@list( $role, $hmac ) = explode( ':', $json->scope );
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...
1940
		if ( empty( $role ) || empty( $hmac ) ) {
1941
			return new \WP_Error( 'scope', 'Malformed Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1942
		}
1943
1944
		if ( $this->sign_role( $role ) !== $json->scope ) {
1945
			return new \WP_Error( 'scope', 'Invalid Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1946
		}
1947
1948
		$cap = $roles->translate_role_to_cap( $role );
1949
		if ( ! $cap ) {
1950
			return new \WP_Error( 'scope', 'No Cap', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1951
		}
1952
1953
		if ( ! current_user_can( $cap ) ) {
1954
			return new \WP_Error( 'scope', 'current_user_cannot', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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...
1955
		}
1956
1957
		return (string) $json->access_token;
1958
	}
1959
1960
	/**
1961
	 * Increases the request timeout value to 30 seconds.
1962
	 *
1963
	 * @return int Returns 30.
1964
	 */
1965
	public function increase_timeout() {
1966
		return 30;
1967
	}
1968
1969
	/**
1970
	 * Builds a URL to the Jetpack connection auth page.
1971
	 *
1972
	 * @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...
1973
	 * @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...
1974
	 * @return string Connect URL.
1975
	 */
1976
	public function get_authorization_url( $user = null, $redirect = null ) {
1977
1978
		if ( empty( $user ) ) {
1979
			$user = wp_get_current_user();
1980
		}
1981
1982
		$roles       = new Roles();
1983
		$role        = $roles->translate_user_to_role( $user );
1984
		$signed_role = $this->sign_role( $role );
1985
1986
		/**
1987
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1988
		 * data processing.
1989
		 *
1990
		 * @since 8.0.0
1991
		 *
1992
		 * @param string $redirect_url Defaults to the site admin URL.
1993
		 */
1994
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1995
1996
		/**
1997
		 * Filter the URL to redirect the user back to when the authorization process
1998
		 * is complete.
1999
		 *
2000
		 * @since 8.0.0
2001
		 *
2002
		 * @param string $redirect_url Defaults to the site URL.
2003
		 */
2004
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
2005
2006
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
2007
2008
		/**
2009
		 * Filter the type of authorization.
2010
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
2011
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
2012
		 *
2013
		 * @since 4.3.3
2014
		 *
2015
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
2016
		 */
2017
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
2018
2019
		/**
2020
		 * Filters the user connection request data for additional property addition.
2021
		 *
2022
		 * @since 8.0.0
2023
		 *
2024
		 * @param array $request_data request data.
2025
		 */
2026
		$body = apply_filters(
2027
			'jetpack_connect_request_body',
2028
			array(
2029
				'response_type' => 'code',
2030
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
2031
				'redirect_uri'  => add_query_arg(
2032
					array(
2033
						'action'   => 'authorize',
2034
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
2035
						'redirect' => rawurlencode( $redirect ),
2036
					),
2037
					esc_url( $processing_url )
2038
				),
2039
				'state'         => $user->ID,
2040
				'scope'         => $signed_role,
2041
				'user_email'    => $user->user_email,
2042
				'user_login'    => $user->user_login,
2043
				'is_active'     => $this->is_active(),
2044
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
2045
				'auth_type'     => $auth_type,
2046
				'secret'        => $secrets['secret_1'],
2047
				'blogname'      => get_option( 'blogname' ),
2048
				'site_url'      => site_url(),
2049
				'home_url'      => home_url(),
2050
				'site_icon'     => get_site_icon_url(),
2051
				'site_lang'     => get_locale(),
2052
				'site_created'  => $this->get_assumed_site_creation_date(),
2053
			)
2054
		);
2055
2056
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
2057
2058
		$api_url = $this->api_url( 'authorize' );
2059
2060
		return add_query_arg( $body, $api_url );
2061
	}
2062
2063
	/**
2064
	 * Authorizes the user by obtaining and storing the user token.
2065
	 *
2066
	 * @param array $data The request data.
2067
	 * @return string|\WP_Error Returns a string on success.
2068
	 *                          Returns a \WP_Error on failure.
2069
	 */
2070
	public function authorize( $data = array() ) {
2071
		/**
2072
		 * Action fired when user authorization starts.
2073
		 *
2074
		 * @since 8.0.0
2075
		 */
2076
		do_action( 'jetpack_authorize_starting' );
2077
2078
		$roles = new Roles();
2079
		$role  = $roles->translate_current_user_to_role();
2080
2081
		if ( ! $role ) {
2082
			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...
2083
		}
2084
2085
		$cap = $roles->translate_role_to_cap( $role );
2086
		if ( ! $cap ) {
2087
			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...
2088
		}
2089
2090
		if ( ! empty( $data['error'] ) ) {
2091
			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...
2092
		}
2093
2094
		if ( ! isset( $data['state'] ) ) {
2095
			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...
2096
		}
2097
2098
		if ( ! ctype_digit( $data['state'] ) ) {
2099
			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...
2100
		}
2101
2102
		$current_user_id = get_current_user_id();
2103
		if ( $current_user_id !== (int) $data['state'] ) {
2104
			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...
2105
		}
2106
2107
		if ( empty( $data['code'] ) ) {
2108
			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...
2109
		}
2110
2111
		$token = $this->get_token( $data );
2112
2113 View Code Duplication
		if ( is_wp_error( $token ) ) {
2114
			$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...
2115
			if ( empty( $code ) ) {
2116
				$code = 'invalid_token';
2117
			}
2118
			return new \WP_Error( $code, $token->get_error_message(), 400 );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

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

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

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

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

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

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

Loading history...
2119
		}
2120
2121
		if ( ! $token ) {
2122
			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...
2123
		}
2124
2125
		$is_master_user = ! $this->is_active();
2126
2127
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
2128
2129
		/**
2130
		 * Fires after user has successfully received an auth token.
2131
		 *
2132
		 * @since 3.9.0
2133
		 */
2134
		do_action( 'jetpack_user_authorized' );
2135
2136
		if ( ! $is_master_user ) {
2137
			/**
2138
			 * Action fired when a secondary user has been authorized.
2139
			 *
2140
			 * @since 8.0.0
2141
			 */
2142
			do_action( 'jetpack_authorize_ending_linked' );
2143
			return 'linked';
2144
		}
2145
2146
		/**
2147
		 * Action fired when the master user has been authorized.
2148
		 *
2149
		 * @since 8.0.0
2150
		 *
2151
		 * @param array $data The request data.
2152
		 */
2153
		do_action( 'jetpack_authorize_ending_authorized', $data );
2154
2155
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
2156
2157
		// Start nonce cleaner.
2158
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2159
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
2160
2161
		return 'authorized';
2162
	}
2163
2164
	/**
2165
	 * Disconnects from the Jetpack servers.
2166
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2167
	 */
2168
	public function disconnect_site() {
2169
2170
	}
2171
2172
	/**
2173
	 * The Base64 Encoding of the SHA1 Hash of the Input.
2174
	 *
2175
	 * @param string $text The string to hash.
2176
	 * @return string
2177
	 */
2178
	public function sha1_base64( $text ) {
2179
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2180
	}
2181
2182
	/**
2183
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
2184
	 *
2185
	 * @param string $domain The domain to check.
2186
	 *
2187
	 * @return bool|WP_Error
2188
	 */
2189
	public function is_usable_domain( $domain ) {
2190
2191
		// If it's empty, just fail out.
2192
		if ( ! $domain ) {
2193
			return new \WP_Error(
2194
				'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...
2195
				/* translators: %1$s is a domain name. */
2196
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
2197
			);
2198
		}
2199
2200
		/**
2201
		 * Skips the usuable domain check when connecting a site.
2202
		 *
2203
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
2204
		 *
2205
		 * @since 4.1.0
2206
		 *
2207
		 * @param bool If the check should be skipped. Default false.
2208
		 */
2209
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
2210
			return true;
2211
		}
2212
2213
		// None of the explicit localhosts.
2214
		$forbidden_domains = array(
2215
			'wordpress.com',
2216
			'localhost',
2217
			'localhost.localdomain',
2218
			'127.0.0.1',
2219
			'local.wordpress.test',         // VVV pattern.
2220
			'local.wordpress-trunk.test',   // VVV pattern.
2221
			'src.wordpress-develop.test',   // VVV pattern.
2222
			'build.wordpress-develop.test', // VVV pattern.
2223
		);
2224 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
2225
			return new \WP_Error(
2226
				'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...
2227
				sprintf(
2228
					/* translators: %1$s is a domain name. */
2229
					__(
2230
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
2231
						'jetpack'
2232
					),
2233
					$domain
2234
				)
2235
			);
2236
		}
2237
2238
		// No .test or .local domains.
2239 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
2240
			return new \WP_Error(
2241
				'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...
2242
				sprintf(
2243
					/* translators: %1$s is a domain name. */
2244
					__(
2245
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
2246
						'jetpack'
2247
					),
2248
					$domain
2249
				)
2250
			);
2251
		}
2252
2253
		// No WPCOM subdomains.
2254 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
2255
			return new \WP_Error(
2256
				'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...
2257
				sprintf(
2258
					/* translators: %1$s is a domain name. */
2259
					__(
2260
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
2261
						'jetpack'
2262
					),
2263
					$domain
2264
				)
2265
			);
2266
		}
2267
2268
		// If PHP was compiled without support for the Filter module (very edge case).
2269
		if ( ! function_exists( 'filter_var' ) ) {
2270
			// Just pass back true for now, and let wpcom sort it out.
2271
			return true;
2272
		}
2273
2274
		return true;
2275
	}
2276
2277
	/**
2278
	 * Gets the requested token.
2279
	 *
2280
	 * Tokens are one of two types:
2281
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
2282
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
2283
	 *    are not associated with a user account. They represent the site's connection with
2284
	 *    the Jetpack servers.
2285
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
2286
	 *
2287
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
2288
	 * token, and $private is a secret that should never be displayed anywhere or sent
2289
	 * over the network; it's used only for signing things.
2290
	 *
2291
	 * Blog Tokens can be "Normal" or "Special".
2292
	 * * Normal: The result of a normal connection flow. They look like
2293
	 *   "{$random_string_1}.{$random_string_2}"
2294
	 *   That is, $token_key and $private are both random strings.
2295
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
2296
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
2297
	 *   constant (rare).
2298
	 * * Special: A connection token for sites that have gone through an alternative
2299
	 *   connection flow. They look like:
2300
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
2301
	 *   That is, $private is a random string and $token_key has a special structure with
2302
	 *   lots of semicolons.
2303
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
2304
	 *   JETPACK_BLOG_TOKEN constant.
2305
	 *
2306
	 * In particular, note that Normal Blog Tokens never start with ";" and that
2307
	 * Special Blog Tokens always do.
2308
	 *
2309
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
2310
	 * order:
2311
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
2312
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
2313
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
2314
	 *
2315
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
2316
	 * @param string|false $token_key If provided, check that the token matches the provided input.
2317
	 * @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.
2318
	 *
2319
	 * @return object|false
2320
	 */
2321
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
2322
		$possible_special_tokens = array();
2323
		$possible_normal_tokens  = array();
2324
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
2325
2326
		if ( ( new Status() )->is_no_user_testing_mode() ) {
2327
			$user_tokens = false;
2328
		}
2329
2330
		if ( $user_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user_id of type false|integer is loosely compared to true; 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...
2331
			if ( ! $user_tokens ) {
2332
				return $suppress_errors ? false : new \WP_Error( 'no_user_tokens', __( 'No user tokens found', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_user_tokens'.

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...
2333
			}
2334
			if ( self::CONNECTION_OWNER === $user_id ) {
2335
				$user_id = \Jetpack_Options::get_option( 'master_user' );
2336
				if ( ! $user_id ) {
2337
					return $suppress_errors ? false : new \WP_Error( 'empty_master_user_option', __( 'No primary user defined', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'empty_master_user_option'.

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...
2338
				}
2339
			}
2340
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
2341
				// translators: %s is the user ID.
2342
				return $suppress_errors ? false : new \WP_Error( 'no_token_for_user', sprintf( __( 'No token for user %d', 'jetpack' ), $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_token_for_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...
2343
			}
2344
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
2345 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
2346
				// translators: %s is the user ID.
2347
				return $suppress_errors ? false : new \WP_Error( 'token_malformed', sprintf( __( 'Token for user %d is malformed', 'jetpack' ), $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_malformed'.

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...
2348
			}
2349
			if ( $user_token_chunks[2] !== (string) $user_id ) {
2350
				// translators: %1$d is the ID of the requested user. %2$d is the user ID found in the token.
2351
				return $suppress_errors ? false : new \WP_Error( 'user_id_mismatch', sprintf( __( 'Requesting user_id %1$d does not match token user_id %2$d', 'jetpack' ), $user_id, $user_token_chunks[2] ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_id_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...
2352
			}
2353
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
2354
		} else {
2355
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
2356
			if ( $stored_blog_token ) {
2357
				$possible_normal_tokens[] = $stored_blog_token;
2358
			}
2359
2360
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
2361
2362
			if ( $defined_tokens_string ) {
2363
				$defined_tokens = explode( ',', $defined_tokens_string );
2364
				foreach ( $defined_tokens as $defined_token ) {
2365
					if ( ';' === $defined_token[0] ) {
2366
						$possible_special_tokens[] = $defined_token;
2367
					} else {
2368
						$possible_normal_tokens[] = $defined_token;
2369
					}
2370
				}
2371
			}
2372
		}
2373
2374
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2375
			$possible_tokens = $possible_normal_tokens;
2376
		} else {
2377
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
2378
		}
2379
2380
		if ( ! $possible_tokens ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $possible_tokens of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2381
			// If no user tokens were found, it would have failed earlier, so this is about blog token.
2382
			return $suppress_errors ? false : new \WP_Error( 'no_possible_tokens', __( 'No blog token found', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_possible_tokens'.

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...
2383
		}
2384
2385
		$valid_token = false;
2386
2387
		if ( false === $token_key ) {
2388
			// Use first token.
2389
			$valid_token = $possible_tokens[0];
2390
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2391
			// Use first normal token.
2392
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
2393
		} else {
2394
			// Use the token matching $token_key or false if none.
2395
			// Ensure we check the full key.
2396
			$token_check = rtrim( $token_key, '.' ) . '.';
2397
2398
			foreach ( $possible_tokens as $possible_token ) {
2399
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
2400
					$valid_token = $possible_token;
2401
					break;
2402
				}
2403
			}
2404
		}
2405
2406
		if ( ! $valid_token ) {
2407
			if ( $user_id ) {
2408
				// translators: %d is the user ID.
2409
				return $suppress_errors ? false : new \WP_Error( 'no_valid_user_token', sprintf( __( 'Invalid token for user %d', 'jetpack' ), $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_valid_user_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...
2410
			} else {
2411
				return $suppress_errors ? false : new \WP_Error( 'no_valid_blog_token', __( 'Invalid blog token', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_valid_blog_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...
2412
			}
2413
		}
2414
2415
		return (object) array(
2416
			'secret'           => $valid_token,
2417
			'external_user_id' => (int) $user_id,
2418
		);
2419
	}
2420
2421
	/**
2422
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2423
	 * since it is passed by reference to various methods.
2424
	 * Capture it here so we can verify the signature later.
2425
	 *
2426
	 * @param array $methods an array of available XMLRPC methods.
2427
	 * @return array the same array, since this method doesn't add or remove anything.
2428
	 */
2429
	public function xmlrpc_methods( $methods ) {
2430
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
2431
		return $methods;
2432
	}
2433
2434
	/**
2435
	 * Resets the raw post data parameter for testing purposes.
2436
	 */
2437
	public function reset_raw_post_data() {
2438
		$this->raw_post_data = null;
2439
	}
2440
2441
	/**
2442
	 * Registering an additional method.
2443
	 *
2444
	 * @param array $methods an array of available XMLRPC methods.
2445
	 * @return array the amended array in case the method is added.
2446
	 */
2447
	public function public_xmlrpc_methods( $methods ) {
2448
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2449
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2450
		}
2451
		return $methods;
2452
	}
2453
2454
	/**
2455
	 * Handles a getOptions XMLRPC method call.
2456
	 *
2457
	 * @param array $args method call arguments.
2458
	 * @return an amended XMLRPC server options array.
2459
	 */
2460
	public function jetpack_get_options( $args ) {
2461
		global $wp_xmlrpc_server;
2462
2463
		$wp_xmlrpc_server->escape( $args );
2464
2465
		$username = $args[1];
2466
		$password = $args[2];
2467
2468
		$user = $wp_xmlrpc_server->login( $username, $password );
2469
		if ( ! $user ) {
2470
			return $wp_xmlrpc_server->error;
2471
		}
2472
2473
		$options   = array();
2474
		$user_data = $this->get_connected_user_data();
2475
		if ( is_array( $user_data ) ) {
2476
			$options['jetpack_user_id']         = array(
2477
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2478
				'readonly' => true,
2479
				'value'    => $user_data['ID'],
2480
			);
2481
			$options['jetpack_user_login']      = array(
2482
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2483
				'readonly' => true,
2484
				'value'    => $user_data['login'],
2485
			);
2486
			$options['jetpack_user_email']      = array(
2487
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2488
				'readonly' => true,
2489
				'value'    => $user_data['email'],
2490
			);
2491
			$options['jetpack_user_site_count'] = array(
2492
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2493
				'readonly' => true,
2494
				'value'    => $user_data['site_count'],
2495
			);
2496
		}
2497
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2498
		$args                           = stripslashes_deep( $args );
2499
		return $wp_xmlrpc_server->wp_getOptions( $args );
2500
	}
2501
2502
	/**
2503
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2504
	 *
2505
	 * @param array $options standard Core options.
2506
	 * @return array amended options.
2507
	 */
2508
	public function xmlrpc_options( $options ) {
2509
		$jetpack_client_id = false;
2510
		if ( $this->is_active() ) {
2511
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2512
		}
2513
		$options['jetpack_version'] = array(
2514
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2515
			'readonly' => true,
2516
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2517
		);
2518
2519
		$options['jetpack_client_id'] = array(
2520
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2521
			'readonly' => true,
2522
			'value'    => $jetpack_client_id,
2523
		);
2524
		return $options;
2525
	}
2526
2527
	/**
2528
	 * Resets the saved authentication state in between testing requests.
2529
	 */
2530
	public function reset_saved_auth_state() {
2531
		$this->xmlrpc_verification = null;
2532
	}
2533
2534
	/**
2535
	 * Sign a user role with the master access token.
2536
	 * If not specified, will default to the current user.
2537
	 *
2538
	 * @access public
2539
	 *
2540
	 * @param string $role    User role.
2541
	 * @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...
2542
	 * @return string Signed user role.
2543
	 */
2544
	public function sign_role( $role, $user_id = null ) {
2545
		if ( empty( $user_id ) ) {
2546
			$user_id = (int) get_current_user_id();
2547
		}
2548
2549
		if ( ! $user_id ) {
2550
			return false;
2551
		}
2552
2553
		$token = $this->get_access_token();
2554
		if ( ! $token || is_wp_error( $token ) ) {
2555
			return false;
2556
		}
2557
2558
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2559
	}
2560
2561
	/**
2562
	 * Set the plugin instance.
2563
	 *
2564
	 * @param Plugin $plugin_instance The plugin instance.
2565
	 *
2566
	 * @return $this
2567
	 */
2568
	public function set_plugin_instance( Plugin $plugin_instance ) {
2569
		$this->plugin = $plugin_instance;
2570
2571
		return $this;
2572
	}
2573
2574
	/**
2575
	 * Retrieve the plugin management object.
2576
	 *
2577
	 * @return Plugin
2578
	 */
2579
	public function get_plugin() {
2580
		return $this->plugin;
2581
	}
2582
2583
	/**
2584
	 * Get all connected plugins information, excluding those disconnected by user.
2585
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2586
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2587
	 * so please make sure not to run the method too early in the code.
2588
	 *
2589
	 * @return array|WP_Error
2590
	 */
2591
	public function get_connected_plugins() {
2592
		$maybe_plugins = Plugin_Storage::get_all( true );
2593
2594
		if ( $maybe_plugins instanceof WP_Error ) {
2595
			return $maybe_plugins;
2596
		}
2597
2598
		return $maybe_plugins;
2599
	}
2600
2601
	/**
2602
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2603
	 * Note: this method does not remove any access tokens.
2604
	 *
2605
	 * @return bool
2606
	 */
2607
	public function disable_plugin() {
2608
		if ( ! $this->plugin ) {
2609
			return false;
2610
		}
2611
2612
		return $this->plugin->disable();
2613
	}
2614
2615
	/**
2616
	 * Force plugin reconnect after user-initiated disconnect.
2617
	 * After its called, the plugin will be allowed to use the connection again.
2618
	 * Note: this method does not initialize access tokens.
2619
	 *
2620
	 * @return bool
2621
	 */
2622
	public function enable_plugin() {
2623
		if ( ! $this->plugin ) {
2624
			return false;
2625
		}
2626
2627
		return $this->plugin->enable();
2628
	}
2629
2630
	/**
2631
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2632
	 * If no plugin slug was passed into the constructor, always returns true.
2633
	 *
2634
	 * @return bool
2635
	 */
2636
	public function is_plugin_enabled() {
2637
		if ( ! $this->plugin ) {
2638
			return true;
2639
		}
2640
2641
		return $this->plugin->is_enabled();
2642
	}
2643
2644
	/**
2645
	 * Perform the API request to refresh the blog token.
2646
	 * Note that we are making this request on behalf of the Jetpack master user,
2647
	 * given they were (most probably) the ones that registered the site at the first place.
2648
	 *
2649
	 * @return WP_Error|bool The result of updating the blog_token option.
2650
	 */
2651
	public static function refresh_blog_token() {
2652
		( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
2653
2654
		$blog_id = Jetpack_Options::get_option( 'id' );
2655
		if ( ! $blog_id ) {
2656
			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...
2657
		}
2658
2659
		$url     = sprintf(
2660
			'%s/%s/v%s/%s',
2661
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
2662
			'wpcom',
2663
			'2',
2664
			'sites/' . $blog_id . '/jetpack-refresh-blog-token'
2665
		);
2666
		$method  = 'POST';
2667
		$user_id = get_current_user_id();
2668
2669
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2670
2671
		if ( is_wp_error( $response ) ) {
2672
			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...
2673
		}
2674
2675
		$code   = wp_remote_retrieve_response_code( $response );
2676
		$entity = wp_remote_retrieve_body( $response );
2677
2678
		if ( $entity ) {
2679
			$json = json_decode( $entity );
2680
		} else {
2681
			$json = false;
2682
		}
2683
2684 View Code Duplication
		if ( 200 !== $code ) {
2685
			if ( empty( $json->code ) ) {
2686
				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...
2687
			}
2688
2689
			/* translators: Error description string. */
2690
			$error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->message ) : '';
2691
2692
			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...
2693
		}
2694
2695
		if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
2696
			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...
2697
		}
2698
2699
		return Jetpack_Options::update_option( 'blog_token', (string) $json->jetpack_secret );
2700
	}
2701
2702
	/**
2703
	 * Disconnect the user from WP.com, and initiate the reconnect process.
2704
	 *
2705
	 * @return bool
2706
	 */
2707
	public static function refresh_user_token() {
2708
		( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2709
2710
		self::disconnect_user( null, true );
2711
2712
		return true;
2713
	}
2714
2715
	/**
2716
	 * Fetches a signed token.
2717
	 *
2718
	 * @param object $token the token.
2719
	 * @return WP_Error|string a signed token
2720
	 */
2721
	public function get_signed_token( $token ) {
2722
		if ( ! isset( $token->secret ) || empty( $token->secret ) ) {
2723
			return new WP_Error( 'invalid_token' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_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...
2724
		}
2725
2726
		list( $token_key, $token_secret ) = explode( '.', $token->secret );
2727
2728
		$token_key = sprintf(
2729
			'%s:%d:%d',
2730
			$token_key,
2731
			Constants::get_constant( 'JETPACK__API_VERSION' ),
2732
			$token->external_user_id
2733
		);
2734
2735
		$timestamp = time();
2736
2737 View Code Duplication
		if ( function_exists( 'wp_generate_password' ) ) {
2738
			$nonce = wp_generate_password( 10, false );
2739
		} else {
2740
			$nonce = substr( sha1( wp_rand( 0, 1000000 ) ), 0, 10 );
2741
		}
2742
2743
		$normalized_request_string = join(
2744
			"\n",
2745
			array(
2746
				$token_key,
2747
				$timestamp,
2748
				$nonce,
2749
			)
2750
		) . "\n";
2751
2752
		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2753
		$signature = base64_encode( hash_hmac( 'sha1', $normalized_request_string, $token_secret, true ) );
2754
2755
		$auth = array(
2756
			'token'     => $token_key,
2757
			'timestamp' => $timestamp,
2758
			'nonce'     => $nonce,
2759
			'signature' => $signature,
2760
		);
2761
2762
		$header_pieces = array();
2763
		foreach ( $auth as $key => $value ) {
2764
			$header_pieces[] = sprintf( '%s="%s"', $key, $value );
2765
		}
2766
2767
		return join( ' ', $header_pieces );
2768
	}
2769
2770
	/**
2771
	 * If connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2772
	 *
2773
	 * @param array $stats The Heartbeat stats array.
2774
	 * @return array $stats
2775
	 */
2776
	public function add_stats_to_heartbeat( $stats ) {
2777
2778
		// Connected but missing the connection owner?
2779
		if ( $this->is_connected() && $this->is_missing_connection_owner() ) {
2780
2781
			// add 1 in all cases.
2782
			$stats['missing-owner'] = array( true );
2783
2784
			$token = $this->get_access_token( self::CONNECTION_OWNER, false, false );
0 ignored issues
show
Documentation introduced by
self::CONNECTION_OWNER is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2785
2786
			// Also add the specific error.
2787
			if ( is_wp_error( $token ) ) {
2788
				$stats['missing-owner'][] = $token->get_error_code();
2789
			} elseif ( is_object( $token ) && isset( $token->secret ) ) {
2790
				$stats['missing-owner'][] = 'missing_user';
2791
			}
2792
		}
2793
2794
		if ( ! $this->is_active() ) {
2795
			return $stats;
2796
		}
2797
2798
		$active_plugins_using_connection = Plugin_Storage::get_all();
2799
		foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
2800
			if ( 'jetpack' !== $plugin_slug ) {
2801
				$stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2802
				$stats[ $stats_group ][] = $plugin_slug;
2803
			}
2804
		}
2805
2806
		return $stats;
2807
	}
2808
2809
}
2810