Completed
Push — add/connection-package-json-ap... ( 457d59 )
by Marin
14:50 queued 07:14
created

Manager   F

Complexity

Total Complexity 233

Size/Duplication

Total Lines 1863
Duplicated Lines 6.33 %

Coupling/Cohesion

Components 4
Dependencies 10

Importance

Changes 0
Metric Value
dl 118
loc 1863
rs 0.8
c 0
b 0
f 0
wmc 233
lcom 4
cbo 10

54 Methods

Rating   Name   Duplication   Size   Complexity  
B init() 0 30 7
C setup_xmlrpc_handlers() 0 78 12
A initialize_rest_api_registration_connector() 0 3 1
A alternate_xmlrpc() 0 35 2
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 26 4
F internal_verify_xml_rpc_signature() 0 149 28
A is_active() 0 3 1
A is_user_connected() 0 8 3
A get_connected_user_data() 27 27 4
A is_connection_owner() 0 9 5
A disconnect_user() 0 3 1
A initialize_server() 0 3 1
A require_authentication() 0 3 1
A verify_signature() 0 3 1
A api_url() 0 9 3
C register() 0 135 12
C validate_remote_register_response() 0 69 13
A add_nonce() 0 38 3
A clean_nonces() 0 21 4
A get_max_execution_time() 0 9 2
A set_min_time_limit() 8 8 2
A get_assumed_site_creation_date() 31 31 2
A apply_activation_source_to_args() 13 13 3
A get_secret_callable() 0 12 2
A generate_secrets() 0 28 3
A get_secrets() 0 18 3
A delete_secrets() 0 11 2
A handle_registration() 0 8 2
C verify_secrets() 0 116 12
A handle_authorization() 0 3 1
A build_connect_url() 0 3 1
A disconnect_site() 0 3 1
A sha1_base64() 0 3 1
B is_usable_domain() 39 87 7
F get_access_token() 0 86 28
A xmlrpc_methods() 0 4 1
A reset_raw_post_data() 0 3 1
A public_xmlrpc_methods() 0 6 2
A jetpack_getOptions() 0 41 3
A xmlrpc_options() 0 18 2
A reset_saved_auth_state() 0 3 1
A login_form_json_api_authorization() 0 9 1
A post_login_form_to_signed_url() 0 14 5
A preserve_action_in_login_form_for_json_api_authorization() 0 4 1
A store_json_api_authorization_token() 0 6 1
A allow_wpcom_public_api_domain() 0 4 1
A is_redirect_encoded() 0 3 1
A allow_wpcom_environments() 0 7 1
A add_token_to_login_redirect_json_api_authorization() 0 12 1
F verify_json_api_authorization_request() 0 119 22
A login_message_json_api_authorization() 0 7 1

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 jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Tracking;
12
13
/**
14
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
15
 * and Jetpack.
16
 */
17
class Manager implements Manager_Interface {
18
19
	const SECRETS_MISSING        = 'secrets_missing';
20
	const SECRETS_EXPIRED        = 'secrets_expired';
21
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
22
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
23
	const JETPACK_MASTER_USER    = true;
24
25
	/**
26
	 * The procedure that should be run to generate secrets.
27
	 *
28
	 * @var Callable
29
	 */
30
	protected $secret_callable;
31
32
	/**
33
	 * A copy of the raw POST data for signature verification purposes.
34
	 *
35
	 * @var String
36
	 */
37
	protected $raw_post_data;
38
39
	/**
40
	 * Verification data needs to be stored to properly verify everything.
41
	 *
42
	 * @var Object
43
	 */
44
	private $xmlrpc_verification = null;
45
46
	/**
47
	 * Initializes required listeners. This is done separately from the constructors
48
	 * because some objects sometimes need to instantiate separate objects of this class.
49
	 *
50
	 * @todo Implement a proper nonce verification.
51
	 */
52
	public function init() {
53
54
		$is_jetpack_xmlrpc_request = $this->setup_xmlrpc_handlers(
55
			$_GET,
56
			$this->is_active(),
57
			$this->verify_xml_rpc_signature()
0 ignored issues
show
Bug introduced by
It seems like $this->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...
58
		);
59
60
		// All the XMLRPC functionality has been moved into setup_xmlrpc_handlers.
61
		if (
62
			! $is_jetpack_xmlrpc_request
63
			&& is_admin()
64
			&& isset( $_POST['action'] ) // phpcs:ignore WordPress.Security.NonceVerification
65
			&& (
66
				'jetpack_upload_file' === $_POST['action']  // phpcs:ignore WordPress.Security.NonceVerification
67
				|| 'jetpack_update_file' === $_POST['action']  // phpcs:ignore WordPress.Security.NonceVerification
68
			)
69
		) {
70
			$this->require_jetpack_authentication();
71
			$this->add_remote_request_handlers();
0 ignored issues
show
Bug introduced by
The method add_remote_request_handlers() does not seem to exist on object<Automattic\Jetpack\Connection\Manager>.

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...
72
			return;
73
		}
74
75
		if ( $this->is_active() ) {
76
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
77
			add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
78
		} else {
79
			add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
80
		}
81
	}
82
83
	/**
84
	 * Sets up the XMLRPC request handlers.
85
	 *
86
	 * @param Array                  $request_params incoming request parameters.
87
	 * @param Boolean                $is_active whether the connection is currently active.
88
	 * @param Boolean                $is_signed whether the signature check has been successful.
89
	 * @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...
90
	 */
91
	public function setup_xmlrpc_handlers(
92
		$request_params,
93
		$is_active,
94
		$is_signed,
95
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
96
	) {
97
		if (
98
			! isset( $request_params['for'] )
99
			|| 'jetpack' !== $request_params['for']
100
		) {
101
			return false;
102
		}
103
104
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
105
		if (
106
			isset( $request_params['jetpack'] )
107
			&& 'comms' === $request_params['jetpack']
108
		) {
109
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
110
				// Use the real constant here for WordPress' sake.
111
				define( 'XMLRPC_REQUEST', true );
112
			}
113
114
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
115
116
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
117
		}
118
119
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
120
			return false;
121
		}
122
		// Display errors can cause the XML to be not well formed.
123
		@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...
124
125
		if ( $xmlrpc_server ) {
126
			$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...
127
		} else {
128
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
129
		}
130
131
		$this->require_jetpack_authentication();
132
133
		if ( $is_active ) {
134
			// Hack to preserve $HTTP_RAW_POST_DATA.
135
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
136
137
			if ( $is_signed ) {
138
				// The actual API methods.
139
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
140
			} else {
141
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
142
				// active Jetpack connection, so that additional users can link their account.
143
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
144
			}
145
		} else {
146
			// The bootstrap API methods.
147
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
148
149
			if ( $is_signed ) {
150
				// The jetpack Provision method is available for blog-token-signed requests.
151
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
152
			} else {
153
				new XMLRPC_Connector( $this );
154
			}
155
		}
156
157
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
158
159
		add_action( 'jetpack_clean_nonces', array( $this, 'clean_nonces' ) );
160
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
161
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
162
		}
163
164
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
165
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
166
167
		return true;
168
	}
169
170
	/**
171
	 * Initializes the REST API connector on the init hook.
172
	 */
173
	public function initialize_rest_api_registration_connector() {
174
		new REST_Connector( $this );
175
	}
176
177
	/**
178
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
179
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
180
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
181
	 * which is accessible via a different URI. Most of the below is copied directly
182
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
183
	 *
184
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
185
	 */
186
	public function alternate_xmlrpc() {
187
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
188
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
189
		global $HTTP_RAW_POST_DATA;
190
191
		// Some browser-embedded clients send cookies. We don't want them.
192
		$_COOKIE = array();
193
194
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
195
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
196
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
197
		}
198
199
		// phpcs:enable
200
201
		include_once ABSPATH . 'wp-admin/includes/admin.php';
202
		include_once ABSPATH . WPINC . '/class-IXR.php';
203
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
204
205
		/**
206
		 * Filters the class used for handling XML-RPC requests.
207
		 *
208
		 * @since 3.1.0
209
		 *
210
		 * @param string $class The name of the XML-RPC server class.
211
		 */
212
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
213
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
214
215
		// Fire off the request.
216
		nocache_headers();
217
		$wp_xmlrpc_server->serve_request();
218
219
		exit;
220
	}
221
222
	/**
223
	 * Removes all XML-RPC methods that are not `jetpack.*`.
224
	 * Only used in our alternate XML-RPC endpoint, where we want to
225
	 * ensure that Core and other plugins' methods are not exposed.
226
	 *
227
	 * @param array $methods a list of registered WordPress XMLRPC methods.
228
	 * @return array filtered $methods
229
	 */
230
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
231
		$jetpack_methods = array();
232
233
		foreach ( $methods as $method => $callback ) {
234
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
235
				$jetpack_methods[ $method ] = $callback;
236
			}
237
		}
238
239
		return $jetpack_methods;
240
	}
241
242
	/**
243
	 * Removes all other authentication methods not to allow other
244
	 * methods to validate unauthenticated requests.
245
	 */
246
	public function require_jetpack_authentication() {
247
		// Don't let anyone authenticate.
248
		$_COOKIE = array();
249
		remove_all_filters( 'authenticate' );
250
		remove_all_actions( 'wp_login_failed' );
251
252
		if ( $this->is_active() ) {
253
			// Allow Jetpack authentication.
254
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
255
		}
256
	}
257
258
	/**
259
	 * Authenticates XML-RPC and other requests from the Jetpack Server
260
	 *
261
	 * @param WP_User|Mixed $user user object if authenticated.
262
	 * @param String        $username username.
263
	 * @param String        $password password string.
264
	 * @return WP_User|Mixed authenticated user or error.
265
	 */
266
	public function authenticate_jetpack( $user, $username, $password ) {
267
		if ( is_a( $user, '\\WP_User' ) ) {
268
			return $user;
269
		}
270
271
		$token_details = $this->verify_xml_rpc_signature();
272
273
		if ( ! $token_details ) {
274
			return $user;
275
		}
276
277
		if ( 'user' !== $token_details['type'] ) {
278
			return $user;
279
		}
280
281
		if ( ! $token_details['user_id'] ) {
282
			return $user;
283
		}
284
285
		nocache_headers();
286
287
		return new \WP_User( $token_details['user_id'] );
288
	}
289
290
	/**
291
	 * Verifies the signature of the current request.
292
	 *
293
	 * @return false|array
294
	 */
295
	public function verify_xml_rpc_signature() {
296
		if ( is_null( $this->xmlrpc_verification ) ) {
297
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
298
299
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
300
				/**
301
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
302
				 *
303
				 * Error codes:
304
				 * - malformed_token
305
				 * - malformed_user_id
306
				 * - unknown_token
307
				 * - could_not_sign
308
				 * - invalid_nonce
309
				 * - signature_mismatch
310
				 *
311
				 * @since 7.5.0
312
				 *
313
				 * @param WP_Error $signature_verification_error The verification error
314
				 */
315
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
316
			}
317
		}
318
319
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
320
	}
321
322
	/**
323
	 * Verifies the signature of the current request.
324
	 *
325
	 * This function has side effects and should not be used. Instead,
326
	 * use the memoized version `->verify_xml_rpc_signature()`.
327
	 *
328
	 * @internal
329
	 */
330
	private function internal_verify_xml_rpc_signature() {
331
		// It's not for us.
332
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
333
			return false;
334
		}
335
336
		$signature_details = array(
337
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
338
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
339
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
340
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
341
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
342
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
343
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
344
		);
345
346
		@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...
347
		if (
348
			empty( $token_key )
349
		||
350
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
351
		) {
352
			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...
353
		}
354
355
		if ( '0' === $user_id ) {
356
			$token_type = 'blog';
357
			$user_id    = 0;
358
		} else {
359
			$token_type = 'user';
360
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
361
				return new \WP_Error(
362
					'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...
363
					'Malformed user_id in request',
364
					compact( 'signature_details' )
365
				);
366
			}
367
			$user_id = (int) $user_id;
368
369
			$user = new \WP_User( $user_id );
370
			if ( ! $user || ! $user->exists() ) {
371
				return new \WP_Error(
372
					'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...
373
					sprintf( 'User %d does not exist', $user_id ),
374
					compact( 'signature_details' )
375
				);
376
			}
377
		}
378
379
		$token = $this->get_access_token( $user_id, $token_key, false );
380
		if ( is_wp_error( $token ) ) {
381
			$token->add_data( compact( 'signature_details' ) );
382
			return $token;
383
		} elseif ( ! $token ) {
384
			return new \WP_Error(
385
				'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...
386
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
387
				compact( 'signature_details' )
388
			);
389
		}
390
391
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
392
		// phpcs:disable WordPress.Security.NonceVerification.Missing
393
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
394
			$post_data   = $_POST;
395
			$file_hashes = array();
396
			foreach ( $post_data as $post_data_key => $post_data_value ) {
397
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
398
					continue;
399
				}
400
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
401
				$file_hashes[ $post_data_key ] = $post_data_value;
402
			}
403
404
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
405
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
406
				$post_data[ $post_data_key ] = $post_data_value;
407
			}
408
409
			ksort( $post_data );
410
411
			$body = http_build_query( stripslashes_deep( $post_data ) );
412
		} elseif ( is_null( $this->raw_post_data ) ) {
413
			$body = file_get_contents( 'php://input' );
414
		} else {
415
			$body = null;
416
		}
417
		// phpcs:enable
418
419
		$signature = $jetpack_signature->sign_current_request(
420
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
421
		);
422
423
		$signature_details['url'] = $jetpack_signature->current_request_url;
424
425
		if ( ! $signature ) {
426
			return new \WP_Error(
427
				'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...
428
				'Unknown signature error',
429
				compact( 'signature_details' )
430
			);
431
		} elseif ( is_wp_error( $signature ) ) {
432
			return $signature;
433
		}
434
435
		$timestamp = (int) $_GET['timestamp'];
436
		$nonce     = stripslashes( (string) $_GET['nonce'] );
437
438
		// Use up the nonce regardless of whether the signature matches.
439
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
440
			return new \WP_Error(
441
				'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...
442
				'Could not add nonce',
443
				compact( 'signature_details' )
444
			);
445
		}
446
447
		// Be careful about what you do with this debugging data.
448
		// If a malicious requester has access to the expected signature,
449
		// bad things might be possible.
450
		$signature_details['expected'] = $signature;
451
452
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
453
			return new \WP_Error(
454
				'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...
455
				'Signature mismatch',
456
				compact( 'signature_details' )
457
			);
458
		}
459
460
		/**
461
		 * Action for additional token checking.
462
		 *
463
		 * @since 7.7.0
464
		 *
465
		 * @param Array $post_data request data.
466
		 * @param Array $token_data token data.
467
		 */
468
		return apply_filters(
469
			'jetpack_signature_check_token',
470
			array(
471
				'type'      => $token_type,
472
				'token_key' => $token_key,
473
				'user_id'   => $token->external_user_id,
474
			),
475
			$token,
476
			$this->raw_post_data
477
		);
478
	}
479
480
	/**
481
	 * Returns true if the current site is connected to WordPress.com.
482
	 *
483
	 * @return Boolean is the site connected?
484
	 */
485
	public function is_active() {
486
		return (bool) $this->get_access_token( self::JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
self::JETPACK_MASTER_USER 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...
487
	}
488
489
	/**
490
	 * Returns true if the user with the specified identifier is connected to
491
	 * WordPress.com.
492
	 *
493
	 * @param Integer|Boolean $user_id the user identifier.
494
	 * @return Boolean is the user connected?
495
	 */
496
	public function is_user_connected( $user_id = false ) {
497
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
498
		if ( ! $user_id ) {
499
			return false;
500
		}
501
502
		return (bool) $this->get_access_token( $user_id );
503
	}
504
505
	/**
506
	 * Get the wpcom user data of the current|specified connected user.
507
	 *
508
	 * @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...
509
	 * @return Object the user object.
510
	 */
511 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
512
		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...
513
			$user_id = get_current_user_id();
514
		}
515
516
		$transient_key    = "jetpack_connected_user_data_$user_id";
517
		$cached_user_data = get_transient( $transient_key );
518
519
		if ( $cached_user_data ) {
520
			return $cached_user_data;
521
		}
522
523
		\Jetpack::load_xml_rpc_client();
524
		$xml = new \Jetpack_IXR_Client(
525
			array(
526
				'user_id' => $user_id,
527
			)
528
		);
529
		$xml->query( 'wpcom.getUser' );
530
		if ( ! $xml->isError() ) {
531
			$user_data = $xml->getResponse();
532
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
533
			return $user_data;
534
		}
535
536
		return false;
537
	}
538
539
	/**
540
	 * Returns true if the provided user is the Jetpack connection owner.
541
	 * If user ID is not specified, the current user will be used.
542
	 *
543
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
544
	 * @return Boolean True the user the connection owner, false otherwise.
545
	 */
546
	public function is_connection_owner( $user_id = false ) {
547
		if ( ! $user_id ) {
548
			$user_id = get_current_user_id();
549
		}
550
551
		$user_token = $this->get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
JETPACK_MASTER_USER 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...
552
553
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
554
	}
555
556
	/**
557
	 * Unlinks the current user from the linked WordPress.com user
558
	 *
559
	 * @param Integer $user_id the user identifier.
560
	 */
561
	public static function disconnect_user( $user_id ) {
562
		return $user_id;
563
	}
564
565
	/**
566
	 * Initializes a transport server, whatever it may be, saves into the object property.
567
	 * Should be changed to be protected.
568
	 */
569
	public function initialize_server() {
570
571
	}
572
573
	/**
574
	 * Checks if the current request is properly authenticated, bails if not.
575
	 * Should be changed to be protected.
576
	 */
577
	public function require_authentication() {
578
579
	}
580
581
	/**
582
	 * Verifies the correctness of the request signature.
583
	 * Should be changed to be protected.
584
	 */
585
	public function verify_signature() {
586
587
	}
588
589
	/**
590
	 * Returns the requested Jetpack API URL.
591
	 *
592
	 * @param String $relative_url the relative API path.
593
	 * @return String API URL.
594
	 */
595
	public function api_url( $relative_url ) {
596
		$api_base = Constants::get_constant( 'JETPACK__API_BASE' );
597
		$version  = Constants::get_constant( 'JETPACK__API_VERSION' );
598
599
		$api_base = $api_base ? $api_base : 'https://jetpack.wordpress.com/jetpack.';
600
		$version  = $version ? '/' . $version . '/' : '/1/';
601
602
		return rtrim( $api_base . $relative_url, '/\\' ) . $version;
603
	}
604
605
	/**
606
	 * Attempts Jetpack registration which sets up the site for connection. Should
607
	 * remain public because the call to action comes from the current site, not from
608
	 * WordPress.com.
609
	 *
610
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
611
	 * @return Integer zero on success, or a bitmask on failure.
612
	 */
613
	public function register( $api_endpoint = 'register' ) {
614
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
615
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
616
617
		if (
618
			empty( $secrets['secret_1'] ) ||
619
			empty( $secrets['secret_2'] ) ||
620
			empty( $secrets['exp'] )
621
		) {
622
			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...
623
		}
624
625
		// Better to try (and fail) to set a higher timeout than this system
626
		// supports than to have register fail for more users than it should.
627
		$timeout = $this->set_min_time_limit( 60 ) / 2;
628
629
		$gmt_offset = get_option( 'gmt_offset' );
630
		if ( ! $gmt_offset ) {
631
			$gmt_offset = 0;
632
		}
633
634
		$stats_options = get_option( 'stats_options' );
635
		$stats_id      = isset( $stats_options['blog_id'] )
636
			? $stats_options['blog_id']
637
			: null;
638
639
		/**
640
		 * Filters the request body for additional property addition.
641
		 *
642
		 * @since 7.7.0
643
		 *
644
		 * @param Array $post_data request data.
645
		 * @param Array $token_data token data.
646
		 */
647
		$body = apply_filters(
648
			'jetpack_register_request_body',
649
			array(
650
				'siteurl'         => site_url(),
651
				'home'            => home_url(),
652
				'gmt_offset'      => $gmt_offset,
653
				'timezone_string' => (string) get_option( 'timezone_string' ),
654
				'site_name'       => (string) get_option( 'blogname' ),
655
				'secret_1'        => $secrets['secret_1'],
656
				'secret_2'        => $secrets['secret_2'],
657
				'site_lang'       => get_locale(),
658
				'timeout'         => $timeout,
659
				'stats_id'        => $stats_id,
660
				'state'           => get_current_user_id(),
661
				'site_created'    => $this->get_assumed_site_creation_date(),
662
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
663
			)
664
		);
665
666
		$args = array(
667
			'method'  => 'POST',
668
			'body'    => $body,
669
			'headers' => array(
670
				'Accept' => 'application/json',
671
			),
672
			'timeout' => $timeout,
673
		);
674
675
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
676
677
		// TODO: fix URLs for bad hosts.
678
		$response = Client::_wp_remote_request(
679
			$this->api_url( $api_endpoint ),
680
			$args,
681
			true
682
		);
683
684
		// Make sure the response is valid and does not contain any Jetpack errors.
685
		$registration_details = $this->validate_remote_register_response( $response );
686
687
		if ( is_wp_error( $registration_details ) ) {
688
			return $registration_details;
689
		} elseif ( ! $registration_details ) {
690
			return new \WP_Error(
691
				'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...
692
				'Unknown error registering your Jetpack site.',
693
				wp_remote_retrieve_response_code( $response )
694
			);
695
		}
696
697
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
698
			return new \WP_Error(
699
				'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...
700
				'Unable to validate registration of your Jetpack site.',
701
				wp_remote_retrieve_response_code( $response )
702
			);
703
		}
704
705
		if ( isset( $registration_details->jetpack_public ) ) {
706
			$jetpack_public = (int) $registration_details->jetpack_public;
707
		} else {
708
			$jetpack_public = false;
709
		}
710
711
		\Jetpack_Options::update_options(
712
			array(
713
				'id'         => (int) $registration_details->jetpack_id,
714
				'blog_token' => (string) $registration_details->jetpack_secret,
715
				'public'     => $jetpack_public,
716
			)
717
		);
718
719
		/**
720
		 * Fires when a site is registered on WordPress.com.
721
		 *
722
		 * @since 3.7.0
723
		 *
724
		 * @param int $json->jetpack_id Jetpack Blog ID.
725
		 * @param string $json->jetpack_secret Jetpack Blog Token.
726
		 * @param int|bool $jetpack_public Is the site public.
727
		 */
728
		do_action(
729
			'jetpack_site_registered',
730
			$registration_details->jetpack_id,
731
			$registration_details->jetpack_secret,
732
			$jetpack_public
733
		);
734
735
		if ( isset( $registration_details->token ) ) {
736
			/**
737
			 * Fires when a user token is sent along with the registration data.
738
			 *
739
			 * @since 7.6.0
740
			 *
741
			 * @param object $token the administrator token for the newly registered site.
742
			 */
743
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
744
		}
745
746
		return true;
747
	}
748
749
	/**
750
	 * Takes the response from the Jetpack register new site endpoint and
751
	 * verifies it worked properly.
752
	 *
753
	 * @since 2.6
754
	 *
755
	 * @param Mixed $response the response object, or the error object.
756
	 * @return string|WP_Error A JSON object on success or Jetpack_Error on failures
757
	 **/
758
	protected function validate_remote_register_response( $response ) {
759
		if ( is_wp_error( $response ) ) {
760
			return new \WP_Error(
761
				'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...
762
				$response->get_error_message()
763
			);
764
		}
765
766
		$code   = wp_remote_retrieve_response_code( $response );
767
		$entity = wp_remote_retrieve_body( $response );
768
769
		if ( $entity ) {
770
			$registration_response = json_decode( $entity );
771
		} else {
772
			$registration_response = false;
773
		}
774
775
		$code_type = intval( $code / 100 );
776
		if ( 5 === $code_type ) {
777
			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...
778
		} elseif ( 408 === $code ) {
779
			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...
780
		} elseif ( ! empty( $registration_response->error ) ) {
781
			if (
782
				'xml_rpc-32700' === $registration_response->error
783
				&& ! function_exists( 'xml_parser_create' )
784
			) {
785
				$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' );
786
			} else {
787
				$error_description = isset( $registration_response->error_description )
788
					? (string) $registration_response->error_description
789
					: '';
790
			}
791
792
			return new \WP_Error(
793
				(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...
794
				$error_description,
795
				$code
796
			);
797
		} elseif ( 200 !== $code ) {
798
			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...
799
		}
800
801
		// Jetpack ID error block.
802
		if ( empty( $registration_response->jetpack_id ) ) {
803
			return new \WP_Error(
804
				'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...
805
				/* translators: %s is an error message string */
806
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
807
				$entity
808
			);
809
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
810
			return new \WP_Error(
811
				'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...
812
				/* translators: %s is an error message string */
813
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
814
				$entity
815
			);
816
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
817
			return new \WP_Error(
818
				'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...
819
				/* translators: %s is an error message string */
820
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
821
				$entity
822
			);
823
		}
824
825
		return $registration_response;
826
	}
827
828
	/**
829
	 * Adds a used nonce to a list of known nonces.
830
	 *
831
	 * @param int    $timestamp the current request timestamp.
832
	 * @param string $nonce the nonce value.
833
	 * @return bool whether the nonce is unique or not.
834
	 */
835
	public function add_nonce( $timestamp, $nonce ) {
836
		global $wpdb;
837
		static $nonces_used_this_request = array();
838
839
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
840
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
841
		}
842
843
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
844
		$timestamp = (int) $timestamp;
845
		$nonce     = esc_sql( $nonce );
846
847
		// Raw query so we can avoid races: add_option will also update.
848
		$show_errors = $wpdb->show_errors( false );
849
850
		$old_nonce = $wpdb->get_row(
851
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
852
		);
853
854
		if ( is_null( $old_nonce ) ) {
855
			$return = $wpdb->query(
856
				$wpdb->prepare(
857
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
858
					"jetpack_nonce_{$timestamp}_{$nonce}",
859
					time(),
860
					'no'
861
				)
862
			);
863
		} else {
864
			$return = false;
865
		}
866
867
		$wpdb->show_errors( $show_errors );
868
869
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
870
871
		return $return;
872
	}
873
874
	/**
875
	 * Cleans nonces that were saved when calling ::add_nonce.
876
	 *
877
	 * @todo Properly prepare the query before executing it.
878
	 *
879
	 * @param bool $all whether to clean even non-expired nonces.
880
	 */
881
	public function clean_nonces( $all = false ) {
882
		global $wpdb;
883
884
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
885
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
886
887
		if ( true !== $all ) {
888
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
889
			$sql_args[] = time() - 3600;
890
		}
891
892
		$sql .= ' ORDER BY `option_id` LIMIT 100';
893
894
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
895
896
		for ( $i = 0; $i < 1000; $i++ ) {
897
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
898
				break;
899
			}
900
		}
901
	}
902
903
	/**
904
	 * Builds the timeout limit for queries talking with the wpcom servers.
905
	 *
906
	 * Based on local php max_execution_time in php.ini
907
	 *
908
	 * @since 5.4
909
	 * @return int
910
	 **/
911
	public function get_max_execution_time() {
912
		$timeout = (int) ini_get( 'max_execution_time' );
913
914
		// Ensure exec time set in php.ini.
915
		if ( ! $timeout ) {
916
			$timeout = 30;
917
		}
918
		return $timeout;
919
	}
920
921
	/**
922
	 * Sets a minimum request timeout, and returns the current timeout
923
	 *
924
	 * @since 5.4
925
	 * @param Integer $min_timeout the minimum timeout value.
926
	 **/
927 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
928
		$timeout = $this->get_max_execution_time();
929
		if ( $timeout < $min_timeout ) {
930
			$timeout = $min_timeout;
931
			set_time_limit( $timeout );
932
		}
933
		return $timeout;
934
	}
935
936
	/**
937
	 * Get our assumed site creation date.
938
	 * Calculated based on the earlier date of either:
939
	 * - Earliest admin user registration date.
940
	 * - Earliest date of post of any post type.
941
	 *
942
	 * @since 7.2.0
943
	 *
944
	 * @return string Assumed site creation date and time.
945
	 */
946 View Code Duplication
	public function get_assumed_site_creation_date() {
947
		$earliest_registered_users  = get_users(
948
			array(
949
				'role'    => 'administrator',
950
				'orderby' => 'user_registered',
951
				'order'   => 'ASC',
952
				'fields'  => array( 'user_registered' ),
953
				'number'  => 1,
954
			)
955
		);
956
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
957
958
		$earliest_posts = get_posts(
959
			array(
960
				'posts_per_page' => 1,
961
				'post_type'      => 'any',
962
				'post_status'    => 'any',
963
				'orderby'        => 'date',
964
				'order'          => 'ASC',
965
			)
966
		);
967
968
		// If there are no posts at all, we'll count only on user registration date.
969
		if ( $earliest_posts ) {
970
			$earliest_post_date = $earliest_posts[0]->post_date;
971
		} else {
972
			$earliest_post_date = PHP_INT_MAX;
973
		}
974
975
		return min( $earliest_registration_date, $earliest_post_date );
976
	}
977
978
	/**
979
	 * Adds the activation source string as a parameter to passed arguments.
980
	 *
981
	 * @param Array $args arguments that need to have the source added.
982
	 * @return Array $amended arguments.
983
	 */
984 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
985
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
986
987
		if ( $activation_source_name ) {
988
			$args['_as'] = urlencode( $activation_source_name );
989
		}
990
991
		if ( $activation_source_keyword ) {
992
			$args['_ak'] = urlencode( $activation_source_keyword );
993
		}
994
995
		return $args;
996
	}
997
998
	/**
999
	 * Returns the callable that would be used to generate secrets.
1000
	 *
1001
	 * @return Callable a function that returns a secure string to be used as a secret.
1002
	 */
1003
	protected function get_secret_callable() {
1004
		if ( ! isset( $this->secret_callable ) ) {
1005
			/**
1006
			 * Allows modification of the callable that is used to generate connection secrets.
1007
			 *
1008
			 * @param Callable a function or method that returns a secret string.
1009
			 */
1010
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', 'wp_generate_password' );
1011
		}
1012
1013
		return $this->secret_callable;
1014
	}
1015
1016
	/**
1017
	 * Generates two secret tokens and the end of life timestamp for them.
1018
	 *
1019
	 * @param String  $action  The action name.
1020
	 * @param Integer $user_id The user identifier.
1021
	 * @param Integer $exp     Expiration time in seconds.
1022
	 */
1023
	public function generate_secrets( $action, $user_id, $exp ) {
1024
		$callable = $this->get_secret_callable();
1025
1026
		$secrets = \Jetpack_Options::get_raw_option(
1027
			self::SECRETS_OPTION_NAME,
1028
			array()
1029
		);
1030
1031
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1032
1033
		if (
1034
			isset( $secrets[ $secret_name ] ) &&
1035
			$secrets[ $secret_name ]['exp'] > time()
1036
		) {
1037
			return $secrets[ $secret_name ];
1038
		}
1039
1040
		$secret_value = array(
1041
			'secret_1' => call_user_func( $callable ),
1042
			'secret_2' => call_user_func( $callable ),
1043
			'exp'      => time() + $exp,
1044
		);
1045
1046
		$secrets[ $secret_name ] = $secret_value;
1047
1048
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1049
		return $secrets[ $secret_name ];
1050
	}
1051
1052
	/**
1053
	 * Returns two secret tokens and the end of life timestamp for them.
1054
	 *
1055
	 * @param String  $action  The action name.
1056
	 * @param Integer $user_id The user identifier.
1057
	 * @return string|array an array of secrets or an error string.
1058
	 */
1059
	public function get_secrets( $action, $user_id ) {
1060
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1061
		$secrets     = \Jetpack_Options::get_raw_option(
1062
			self::SECRETS_OPTION_NAME,
1063
			array()
1064
		);
1065
1066
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1067
			return self::SECRETS_MISSING;
1068
		}
1069
1070
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1071
			$this->delete_secrets( $action, $user_id );
1072
			return self::SECRETS_EXPIRED;
1073
		}
1074
1075
		return $secrets[ $secret_name ];
1076
	}
1077
1078
	/**
1079
	 * Deletes secret tokens in case they, for example, have expired.
1080
	 *
1081
	 * @param String  $action  The action name.
1082
	 * @param Integer $user_id The user identifier.
1083
	 */
1084
	public function delete_secrets( $action, $user_id ) {
1085
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1086
		$secrets     = \Jetpack_Options::get_raw_option(
1087
			self::SECRETS_OPTION_NAME,
1088
			array()
1089
		);
1090
		if ( isset( $secrets[ $secret_name ] ) ) {
1091
			unset( $secrets[ $secret_name ] );
1092
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1093
		}
1094
	}
1095
1096
	/**
1097
	 * Responds to a WordPress.com call to register the current site.
1098
	 * Should be changed to protected.
1099
	 *
1100
	 * @param array $registration_data Array of [ secret_1, user_id ].
1101
	 */
1102
	public function handle_registration( array $registration_data ) {
1103
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1104
		if ( empty( $registration_user_id ) ) {
1105
			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...
1106
		}
1107
1108
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1109
	}
1110
1111
	/**
1112
	 * Verify a Previously Generated Secret.
1113
	 *
1114
	 * @param string $action   The type of secret to verify.
1115
	 * @param string $secret_1 The secret string to compare to what is stored.
1116
	 * @param int    $user_id  The user ID of the owner of the secret.
1117
	 */
1118
	protected function verify_secrets( $action, $secret_1, $user_id ) {
1119
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1120
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1121
			return new \WP_Error( 'unknown_verification_action', 'Unknown Verification Action', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_verification_action'.

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

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

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

Loading history...
1122
		}
1123
1124
		$user = get_user_by( 'id', $user_id );
1125
1126
		/**
1127
		 * We've begun verifying the previously generated secret.
1128
		 *
1129
		 * @since 7.5.0
1130
		 *
1131
		 * @param string   $action The type of secret to verify.
1132
		 * @param \WP_User $user The user object.
1133
		 */
1134
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1135
1136
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1137
			/**
1138
			 * Verifying of the previously generated secret has failed.
1139
			 *
1140
			 * @since 7.5.0
1141
			 *
1142
			 * @param string    $action  The type of secret to verify.
1143
			 * @param \WP_User  $user The user object.
1144
			 * @param \WP_Error $error The error object.
1145
			 */
1146
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1147
1148
			return $error;
1149
		};
1150
1151
		$stored_secrets = $this->get_secrets( $action, $user_id );
1152
		$this->delete_secrets( $action, $user_id );
1153
1154
		if ( empty( $secret_1 ) ) {
1155
			return $return_error(
1156
				new \WP_Error(
1157
					'verify_secret_1_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secret_1_missing'.

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

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

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

Loading history...
1158
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1159
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1160
					400
1161
				)
1162
			);
1163
		} elseif ( ! is_string( $secret_1 ) ) {
1164
			return $return_error(
1165
				new \WP_Error(
1166
					'verify_secret_1_malformed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secret_1_malformed'.

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

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

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

Loading history...
1167
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1168
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1169
					400
1170
				)
1171
			);
1172
		} elseif ( empty( $user_id ) ) {
1173
			// $user_id is passed around during registration as "state".
1174
			return $return_error(
1175
				new \WP_Error(
1176
					'state_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'state_missing'.

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

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

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

Loading history...
1177
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1178
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1179
					400
1180
				)
1181
			);
1182
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1183
			return $return_error(
1184
				new \WP_Error(
1185
					'verify_secret_1_malformed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secret_1_malformed'.

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

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

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

Loading history...
1186
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1187
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1188
					400
1189
				)
1190
			);
1191
		}
1192
1193
		if ( ! $stored_secrets ) {
1194
			return $return_error(
1195
				new \WP_Error(
1196
					'verify_secrets_missing',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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

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

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

Loading history...
1197
					__( 'Verification secrets not found', 'jetpack' ),
1198
					400
1199
				)
1200
			);
1201
		} elseif ( is_wp_error( $stored_secrets ) ) {
1202
			$stored_secrets->add_data( 400 );
0 ignored issues
show
Bug introduced by
The method add_data cannot be called on $stored_secrets (of type string|array).

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

Loading history...
1203
			return $return_error( $stored_secrets );
1204
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1205
			return $return_error(
1206
				new \WP_Error(
1207
					'verify_secrets_incomplete',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_incomplete'.

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

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

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

Loading history...
1208
					__( 'Verification secrets are incomplete', 'jetpack' ),
1209
					400
1210
				)
1211
			);
1212
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1213
			return $return_error(
1214
				new \WP_Error(
1215
					'verify_secrets_mismatch',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_mismatch'.

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

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

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

Loading history...
1216
					__( 'Secret mismatch', 'jetpack' ),
1217
					400
1218
				)
1219
			);
1220
		}
1221
1222
		/**
1223
		 * We've succeeded at verifying the previously generated secret.
1224
		 *
1225
		 * @since 7.5.0
1226
		 *
1227
		 * @param string   $action The type of secret to verify.
1228
		 * @param \WP_User $user The user object.
1229
		 */
1230
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1231
1232
		return $stored_secrets['secret_2'];
1233
	}
1234
1235
	/**
1236
	 * Responds to a WordPress.com call to authorize the current user.
1237
	 * Should be changed to protected.
1238
	 */
1239
	public function handle_authorization() {
1240
1241
	}
1242
1243
	/**
1244
	 * Builds a URL to the Jetpack connection auth page.
1245
	 * This needs rethinking.
1246
	 *
1247
	 * @param bool        $raw If true, URL will not be escaped.
1248
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
1249
	 *                              If string, will be a custom redirect.
1250
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
1251
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0.
1252
	 *
1253
	 * @return string Connect URL
1254
	 */
1255
	public function build_connect_url( $raw, $redirect, $from, $register ) {
1256
		return array( $raw, $redirect, $from, $register );
1257
	}
1258
1259
	/**
1260
	 * Disconnects from the Jetpack servers.
1261
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1262
	 */
1263
	public function disconnect_site() {
1264
1265
	}
1266
1267
	/**
1268
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1269
	 *
1270
	 * @param string $text The string to hash.
1271
	 * @return string
1272
	 */
1273
	public function sha1_base64( $text ) {
1274
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1275
	}
1276
1277
	/**
1278
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1279
	 *
1280
	 * @param string $domain The domain to check.
1281
	 *
1282
	 * @return bool|WP_Error
1283
	 */
1284
	public function is_usable_domain( $domain ) {
1285
1286
		// If it's empty, just fail out.
1287
		if ( ! $domain ) {
1288
			return new \WP_Error(
1289
				'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...
1290
				/* translators: %1$s is a domain name. */
1291
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1292
			);
1293
		}
1294
1295
		/**
1296
		 * Skips the usuable domain check when connecting a site.
1297
		 *
1298
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1299
		 *
1300
		 * @since 4.1.0
1301
		 *
1302
		 * @param bool If the check should be skipped. Default false.
1303
		 */
1304
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1305
			return true;
1306
		}
1307
1308
		// None of the explicit localhosts.
1309
		$forbidden_domains = array(
1310
			'wordpress.com',
1311
			'localhost',
1312
			'localhost.localdomain',
1313
			'127.0.0.1',
1314
			'local.wordpress.test',         // VVV pattern.
1315
			'local.wordpress-trunk.test',   // VVV pattern.
1316
			'src.wordpress-develop.test',   // VVV pattern.
1317
			'build.wordpress-develop.test', // VVV pattern.
1318
		);
1319 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1320
			return new \WP_Error(
1321
				'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...
1322
				sprintf(
1323
					/* translators: %1$s is a domain name. */
1324
					__(
1325
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1326
						'jetpack'
1327
					),
1328
					$domain
1329
				)
1330
			);
1331
		}
1332
1333
		// No .test or .local domains.
1334 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1335
			return new \WP_Error(
1336
				'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...
1337
				sprintf(
1338
					/* translators: %1$s is a domain name. */
1339
					__(
1340
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1341
						'jetpack'
1342
					),
1343
					$domain
1344
				)
1345
			);
1346
		}
1347
1348
		// No WPCOM subdomains.
1349 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1350
			return new \WP_Error(
1351
				'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...
1352
				sprintf(
1353
					/* translators: %1$s is a domain name. */
1354
					__(
1355
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1356
						'jetpack'
1357
					),
1358
					$domain
1359
				)
1360
			);
1361
		}
1362
1363
		// If PHP was compiled without support for the Filter module (very edge case).
1364
		if ( ! function_exists( 'filter_var' ) ) {
1365
			// Just pass back true for now, and let wpcom sort it out.
1366
			return true;
1367
		}
1368
1369
		return true;
1370
	}
1371
1372
	/**
1373
	 * Gets the requested token.
1374
	 *
1375
	 * Tokens are one of two types:
1376
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
1377
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
1378
	 *    are not associated with a user account. They represent the site's connection with
1379
	 *    the Jetpack servers.
1380
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
1381
	 *
1382
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
1383
	 * token, and $private is a secret that should never be displayed anywhere or sent
1384
	 * over the network; it's used only for signing things.
1385
	 *
1386
	 * Blog Tokens can be "Normal" or "Special".
1387
	 * * Normal: The result of a normal connection flow. They look like
1388
	 *   "{$random_string_1}.{$random_string_2}"
1389
	 *   That is, $token_key and $private are both random strings.
1390
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
1391
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
1392
	 *   constant (rare).
1393
	 * * Special: A connection token for sites that have gone through an alternative
1394
	 *   connection flow. They look like:
1395
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
1396
	 *   That is, $private is a random string and $token_key has a special structure with
1397
	 *   lots of semicolons.
1398
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
1399
	 *   JETPACK_BLOG_TOKEN constant.
1400
	 *
1401
	 * In particular, note that Normal Blog Tokens never start with ";" and that
1402
	 * Special Blog Tokens always do.
1403
	 *
1404
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
1405
	 * order:
1406
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
1407
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
1408
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
1409
	 *
1410
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
1411
	 * @param string|false $token_key If provided, check that the token matches the provided input.
1412
	 * @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.
1413
	 *
1414
	 * @return object|false
1415
	 */
1416
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
1417
		$possible_special_tokens = array();
1418
		$possible_normal_tokens  = array();
1419
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
1420
1421
		if ( $user_id ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user_id of type false|integer is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1422
			if ( ! $user_tokens ) {
1423
				return $suppress_errors ? false : new \WP_Error( 'no_user_tokens' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_user_tokens'.

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

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

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

Loading history...
1424
			}
1425
			if ( self::JETPACK_MASTER_USER === $user_id ) {
1426
				$user_id = \Jetpack_Options::get_option( 'master_user' );
1427
				if ( ! $user_id ) {
1428
					return $suppress_errors ? false : new \WP_Error( 'empty_master_user_option' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'empty_master_user_option'.

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

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

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

Loading history...
1429
				}
1430
			}
1431
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
1432
				return $suppress_errors ? false : new \WP_Error( 'no_token_for_user', sprintf( 'No token for user %d', $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_token_for_user'.

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

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

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

Loading history...
1433
			}
1434
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
1435
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
1436
				return $suppress_errors ? false : new \WP_Error( 'token_malformed', sprintf( 'Token for user %d is malformed', $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_malformed'.

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

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

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

Loading history...
1437
			}
1438
			if ( $user_token_chunks[2] !== (string) $user_id ) {
1439
				return $suppress_errors ? false : new \WP_Error( 'user_id_mismatch', sprintf( 'Requesting user_id %d does not match token user_id %d', $user_id, $user_token_chunks[2] ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_id_mismatch'.

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

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

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

Loading history...
1440
			}
1441
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
1442
		} else {
1443
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
1444
			if ( $stored_blog_token ) {
1445
				$possible_normal_tokens[] = $stored_blog_token;
1446
			}
1447
1448
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
1449
1450
			if ( $defined_tokens_string ) {
1451
				$defined_tokens = explode( ',', $defined_tokens_string );
1452
				foreach ( $defined_tokens as $defined_token ) {
1453
					if ( ';' === $defined_token[0] ) {
1454
						$possible_special_tokens[] = $defined_token;
1455
					} else {
1456
						$possible_normal_tokens[] = $defined_token;
1457
					}
1458
				}
1459
			}
1460
		}
1461
1462
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1463
			$possible_tokens = $possible_normal_tokens;
1464
		} else {
1465
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
1466
		}
1467
1468
		if ( ! $possible_tokens ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $possible_tokens of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
1469
			return $suppress_errors ? false : new \WP_Error( 'no_possible_tokens' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_possible_tokens'.

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

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

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

Loading history...
1470
		}
1471
1472
		$valid_token = false;
1473
1474
		if ( false === $token_key ) {
1475
			// Use first token.
1476
			$valid_token = $possible_tokens[0];
1477
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
1478
			// Use first normal token.
1479
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
1480
		} else {
1481
			// Use the token matching $token_key or false if none.
1482
			// Ensure we check the full key.
1483
			$token_check = rtrim( $token_key, '.' ) . '.';
1484
1485
			foreach ( $possible_tokens as $possible_token ) {
1486
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
1487
					$valid_token = $possible_token;
1488
					break;
1489
				}
1490
			}
1491
		}
1492
1493
		if ( ! $valid_token ) {
1494
			return $suppress_errors ? false : new \WP_Error( 'no_valid_token' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_valid_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...
1495
		}
1496
1497
		return (object) array(
1498
			'secret'           => $valid_token,
1499
			'external_user_id' => (int) $user_id,
1500
		);
1501
	}
1502
1503
	/**
1504
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
1505
	 * since it is passed by reference to various methods.
1506
	 * Capture it here so we can verify the signature later.
1507
	 *
1508
	 * @param Array $methods an array of available XMLRPC methods.
1509
	 * @return Array the same array, since this method doesn't add or remove anything.
1510
	 */
1511
	public function xmlrpc_methods( $methods ) {
1512
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
1513
		return $methods;
1514
	}
1515
1516
	/**
1517
	 * Resets the raw post data parameter for testing purposes.
1518
	 */
1519
	public function reset_raw_post_data() {
1520
		$this->raw_post_data = null;
1521
	}
1522
1523
	/**
1524
	 * Registering an additional method.
1525
	 *
1526
	 * @param Array $methods an array of available XMLRPC methods.
1527
	 * @return Array the amended array in case the method is added.
1528
	 */
1529
	public function public_xmlrpc_methods( $methods ) {
1530
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
1531
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
1532
		}
1533
		return $methods;
1534
	}
1535
1536
	/**
1537
	 * Handles a getOptions XMLRPC method call.
1538
	 *
1539
	 * @todo Audit whether we really need to use strings without textdomains.
1540
	 *
1541
	 * @param Array $args method call arguments.
1542
	 * @return an amended XMLRPC server options array.
1543
	 */
1544
	public function jetpack_getOptions( $args ) {
1545
		global $wp_xmlrpc_server;
1546
1547
		$wp_xmlrpc_server->escape( $args );
1548
1549
		$username = $args[1];
1550
		$password = $args[2];
1551
1552
		$user = $wp_xmlrpc_server->login( $username, $password );
1553
		if ( ! $user ) {
1554
			return $wp_xmlrpc_server->error;
1555
		}
1556
1557
		$options   = array();
1558
		$user_data = $this->get_connected_user_data();
1559
		if ( is_array( $user_data ) ) {
1560
			$options['jetpack_user_id']         = array(
1561
				'desc'     => __( 'The WP.com user ID of the connected user' ), // phpcs:ignore WordPress.WP.I18n.MissingArgDomain
1562
				'readonly' => true,
1563
				'value'    => $user_data['ID'],
1564
			);
1565
			$options['jetpack_user_login']      = array(
1566
				'desc'     => __( 'The WP.com username of the connected user' ), // phpcs:ignore WordPress.WP.I18n.MissingArgDomain
1567
				'readonly' => true,
1568
				'value'    => $user_data['login'],
1569
			);
1570
			$options['jetpack_user_email']      = array(
1571
				'desc'     => __( 'The WP.com user email of the connected user' ), // phpcs:ignore WordPress.WP.I18n.MissingArgDomain
1572
				'readonly' => true,
1573
				'value'    => $user_data['email'],
1574
			);
1575
			$options['jetpack_user_site_count'] = array(
1576
				'desc'     => __( 'The number of sites of the connected WP.com user' ), // phpcs:ignore WordPress.WP.I18n.MissingArgDomain
1577
				'readonly' => true,
1578
				'value'    => $user_data['site_count'],
1579
			);
1580
		}
1581
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
1582
		$args                           = stripslashes_deep( $args );
1583
		return $wp_xmlrpc_server->wp_getOptions( $args );
1584
	}
1585
1586
	/**
1587
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
1588
	 *
1589
	 * @todo Audit whether we really need to use strings without textdomains.
1590
	 *
1591
	 * @param Array $options standard Core options.
1592
	 * @return Array amended options.
1593
	 */
1594
	public function xmlrpc_options( $options ) {
1595
		$jetpack_client_id = false;
1596
		if ( $this->is_active() ) {
1597
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
1598
		}
1599
		$options['jetpack_version'] = array(
1600
			'desc'     => __( 'Jetpack Plugin Version' ), // phpcs:ignore WordPress.WP.I18n.MissingArgDomain
1601
			'readonly' => true,
1602
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
1603
		);
1604
1605
		$options['jetpack_client_id'] = array(
1606
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site' ), // phpcs:ignore WordPress.WP.I18n.MissingArgDomain
1607
			'readonly' => true,
1608
			'value'    => $jetpack_client_id,
1609
		);
1610
		return $options;
1611
	}
1612
1613
	/**
1614
	 * Resets the saved authentication state in between testing requests.
1615
	 */
1616
	public function reset_saved_auth_state() {
1617
		$this->xmlrpc_verification = null;
1618
	}
1619
1620
	/**
1621
	 * Handles the login action for Authorizing the JSON API.
1622
	 */
1623
	public function login_form_json_api_authorization() {
1624
		$this->verify_json_api_authorization_request();
1625
1626
		add_action( 'wp_login', array( $this, 'store_json_api_authorization_token' ), 10, 2 );
1627
1628
		add_action( 'login_message', array( $this, 'login_message_json_api_authorization' ) );
1629
		add_action( 'login_form', array( $this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
1630
		add_filter( 'site_url', array( $this, 'post_login_form_to_signed_url' ), 10, 3 );
1631
	}
1632
1633
	/**
1634
	 * Make sure the login form is POSTed to the signed URL so we can reverify the request.
1635
	 *
1636
	 * @param string      $url     The complete site URL including scheme and path.
1637
	 * @param string      $path    Path relative to the site URL. Blank string if no path is specified.
1638
	 * @param string|null $scheme  Scheme to give the site URL context. Accepts 'http', 'https', 'login'.
1639
	 * @return string Signed login form action URL.
1640
	 */
1641
	public function post_login_form_to_signed_url( $url, $path, $scheme ) {
1642
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
1643
			return $url;
1644
		}
1645
1646
		$parsed_url = wp_parse_url( $url );
1647
		$url        = strtok( $url, '?' );
1648
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
1649
		if ( ! empty( $parsed_url['query'] ) ) {
1650
			$url .= "&{$parsed_url['query']}";
1651
		}
1652
1653
		return $url;
1654
	}
1655
1656
	/**
1657
	 * Make sure the POSTed request is handled by the same action.
1658
	 */
1659
	public function preserve_action_in_login_form_for_json_api_authorization() {
1660
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
1661
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
1662
	}
1663
1664
	/**
1665
	 * If someone logs in to approve API access, store the Access Code in usermeta.
1666
	 *
1667
	 * @param string   $user_login Username.
1668
	 * @param \WP_User $user       \WP_User object of the logged-in user.
1669
	 */
1670
	public function store_json_api_authorization_token( $user_login, $user ) {
1671
		add_filter( 'login_redirect', array( $this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
1672
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_public_api_domain' ) );
1673
		$token = wp_generate_password( 32, false );
1674
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
0 ignored issues
show
Bug introduced by
The property json_api_authorization_request 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...
1675
	}
1676
1677
	/**
1678
	 * Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access.
1679
	 *
1680
	 * @param array $domains An array of allowed hosts.
1681
	 * @return array Array of allowed hosts, with the WP.com API domain included.
1682
	 */
1683
	public function allow_wpcom_public_api_domain( $domains ) {
1684
		$domains[] = 'public-api.wordpress.com';
1685
		return $domains;
1686
	}
1687
1688
	/**
1689
	 * Whether the redirect URL is encoded.
1690
	 *
1691
	 * @param string $redirect_url Redirect URL.
1692
	 * @return bool True if the URL is encoded, false otherwise.
1693
	 */
1694
	public function is_redirect_encoded( $redirect_url ) {
1695
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
1696
	}
1697
1698
	/**
1699
	 * Add all wordpress.com environments to the safe redirect whitelist.
1700
	 *
1701
	 * @param array $domains An array of allowed hosts.
1702
	 * @return array Array of allowed hosts, with the WP.com API domain included.
1703
	 */
1704
	public function allow_wpcom_environments( $domains ) {
1705
		$domains[] = 'wordpress.com';
1706
		$domains[] = 'wpcalypso.wordpress.com';
1707
		$domains[] = 'horizon.wordpress.com';
1708
		$domains[] = 'calypso.localhost';
1709
		return $domains;
1710
	}
1711
1712
	/**
1713
	 * Add the Access Code details to the public-api.wordpress.com redirect.
1714
	 *
1715
	 * @todo Refactor to check properly if $user is a \WP_Error.
1716
	 *
1717
	 * @param string             $redirect_to          The redirect destination URL.
1718
	 * @param string             $original_redirect_to The requested redirect destination URL passed as a parameter.
1719
	 * @param \WP_User|\WP_Error $user                 \WP_User object if login was successful, \WP_Error object otherwise.
1720
	 * @return string Login redirect URL, with token parameters added to it.
1721
	 */
1722
	public function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
1723
		return add_query_arg(
1724
			urlencode_deep(
1725
				array(
1726
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
1727
					'jetpack-user-id' => (int) $user->ID,
1728
					'jetpack-state'   => $this->json_api_authorization_request['state'],
1729
				)
1730
			),
1731
			$redirect_to
1732
		);
1733
	}
1734
1735
1736
	/**
1737
	 * Verifies the request by checking the signature.
1738
	 *
1739
	 * @todo Refactor to implement proper nonce verification.
1740
	 *
1741
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
1742
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
1743
	 * @since 7.7.0 This method has been moved from `\Jetpack` to the connection package.
1744
	 *
1745
	 * @param null|array $environment Authorization data.
1746
	 */
1747
	public function verify_json_api_authorization_request( $environment = null ) {
1748
		$environment = is_null( $environment )
1749
			? $_REQUEST // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1750
			: $environment;
1751
1752
		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1753
		list( $env_token, $env_version, $env_user_id ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $env_version is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
1754
		$token = $this->get_access_token( $env_user_id, $env_token );
1755
		if ( ! $token || empty( $token->secret ) ) {
1756
			wp_die( esc_html__( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
1757
		}
1758
1759
		$die_error = __( 'Someone may be trying to trick you into giving them access to your site.  Or it could be you just encountered a bug :).  Either way, please close this window.', 'jetpack' );
1760
1761
		// Host has encoded the request URL, probably as a result of a bad http => https redirect.
1762
		if ( $this->is_redirect_encoded( $_GET['redirect_to'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1763
			/**
1764
			 * Jetpack authorization request Error.
1765
			 *
1766
			 * @since 7.5.0
1767
			 */
1768
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
1769
			$die_error = sprintf(
1770
				/* translators: %s is a URL */
1771
				__( 'Your site is incorrectly double-encoding redirects from http to https. This is preventing Jetpack from authenticating your connection. Please visit our <a href="%s">support page</a> for details about how to resolve this.', 'jetpack' ),
1772
				'https://jetpack.com/support/double-encoding/'
1773
			);
1774
		}
1775
1776
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
1777
1778
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
1779
			$signature = $jetpack_signature->sign_request(
1780
				$environment['token'],
1781
				$environment['timestamp'],
1782
				$environment['nonce'],
1783
				'',
1784
				'GET',
1785
				$environment['jetpack_json_api_original_query'],
1786
				null,
1787
				true
1788
			);
1789
		} else {
1790
			$signature = $jetpack_signature->sign_current_request(
1791
				array(
1792
					'body'   => null,
1793
					'method' => 'GET',
1794
				)
1795
			);
1796
		}
1797
1798
		if ( ! $signature ) {
1799
			wp_die( esc_html( $die_error ) );
1800
		} elseif ( is_wp_error( $signature ) ) {
1801
			wp_die( esc_html( $die_error ) );
1802
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
1803
			if ( is_ssl() ) {
1804
				// If we signed an HTTP request on the Jetpack Servers, but got redirected to HTTPS by the local blog, check the HTTP signature as well.
1805
				$signature = $jetpack_signature->sign_current_request(
1806
					array(
1807
						'scheme' => 'http',
1808
						'body'   => null,
1809
						'method' => 'GET',
1810
					)
1811
				);
1812
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
1813
					wp_die( esc_html( $die_error ) );
1814
				}
1815
			} else {
1816
				wp_die( esc_html( $die_error ) );
1817
			}
1818
		}
1819
1820
		$timestamp = (int) $environment['timestamp'];
1821
		$nonce     = stripslashes( (string) $environment['nonce'] );
1822
1823
		if ( ! $this->connection->add_nonce( $timestamp, $nonce ) ) {
0 ignored issues
show
Bug introduced by
The property connection 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...
1824
			// De-nonce the nonce, at least for 5 minutes.
1825
			// We have to reuse this nonce at least once (used the first time when the initial request is made, used a second time when the login form is POSTed).
1826
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
1827
			if ( $old_nonce_time < time() - 300 ) {
1828
				wp_die( esc_html__( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
1829
			}
1830
		}
1831
1832
		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
1833
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
1834
		$data_filters = array(
1835
			'state'        => 'opaque',
1836
			'client_id'    => 'int',
1837
			'client_title' => 'string',
1838
			'client_image' => 'url',
1839
		);
1840
1841
		foreach ( $data_filters as $key => $sanitation ) {
1842
			if ( ! isset( $data->$key ) ) {
1843
				wp_die( esc_html( $die_error ) );
1844
			}
1845
1846
			switch ( $sanitation ) {
1847
				case 'int':
1848
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
1849
					break;
1850
				case 'opaque':
1851
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
1852
					break;
1853
				case 'string':
1854
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
1855
					break;
1856
				case 'url':
1857
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
1858
					break;
1859
			}
1860
		}
1861
1862
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
1863
			wp_die( esc_html( $die_error ) );
1864
		}
1865
	}
1866
1867
	/**
1868
	 * Retrieve an updated login message for JSON API authorization.
1869
	 *
1870
	 * @return string Updated Login message.
1871
	 */
1872
	public function login_message_json_api_authorization() {
1873
		return '<p class="message">' . sprintf(
1874
			/* translators: %s is the name of the client you wish to authorize */
1875
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
1876
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
1877
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
1878
	}
1879
}
1880