Completed
Push — add/identity-crisis-package ( 0e0dcc...78b820 )
by
unknown
378:08 queued 366:55
created

Manager   F

Complexity

Total Complexity 249

Size/Duplication

Total Lines 2168
Duplicated Lines 4.7 %

Coupling/Cohesion

Components 1
Dependencies 21

Importance

Changes 0
Metric Value
dl 102
loc 2168
rs 0.8
c 0
b 0
f 0
wmc 249
lcom 1
cbo 21

75 Methods

Rating   Name   Duplication   Size   Complexity  
A has_connected_owner() 0 3 1
A get_connected_user_data() 0 26 4
A get_connection_owner() 0 19 5
A is_connection_owner() 0 7 2
A connect_user() 0 20 4
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 __construct() 0 5 3
A configure() 0 35 2
C setup_xmlrpc_handlers() 0 70 11
A is_active() 0 3 1
A get_tokens() 0 3 1
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_users() 0 3 1
A is_userless() 0 3 3
A is_missing_connection_owner() 0 8 2
A is_user_connected() 0 8 3
A get_connection_owner_id() 0 4 2
A disconnect_user() 0 24 3
A api_url() 0 37 3
A xmlrpc_api_url() 0 8 1
C register() 0 143 14
B try_registration() 0 39 6
C validate_remote_register_response() 8 69 13
A add_nonce() 0 4 1
A clean_nonces() 0 4 2
B jetpack_connection_custom_caps() 9 33 8
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 generate_secrets() 0 3 1
A get_secrets() 0 4 1
A delete_secrets() 0 4 1
A delete_all_connection_tokens() 3 36 5
A disconnect_site_wpcom() 3 20 5
A remove_connection() 0 7 1
A reconnect() 0 8 1
B restore() 0 36 10
A handle_registration() 0 8 2
A validate_tokens() 0 4 1
A verify_secrets() 0 4 1
A handle_authorization() 0 3 1
A get_token() 0 3 1
B get_authorization_url() 0 86 3
C authorize() 7 91 12
A disconnect_site() 0 3 1
A sha1_base64() 0 3 1
B is_usable_domain() 39 87 7
A get_access_token() 0 4 1
A xmlrpc_methods() 0 4 2
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 3 1
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 5 1
A get_signed_token() 0 4 1
A add_stats_to_heartbeat() 0 15 5

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\Terms_Of_Service;
15
use Automattic\Jetpack\Tracking;
16
use WP_Error;
17
use WP_User;
18
19
/**
20
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
21
 * and Jetpack.
22
 */
23
class Manager {
24
	/**
25
	 * A copy of the raw POST data for signature verification purposes.
26
	 *
27
	 * @var String
28
	 */
29
	protected $raw_post_data;
30
31
	/**
32
	 * Verification data needs to be stored to properly verify everything.
33
	 *
34
	 * @var Object
35
	 */
36
	private $xmlrpc_verification = null;
37
38
	/**
39
	 * Plugin management object.
40
	 *
41
	 * @var Plugin
42
	 */
43
	private $plugin = null;
44
45
	/**
46
	 * Initialize the object.
47
	 * Make sure to call the "Configure" first.
48
	 *
49
	 * @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...
50
	 *
51
	 * @see \Automattic\Jetpack\Config
52
	 */
53
	public function __construct( $plugin_slug = null ) {
54
		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...
55
			$this->set_plugin_instance( new Plugin( $plugin_slug ) );
56
		}
57
	}
58
59
	/**
60
	 * Initializes required listeners. This is done separately from the constructors
61
	 * because some objects sometimes need to instantiate separate objects of this class.
62
	 *
63
	 * @todo Implement a proper nonce verification.
64
	 */
65
	public static function configure() {
66
		$manager = new self();
67
68
		add_filter(
69
			'jetpack_constant_default_value',
70
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
71
			10,
72
			2
73
		);
74
75
		$manager->setup_xmlrpc_handlers(
76
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
77
			$manager->has_connected_owner(),
78
			$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...
79
		);
80
81
		$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...
82
83
		if ( $manager->is_connected() ) {
84
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
85
		}
86
87
		add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
88
89
		( new Nonce_Handler() )->init_schedule();
90
91
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
92
93
		add_filter( 'map_meta_cap', array( $manager, 'jetpack_connection_custom_caps' ), 1, 4 );
94
95
		Heartbeat::init();
96
		add_filter( 'jetpack_heartbeat_stats_array', array( $manager, 'add_stats_to_heartbeat' ) );
97
98
		Webhooks::init( $manager );
99
	}
100
101
	/**
102
	 * Sets up the XMLRPC request handlers.
103
	 *
104
	 * @since 9.6.0 Deprecate $is_active param.
105
	 *
106
	 * @param array                  $request_params incoming request parameters.
107
	 * @param bool                   $has_connected_owner Whether the site has a connected owner.
108
	 * @param bool                   $is_signed whether the signature check has been successful.
109
	 * @param \Jetpack_XMLRPC_Server $xmlrpc_server (optional) an instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|\Jetpack_XMLRPC_Server?

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

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

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

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

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

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

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
149
		} else {
150
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
151
		}
152
153
		$this->require_jetpack_authentication();
154
155
		if ( $is_signed ) {
156
			// If the site is connected either at a site or user level and the request is signed, expose the methods.
157
			// The callback is responsible to determine whether the request is signed with blog or user token and act accordingly.
158
			// The actual API methods.
159
			$callback = array( $this->xmlrpc_server, 'xmlrpc_methods' );
160
161
			// Hack to preserve $HTTP_RAW_POST_DATA.
162
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
163
164
		} elseif ( $has_connected_owner && ! $is_signed ) {
165
			// The jetpack.authorize method should be available for unauthenticated users on a site with an
166
			// active Jetpack connection, so that additional users can link their account.
167
			$callback = array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' );
168
169
		} else {
170
			// Any other unsigned request should expose the bootstrap methods.
171
			$callback = array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' );
172
			new XMLRPC_Connector( $this );
173
		}
174
175
		add_filter( 'xmlrpc_methods', $callback );
176
177
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
178
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
179
		return true;
180
	}
181
182
	/**
183
	 * Initializes the REST API connector on the init hook.
184
	 */
185
	public function initialize_rest_api_registration_connector() {
186
		new REST_Connector( $this );
187
	}
188
189
	/**
190
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
191
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
192
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
193
	 * which is accessible via a different URI. Most of the below is copied directly
194
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
195
	 *
196
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
197
	 */
198
	public function alternate_xmlrpc() {
199
		// Some browser-embedded clients send cookies. We don't want them.
200
		$_COOKIE = array();
201
202
		include_once ABSPATH . 'wp-admin/includes/admin.php';
203
		include_once ABSPATH . WPINC . '/class-IXR.php';
204
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
205
206
		/**
207
		 * Filters the class used for handling XML-RPC requests.
208
		 *
209
		 * @since 3.1.0
210
		 *
211
		 * @param string $class The name of the XML-RPC server class.
212
		 */
213
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
214
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
215
216
		// Fire off the request.
217
		nocache_headers();
218
		$wp_xmlrpc_server->serve_request();
219
220
		exit;
221
	}
222
223
	/**
224
	 * Removes all XML-RPC methods that are not `jetpack.*`.
225
	 * Only used in our alternate XML-RPC endpoint, where we want to
226
	 * ensure that Core and other plugins' methods are not exposed.
227
	 *
228
	 * @param array $methods a list of registered WordPress XMLRPC methods.
229
	 * @return array filtered $methods
230
	 */
231
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
232
		$jetpack_methods = array();
233
234
		foreach ( $methods as $method => $callback ) {
235
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
236
				$jetpack_methods[ $method ] = $callback;
237
			}
238
		}
239
240
		return $jetpack_methods;
241
	}
242
243
	/**
244
	 * Removes all other authentication methods not to allow other
245
	 * methods to validate unauthenticated requests.
246
	 */
247
	public function require_jetpack_authentication() {
248
		// Don't let anyone authenticate.
249
		$_COOKIE = array();
250
		remove_all_filters( 'authenticate' );
251
		remove_all_actions( 'wp_login_failed' );
252
253
		if ( $this->is_connected() ) {
254
			// Allow Jetpack authentication.
255
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
256
		}
257
	}
258
259
	/**
260
	 * Authenticates XML-RPC and other requests from the Jetpack Server
261
	 *
262
	 * @param WP_User|Mixed $user user object if authenticated.
263
	 * @param String        $username username.
264
	 * @param String        $password password string.
265
	 * @return WP_User|Mixed authenticated user or error.
266
	 */
267
	public function authenticate_jetpack( $user, $username, $password ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
268
		if ( is_a( $user, '\\WP_User' ) ) {
269
			return $user;
270
		}
271
272
		$token_details = $this->verify_xml_rpc_signature();
273
274
		if ( ! $token_details ) {
275
			return $user;
276
		}
277
278
		if ( 'user' !== $token_details['type'] ) {
279
			return $user;
280
		}
281
282
		if ( ! $token_details['user_id'] ) {
283
			return $user;
284
		}
285
286
		nocache_headers();
287
288
		return new \WP_User( $token_details['user_id'] );
289
	}
290
291
	/**
292
	 * Verifies the signature of the current request.
293
	 *
294
	 * @return false|array
295
	 */
296
	public function verify_xml_rpc_signature() {
297
		if ( is_null( $this->xmlrpc_verification ) ) {
298
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
299
300
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
301
				/**
302
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
303
				 *
304
				 * @since 7.5.0
305
				 *
306
				 * @param WP_Error $signature_verification_error The verification error
307
				 */
308
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
309
310
				Error_Handler::get_instance()->report_error( $this->xmlrpc_verification );
311
312
			}
313
		}
314
315
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
316
	}
317
318
	/**
319
	 * Verifies the signature of the current request.
320
	 *
321
	 * This function has side effects and should not be used. Instead,
322
	 * use the memoized version `->verify_xml_rpc_signature()`.
323
	 *
324
	 * @internal
325
	 * @todo Refactor to use proper nonce verification.
326
	 */
327
	private function internal_verify_xml_rpc_signature() {
328
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
329
		// It's not for us.
330
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
331
			return false;
332
		}
333
334
		$signature_details = array(
335
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
336
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
337
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
338
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
339
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
340
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
341
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
342
		);
343
344
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
345
		@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...
346
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
347
348
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
349
350
		if (
351
			empty( $token_key )
352
		||
353
			empty( $version ) || (string) $jetpack_api_version !== $version ) {
354
			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...
355
		}
356
357
		if ( '0' === $user_id ) {
358
			$token_type = 'blog';
359
			$user_id    = 0;
360
		} else {
361
			$token_type = 'user';
362
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
363
				return new \WP_Error(
364
					'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...
365
					'Malformed user_id in request',
366
					compact( 'signature_details' )
367
				);
368
			}
369
			$user_id = (int) $user_id;
370
371
			$user = new \WP_User( $user_id );
372
			if ( ! $user || ! $user->exists() ) {
373
				return new \WP_Error(
374
					'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...
375
					sprintf( 'User %d does not exist', $user_id ),
376
					compact( 'signature_details' )
377
				);
378
			}
379
		}
380
381
		$token = $this->get_tokens()->get_access_token( $user_id, $token_key, false );
382
		if ( is_wp_error( $token ) ) {
383
			$token->add_data( compact( 'signature_details' ) );
384
			return $token;
385
		} elseif ( ! $token ) {
386
			return new \WP_Error(
387
				'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...
388
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
389
				compact( 'signature_details' )
390
			);
391
		}
392
393
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
394
		// phpcs:disable WordPress.Security.NonceVerification.Missing
395
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
396
			$post_data   = $_POST;
397
			$file_hashes = array();
398
			foreach ( $post_data as $post_data_key => $post_data_value ) {
399
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
400
					continue;
401
				}
402
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
403
				$file_hashes[ $post_data_key ] = $post_data_value;
404
			}
405
406
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
407
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
408
				$post_data[ $post_data_key ] = $post_data_value;
409
			}
410
411
			ksort( $post_data );
412
413
			$body = http_build_query( stripslashes_deep( $post_data ) );
414
		} elseif ( is_null( $this->raw_post_data ) ) {
415
			$body = file_get_contents( 'php://input' );
416
		} else {
417
			$body = null;
418
		}
419
		// phpcs:enable
420
421
		$signature = $jetpack_signature->sign_current_request(
422
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
423
		);
424
425
		$signature_details['url'] = $jetpack_signature->current_request_url;
426
427
		if ( ! $signature ) {
428
			return new \WP_Error(
429
				'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...
430
				'Unknown signature error',
431
				compact( 'signature_details' )
432
			);
433
		} elseif ( is_wp_error( $signature ) ) {
434
			return $signature;
435
		}
436
437
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
438
		$timestamp = (int) $_GET['timestamp'];
439
		$nonce     = stripslashes( (string) $_GET['nonce'] );
440
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
441
442
		// Use up the nonce regardless of whether the signature matches.
443
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
444
			return new \WP_Error(
445
				'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...
446
				'Could not add nonce',
447
				compact( 'signature_details' )
448
			);
449
		}
450
451
		// Be careful about what you do with this debugging data.
452
		// If a malicious requester has access to the expected signature,
453
		// bad things might be possible.
454
		$signature_details['expected'] = $signature;
455
456
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
457
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
458
			return new \WP_Error(
459
				'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...
460
				'Signature mismatch',
461
				compact( 'signature_details' )
462
			);
463
		}
464
465
		/**
466
		 * Action for additional token checking.
467
		 *
468
		 * @since 7.7.0
469
		 *
470
		 * @param array $post_data request data.
471
		 * @param array $token_data token data.
472
		 */
473
		return apply_filters(
474
			'jetpack_signature_check_token',
475
			array(
476
				'type'      => $token_type,
477
				'token_key' => $token_key,
478
				'user_id'   => $token->external_user_id,
479
			),
480
			$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...
481
			$this->raw_post_data
482
		);
483
	}
484
485
	/**
486
	 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI.
487
	 *
488
	 * This method is deprecated since Jetpack 9.6.0. Please use has_connected_owner instead.
489
	 *
490
	 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
491
	 *
492
	 * @deprecated 9.6.0
493
	 * @see Manager::has_connected_owner
494
	 * @return Boolean is the site connected?
495
	 */
496
	public function is_active() {
497
		return (bool) $this->get_tokens()->get_access_token( true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

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

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
648
			$user_id = get_current_user_id();
649
		}
650
651
		$transient_key    = "jetpack_connected_user_data_$user_id";
652
		$cached_user_data = get_transient( $transient_key );
653
654
		if ( $cached_user_data ) {
655
			return $cached_user_data;
656
		}
657
658
		$xml = new \Jetpack_IXR_Client(
659
			array(
660
				'user_id' => $user_id,
661
			)
662
		);
663
		$xml->query( 'wpcom.getUser' );
664
		if ( ! $xml->isError() ) {
665
			$user_data = $xml->getResponse();
666
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
667
			return $user_data;
668
		}
669
670
		return false;
671
	}
672
673
	/**
674
	 * Returns a user object of the connection owner.
675
	 *
676
	 * @return WP_User|false False if no connection owner found.
677
	 */
678
	public function get_connection_owner() {
679
680
		$user_id = \Jetpack_Options::get_option( 'master_user' );
681
682
		if ( ! $user_id ) {
683
			return false;
684
		}
685
686
		// Make sure user is connected.
687
		$user_token = $this->get_tokens()->get_access_token( $user_id );
688
689
		$connection_owner = false;
690
691
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
692
			$connection_owner = get_userdata( $user_token->external_user_id );
693
		}
694
695
		return $connection_owner;
696
	}
697
698
	/**
699
	 * Returns true if the provided user is the Jetpack connection owner.
700
	 * If user ID is not specified, the current user will be used.
701
	 *
702
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
703
	 * @return Boolean True the user the connection owner, false otherwise.
704
	 */
705
	public function is_connection_owner( $user_id = false ) {
706
		if ( ! $user_id ) {
707
			$user_id = get_current_user_id();
708
		}
709
710
		return ( (int) $user_id ) === $this->get_connection_owner_id();
711
	}
712
713
	/**
714
	 * Connects the user with a specified ID to a WordPress.com user using the
715
	 * remote login flow.
716
	 *
717
	 * @access public
718
	 *
719
	 * @param Integer $user_id (optional) the user identifier, defaults to current user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
726
		if ( null === $user_id ) {
727
			$user = wp_get_current_user();
728
		} else {
729
			$user = get_user_by( 'ID', $user_id );
730
		}
731
732
		if ( empty( $user ) ) {
733
			return new \WP_Error( 'user_not_found', 'Attempting to connect a non-existent user.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_not_found'.

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

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

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

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

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

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

Loading history...
1628
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1629
				'auth_type'     => $auth_type,
1630
				'secret'        => $secrets['secret_1'],
1631
				'blogname'      => get_option( 'blogname' ),
1632
				'site_url'      => site_url(),
1633
				'home_url'      => home_url(),
1634
				'site_icon'     => get_site_icon_url(),
1635
				'site_lang'     => get_locale(),
1636
				'site_created'  => $this->get_assumed_site_creation_date(),
1637
			)
1638
		);
1639
1640
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1641
1642
		$api_url = $this->api_url( 'authorize' );
1643
1644
		return add_query_arg( $body, $api_url );
1645
	}
1646
1647
	/**
1648
	 * Authorizes the user by obtaining and storing the user token.
1649
	 *
1650
	 * @param array $data The request data.
1651
	 * @return string|\WP_Error Returns a string on success.
1652
	 *                          Returns a \WP_Error on failure.
1653
	 */
1654
	public function authorize( $data = array() ) {
1655
		/**
1656
		 * Action fired when user authorization starts.
1657
		 *
1658
		 * @since 8.0.0
1659
		 */
1660
		do_action( 'jetpack_authorize_starting' );
1661
1662
		$roles = new Roles();
1663
		$role  = $roles->translate_current_user_to_role();
1664
1665
		if ( ! $role ) {
1666
			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...
1667
		}
1668
1669
		$cap = $roles->translate_role_to_cap( $role );
1670
		if ( ! $cap ) {
1671
			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...
1672
		}
1673
1674
		if ( ! empty( $data['error'] ) ) {
1675
			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...
1676
		}
1677
1678
		if ( ! isset( $data['state'] ) ) {
1679
			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...
1680
		}
1681
1682
		if ( ! ctype_digit( $data['state'] ) ) {
1683
			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...
1684
		}
1685
1686
		$current_user_id = get_current_user_id();
1687
		if ( $current_user_id !== (int) $data['state'] ) {
1688
			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...
1689
		}
1690
1691
		if ( empty( $data['code'] ) ) {
1692
			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...
1693
		}
1694
1695
		$token = $this->get_tokens()->get( $data, $this->api_url( 'token' ) );
1696
1697 View Code Duplication
		if ( is_wp_error( $token ) ) {
1698
			$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...
1699
			if ( empty( $code ) ) {
1700
				$code = 'invalid_token';
1701
			}
1702
			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...
1703
		}
1704
1705
		if ( ! $token ) {
1706
			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...
1707
		}
1708
1709
		$is_connection_owner = ! $this->has_connected_owner();
1710
1711
		$this->get_tokens()->update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_connection_owner );
1712
1713
		/**
1714
		 * Fires after user has successfully received an auth token.
1715
		 *
1716
		 * @since 3.9.0
1717
		 */
1718
		do_action( 'jetpack_user_authorized' );
1719
1720
		if ( ! $is_connection_owner ) {
1721
			/**
1722
			 * Action fired when a secondary user has been authorized.
1723
			 *
1724
			 * @since 8.0.0
1725
			 */
1726
			do_action( 'jetpack_authorize_ending_linked' );
1727
			return 'linked';
1728
		}
1729
1730
		/**
1731
		 * Action fired when the master user has been authorized.
1732
		 *
1733
		 * @since 8.0.0
1734
		 *
1735
		 * @param array $data The request data.
1736
		 */
1737
		do_action( 'jetpack_authorize_ending_authorized', $data );
1738
1739
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
1740
1741
		( new Nonce_Handler() )->reschedule();
1742
1743
		return 'authorized';
1744
	}
1745
1746
	/**
1747
	 * Disconnects from the Jetpack servers.
1748
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1749
	 */
1750
	public function disconnect_site() {
1751
1752
	}
1753
1754
	/**
1755
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1756
	 *
1757
	 * @param string $text The string to hash.
1758
	 * @return string
1759
	 */
1760
	public function sha1_base64( $text ) {
1761
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1762
	}
1763
1764
	/**
1765
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1766
	 *
1767
	 * @param string $domain The domain to check.
1768
	 *
1769
	 * @return bool|WP_Error
1770
	 */
1771
	public function is_usable_domain( $domain ) {
1772
1773
		// If it's empty, just fail out.
1774
		if ( ! $domain ) {
1775
			return new \WP_Error(
1776
				'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...
1777
				/* translators: %1$s is a domain name. */
1778
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1779
			);
1780
		}
1781
1782
		/**
1783
		 * Skips the usuable domain check when connecting a site.
1784
		 *
1785
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1786
		 *
1787
		 * @since 4.1.0
1788
		 *
1789
		 * @param bool If the check should be skipped. Default false.
1790
		 */
1791
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1792
			return true;
1793
		}
1794
1795
		// None of the explicit localhosts.
1796
		$forbidden_domains = array(
1797
			'wordpress.com',
1798
			'localhost',
1799
			'localhost.localdomain',
1800
			'127.0.0.1',
1801
			'local.wordpress.test',         // VVV pattern.
1802
			'local.wordpress-trunk.test',   // VVV pattern.
1803
			'src.wordpress-develop.test',   // VVV pattern.
1804
			'build.wordpress-develop.test', // VVV pattern.
1805
		);
1806 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1807
			return new \WP_Error(
1808
				'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...
1809
				sprintf(
1810
					/* translators: %1$s is a domain name. */
1811
					__(
1812
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1813
						'jetpack'
1814
					),
1815
					$domain
1816
				)
1817
			);
1818
		}
1819
1820
		// No .test or .local domains.
1821 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1822
			return new \WP_Error(
1823
				'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...
1824
				sprintf(
1825
					/* translators: %1$s is a domain name. */
1826
					__(
1827
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1828
						'jetpack'
1829
					),
1830
					$domain
1831
				)
1832
			);
1833
		}
1834
1835
		// No WPCOM subdomains.
1836 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1837
			return new \WP_Error(
1838
				'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...
1839
				sprintf(
1840
					/* translators: %1$s is a domain name. */
1841
					__(
1842
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1843
						'jetpack'
1844
					),
1845
					$domain
1846
				)
1847
			);
1848
		}
1849
1850
		// If PHP was compiled without support for the Filter module (very edge case).
1851
		if ( ! function_exists( 'filter_var' ) ) {
1852
			// Just pass back true for now, and let wpcom sort it out.
1853
			return true;
1854
		}
1855
1856
		return true;
1857
	}
1858
1859
	/**
1860
	 * Gets the requested token.
1861
	 *
1862
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_access_token() instead.
1863
	 *
1864
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1865
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1866
	 * @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.
1867
	 *
1868
	 * @return object|false
1869
	 *
1870
	 * @see $this->get_tokens()->get_access_token()
1871
	 */
1872
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1873
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_access_token' );
1874
		return $this->get_tokens()->get_access_token( $user_id, $token_key, $suppress_errors );
1875
	}
1876
1877
	/**
1878
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
1879
	 * since it is passed by reference to various methods.
1880
	 * Capture it here so we can verify the signature later.
1881
	 *
1882
	 * @param array $methods an array of available XMLRPC methods.
1883
	 * @return array the same array, since this method doesn't add or remove anything.
1884
	 */
1885
	public function xmlrpc_methods( $methods ) {
1886
		$this->raw_post_data = isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ? $GLOBALS['HTTP_RAW_POST_DATA'] : null;
1887
		return $methods;
1888
	}
1889
1890
	/**
1891
	 * Resets the raw post data parameter for testing purposes.
1892
	 */
1893
	public function reset_raw_post_data() {
1894
		$this->raw_post_data = null;
1895
	}
1896
1897
	/**
1898
	 * Registering an additional method.
1899
	 *
1900
	 * @param array $methods an array of available XMLRPC methods.
1901
	 * @return array the amended array in case the method is added.
1902
	 */
1903
	public function public_xmlrpc_methods( $methods ) {
1904
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
1905
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
1906
		}
1907
		return $methods;
1908
	}
1909
1910
	/**
1911
	 * Handles a getOptions XMLRPC method call.
1912
	 *
1913
	 * @param array $args method call arguments.
1914
	 * @return an amended XMLRPC server options array.
1915
	 */
1916
	public function jetpack_get_options( $args ) {
1917
		global $wp_xmlrpc_server;
1918
1919
		$wp_xmlrpc_server->escape( $args );
1920
1921
		$username = $args[1];
1922
		$password = $args[2];
1923
1924
		$user = $wp_xmlrpc_server->login( $username, $password );
1925
		if ( ! $user ) {
1926
			return $wp_xmlrpc_server->error;
1927
		}
1928
1929
		$options   = array();
1930
		$user_data = $this->get_connected_user_data();
1931
		if ( is_array( $user_data ) ) {
1932
			$options['jetpack_user_id']         = array(
1933
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
1934
				'readonly' => true,
1935
				'value'    => $user_data['ID'],
1936
			);
1937
			$options['jetpack_user_login']      = array(
1938
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
1939
				'readonly' => true,
1940
				'value'    => $user_data['login'],
1941
			);
1942
			$options['jetpack_user_email']      = array(
1943
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
1944
				'readonly' => true,
1945
				'value'    => $user_data['email'],
1946
			);
1947
			$options['jetpack_user_site_count'] = array(
1948
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
1949
				'readonly' => true,
1950
				'value'    => $user_data['site_count'],
1951
			);
1952
		}
1953
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
1954
		$args                           = stripslashes_deep( $args );
1955
		return $wp_xmlrpc_server->wp_getOptions( $args );
1956
	}
1957
1958
	/**
1959
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
1960
	 *
1961
	 * @param array $options standard Core options.
1962
	 * @return array amended options.
1963
	 */
1964
	public function xmlrpc_options( $options ) {
1965
		$jetpack_client_id = false;
1966
		if ( $this->is_connected() ) {
1967
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
1968
		}
1969
		$options['jetpack_version'] = array(
1970
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
1971
			'readonly' => true,
1972
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
1973
		);
1974
1975
		$options['jetpack_client_id'] = array(
1976
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
1977
			'readonly' => true,
1978
			'value'    => $jetpack_client_id,
1979
		);
1980
		return $options;
1981
	}
1982
1983
	/**
1984
	 * Resets the saved authentication state in between testing requests.
1985
	 */
1986
	public function reset_saved_auth_state() {
1987
		$this->xmlrpc_verification = null;
1988
	}
1989
1990
	/**
1991
	 * Sign a user role with the master access token.
1992
	 * If not specified, will default to the current user.
1993
	 *
1994
	 * @access public
1995
	 *
1996
	 * @param string $role    User role.
1997
	 * @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...
1998
	 * @return string Signed user role.
1999
	 */
2000
	public function sign_role( $role, $user_id = null ) {
2001
		return $this->get_tokens()->sign_role( $role, $user_id );
2002
	}
2003
2004
	/**
2005
	 * Set the plugin instance.
2006
	 *
2007
	 * @param Plugin $plugin_instance The plugin instance.
2008
	 *
2009
	 * @return $this
2010
	 */
2011
	public function set_plugin_instance( Plugin $plugin_instance ) {
2012
		$this->plugin = $plugin_instance;
2013
2014
		return $this;
2015
	}
2016
2017
	/**
2018
	 * Retrieve the plugin management object.
2019
	 *
2020
	 * @return Plugin|null
2021
	 */
2022
	public function get_plugin() {
2023
		return $this->plugin;
2024
	}
2025
2026
	/**
2027
	 * Get all connected plugins information, excluding those disconnected by user.
2028
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2029
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2030
	 * so please make sure not to run the method too early in the code.
2031
	 *
2032
	 * @return array|WP_Error
2033
	 */
2034
	public function get_connected_plugins() {
2035
		$maybe_plugins = Plugin_Storage::get_all( true );
2036
2037
		if ( $maybe_plugins instanceof WP_Error ) {
2038
			return $maybe_plugins;
2039
		}
2040
2041
		return $maybe_plugins;
2042
	}
2043
2044
	/**
2045
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2046
	 * Note: this method does not remove any access tokens.
2047
	 *
2048
	 * @return bool
2049
	 */
2050
	public function disable_plugin() {
2051
		if ( ! $this->plugin ) {
2052
			return false;
2053
		}
2054
2055
		return $this->plugin->disable();
2056
	}
2057
2058
	/**
2059
	 * Force plugin reconnect after user-initiated disconnect.
2060
	 * After its called, the plugin will be allowed to use the connection again.
2061
	 * Note: this method does not initialize access tokens.
2062
	 *
2063
	 * @return bool
2064
	 */
2065
	public function enable_plugin() {
2066
		if ( ! $this->plugin ) {
2067
			return false;
2068
		}
2069
2070
		return $this->plugin->enable();
2071
	}
2072
2073
	/**
2074
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2075
	 * If no plugin slug was passed into the constructor, always returns true.
2076
	 *
2077
	 * @return bool
2078
	 */
2079
	public function is_plugin_enabled() {
2080
		if ( ! $this->plugin ) {
2081
			return true;
2082
		}
2083
2084
		return $this->plugin->is_enabled();
2085
	}
2086
2087
	/**
2088
	 * Perform the API request to refresh the blog token.
2089
	 * Note that we are making this request on behalf of the Jetpack master user,
2090
	 * given they were (most probably) the ones that registered the site at the first place.
2091
	 *
2092
	 * @return WP_Error|bool The result of updating the blog_token option.
2093
	 */
2094
	public function refresh_blog_token() {
2095
		( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
2096
2097
		$blog_id = \Jetpack_Options::get_option( 'id' );
2098
		if ( ! $blog_id ) {
2099
			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...
2100
		}
2101
2102
		$url     = sprintf(
2103
			'%s/%s/v%s/%s',
2104
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
2105
			'wpcom',
2106
			'2',
2107
			'sites/' . $blog_id . '/jetpack-refresh-blog-token'
2108
		);
2109
		$method  = 'POST';
2110
		$user_id = get_current_user_id();
2111
2112
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2113
2114
		if ( is_wp_error( $response ) ) {
2115
			return new WP_Error( 'refresh_blog_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 '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...
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...
2116
		}
2117
2118
		$code   = wp_remote_retrieve_response_code( $response );
2119
		$entity = wp_remote_retrieve_body( $response );
2120
2121
		if ( $entity ) {
2122
			$json = json_decode( $entity );
2123
		} else {
2124
			$json = false;
2125
		}
2126
2127 View Code Duplication
		if ( 200 !== $code ) {
2128
			if ( empty( $json->code ) ) {
2129
				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...
2130
			}
2131
2132
			/* translators: Error description string. */
2133
			$error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->message ) : '';
2134
2135
			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...
2136
		}
2137
2138
		if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
2139
			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...
2140
		}
2141
2142
		return $this->get_tokens()->update_blog_token( (string) $json->jetpack_secret );
2143
	}
2144
2145
	/**
2146
	 * Disconnect the user from WP.com, and initiate the reconnect process.
2147
	 *
2148
	 * @return bool
2149
	 */
2150
	public function refresh_user_token() {
2151
		( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2152
		$this->disconnect_user( null, true );
2153
		return true;
2154
	}
2155
2156
	/**
2157
	 * Fetches a signed token.
2158
	 *
2159
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Tokens->get_signed_token() instead.
2160
	 *
2161
	 * @param object $token the token.
2162
	 * @return WP_Error|string a signed token
2163
	 */
2164
	public function get_signed_token( $token ) {
2165
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->get_signed_token' );
2166
		return $this->get_tokens()->get_signed_token( $token );
2167
	}
2168
2169
	/**
2170
	 * If the site-level connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2171
	 *
2172
	 * @param array $stats The Heartbeat stats array.
2173
	 * @return array $stats
2174
	 */
2175
	public function add_stats_to_heartbeat( $stats ) {
2176
2177
		if ( ! $this->is_connected() ) {
2178
			return $stats;
2179
		}
2180
2181
		$active_plugins_using_connection = Plugin_Storage::get_all();
2182
		foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
2183
			if ( 'jetpack' !== $plugin_slug ) {
2184
				$stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2185
				$stats[ $stats_group ][] = $plugin_slug;
2186
			}
2187
		}
2188
		return $stats;
2189
	}
2190
}
2191