Completed
Push — add/partial-reconnect ( ffa9f4...dfe562 )
by
unknown
07:36
created

initialize_rest_api_registration_connector()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * The Jetpack Connection manager class file.
4
 *
5
 * @package automattic/jetpack-connection
6
 */
7
8
namespace Automattic\Jetpack\Connection;
9
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Tracking;
14
use Jetpack_Options;
15
use WP_Error;
16
use WP_User;
17
18
/**
19
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
20
 * and Jetpack.
21
 */
22
class Manager {
23
24
	const SECRETS_MISSING        = 'secrets_missing';
25
	const SECRETS_EXPIRED        = 'secrets_expired';
26
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
27
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
28
	const JETPACK_MASTER_USER    = true;
29
30
	/**
31
	 * The procedure that should be run to generate secrets.
32
	 *
33
	 * @var Callable
34
	 */
35
	protected $secret_callable;
36
37
	/**
38
	 * A copy of the raw POST data for signature verification purposes.
39
	 *
40
	 * @var String
41
	 */
42
	protected $raw_post_data;
43
44
	/**
45
	 * Verification data needs to be stored to properly verify everything.
46
	 *
47
	 * @var Object
48
	 */
49
	private $xmlrpc_verification = null;
50
51
	/**
52
	 * Plugin management object.
53
	 *
54
	 * @var Plugin
55
	 */
56
	private $plugin = null;
57
58
	/**
59
	 * Initialize the object.
60
	 * Make sure to call the "Configure" first.
61
	 *
62
	 * @param string $plugin_slug Slug of the plugin using the connection (optional, but encouraged).
0 ignored issues
show
Documentation introduced by
Should the type for parameter $plugin_slug not be string|null?

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

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

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

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

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

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

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

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

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

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

An additional type check may prevent trouble.

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

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

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

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

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

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

Loading history...
503
			$this->raw_post_data
504
		);
505
	}
506
507
	/**
508
	 * Returns true if the current site is connected to WordPress.com.
509
	 *
510
	 * @return Boolean is the site connected?
511
	 */
512
	public function is_active() {
513
		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...
514
	}
515
516
	/**
517
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
518
	 *
519
	 * @access public
520
	 *
521
	 * @return bool
522
	 */
523
	public function is_registered() {
524
		$has_blog_id    = (bool) \Jetpack_Options::get_option( 'id' );
525
		$has_blog_token = (bool) $this->get_access_token( false );
526
		return $has_blog_id && $has_blog_token;
527
	}
528
529
	/**
530
	 * Checks to see if the connection owner of the site is missing.
531
	 *
532
	 * @return bool
533
	 */
534
	public function is_missing_connection_owner() {
535
		$connection_owner = $this->get_connection_owner_id();
536
		if ( ! get_user_by( 'id', $connection_owner ) ) {
537
			return true;
538
		}
539
540
		return false;
541
	}
542
543
	/**
544
	 * Returns true if the user with the specified identifier is connected to
545
	 * WordPress.com.
546
	 *
547
	 * @param Integer|Boolean $user_id the user identifier.
548
	 * @return Boolean is the user connected?
549
	 */
550
	public function is_user_connected( $user_id = false ) {
551
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
552
		if ( ! $user_id ) {
553
			return false;
554
		}
555
556
		return (bool) $this->get_access_token( $user_id );
557
	}
558
559
	/**
560
	 * Returns the local user ID of the connection owner.
561
	 *
562
	 * @return string|int Returns the ID of the connection owner or False if no connection owner found.
563
	 */
564 View Code Duplication
	public function get_connection_owner_id() {
565
		$user_token       = $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...
566
		$connection_owner = false;
567
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
568
			$connection_owner = $user_token->external_user_id;
569
		}
570
571
		return $connection_owner;
572
	}
573
574
	/**
575
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
576
	 * Able to select by specific capability.
577
	 *
578
	 * @param string $capability The capability of the user.
579
	 * @return array Array of WP_User objects if found.
580
	 */
581
	public function get_connected_users( $capability = 'any' ) {
582
		$connected_users    = array();
583
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
584
585
		if ( ! empty( $connected_user_ids ) ) {
586
			foreach ( $connected_user_ids as $id ) {
587
				// Check for capability.
588
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
589
					continue;
590
				}
591
592
				$connected_users[] = get_userdata( $id );
593
			}
594
		}
595
596
		return $connected_users;
597
	}
598
599
	/**
600
	 * Get the wpcom user data of the current|specified connected user.
601
	 *
602
	 * @todo Refactor to properly load the XMLRPC client independently.
603
	 *
604
	 * @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...
605
	 * @return Object the user object.
606
	 */
607 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
608
		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...
609
			$user_id = get_current_user_id();
610
		}
611
612
		$transient_key    = "jetpack_connected_user_data_$user_id";
613
		$cached_user_data = get_transient( $transient_key );
614
615
		if ( $cached_user_data ) {
616
			return $cached_user_data;
617
		}
618
619
		$xml = new \Jetpack_IXR_Client(
620
			array(
621
				'user_id' => $user_id,
622
			)
623
		);
624
		$xml->query( 'wpcom.getUser' );
625
		if ( ! $xml->isError() ) {
626
			$user_data = $xml->getResponse();
627
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
628
			return $user_data;
629
		}
630
631
		return false;
632
	}
633
634
	/**
635
	 * Returns a user object of the connection owner.
636
	 *
637
	 * @return object|false False if no connection owner found.
638
	 */
639 View Code Duplication
	public function get_connection_owner() {
640
		$user_token = $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...
641
642
		$connection_owner = false;
643
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
644
			$connection_owner = get_userdata( $user_token->external_user_id );
645
		}
646
647
		return $connection_owner;
648
	}
649
650
	/**
651
	 * Returns true if the provided user is the Jetpack connection owner.
652
	 * If user ID is not specified, the current user will be used.
653
	 *
654
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
655
	 * @return Boolean True the user the connection owner, false otherwise.
656
	 */
657 View Code Duplication
	public function is_connection_owner( $user_id = false ) {
658
		if ( ! $user_id ) {
659
			$user_id = get_current_user_id();
660
		}
661
662
		$user_token = $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...
663
664
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
665
	}
666
667
	/**
668
	 * Connects the user with a specified ID to a WordPress.com user using the
669
	 * remote login flow.
670
	 *
671
	 * @access public
672
	 *
673
	 * @param Integer $user_id (optional) the user identifier, defaults to current user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
680
		if ( null === $user_id ) {
681
			$user = wp_get_current_user();
682
		} else {
683
			$user = get_user_by( 'ID', $user_id );
684
		}
685
686
		if ( empty( $user ) ) {
687
			return new \WP_Error( 'user_not_found', 'Attempting to connect a non-existent user.' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_not_found'.

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

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

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

Loading history...
688
		}
689
690
		if ( null === $redirect_url ) {
691
			$redirect_url = admin_url();
0 ignored issues
show
Unused Code introduced by
$redirect_url is not used, you could remove the assignment.

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

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

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

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

Loading history...
692
		}
693
694
		// Using wp_redirect intentionally because we're redirecting outside.
695
		wp_redirect( $this->get_authorization_url( $user ) ); // phpcs:ignore WordPress.Security.SafeRedirect
696
		exit();
697
	}
698
699
	/**
700
	 * Unlinks the current user from the linked WordPress.com user.
701
	 *
702
	 * @access public
703
	 * @static
704
	 *
705
	 * @todo Refactor to properly load the XMLRPC client independently.
706
	 *
707
	 * @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...
708
	 * @param bool    $can_overwrite_primary_user Allow for the primary user to be disconnected.
709
	 * @return Boolean Whether the disconnection of the user was successful.
710
	 */
711
	public static function disconnect_user( $user_id = null, $can_overwrite_primary_user = false ) {
712
		$tokens = Jetpack_Options::get_option( 'user_tokens' );
713
		if ( ! $tokens ) {
714
			return false;
715
		}
716
717
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
718
719
		if ( Jetpack_Options::get_option( 'master_user' ) === $user_id && ! $can_overwrite_primary_user ) {
720
			return false;
721
		}
722
723
		if ( ! isset( $tokens[ $user_id ] ) ) {
724
			return false;
725
		}
726
727
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
728
		$xml->query( 'jetpack.unlink_user', $user_id );
729
730
		unset( $tokens[ $user_id ] );
731
732
		Jetpack_Options::update_option( 'user_tokens', $tokens );
733
734
		// Delete cached connected user data.
735
		$transient_key = "jetpack_connected_user_data_$user_id";
736
		delete_transient( $transient_key );
737
738
		/**
739
		 * Fires after the current user has been unlinked from WordPress.com.
740
		 *
741
		 * @since 4.1.0
742
		 *
743
		 * @param int $user_id The current user's ID.
744
		 */
745
		do_action( 'jetpack_unlinked_user', $user_id );
746
747
		return true;
748
	}
749
750
	/**
751
	 * Returns the requested Jetpack API URL.
752
	 *
753
	 * @param String $relative_url the relative API path.
754
	 * @return String API URL.
755
	 */
756
	public function api_url( $relative_url ) {
757
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
758
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
759
760
		/**
761
		 * Filters whether the connection manager should use the iframe authorization
762
		 * flow instead of the regular redirect-based flow.
763
		 *
764
		 * @since 8.3.0
765
		 *
766
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
767
		 */
768
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
769
770
		// Do not modify anything that is not related to authorize requests.
771
		if ( 'authorize' === $relative_url && $iframe_flow ) {
772
			$relative_url = 'authorize_iframe';
773
		}
774
775
		/**
776
		 * Filters the API URL that Jetpack uses for server communication.
777
		 *
778
		 * @since 8.0.0
779
		 *
780
		 * @param String $url the generated URL.
781
		 * @param String $relative_url the relative URL that was passed as an argument.
782
		 * @param String $api_base the API base string that is being used.
783
		 * @param String $api_version the API version string that is being used.
784
		 */
785
		return apply_filters(
786
			'jetpack_api_url',
787
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
788
			$relative_url,
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $relative_url.

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

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

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

Loading history...
789
			$api_base,
790
			$api_version
791
		);
792
	}
793
794
	/**
795
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
796
	 *
797
	 * @return String XMLRPC API URL.
798
	 */
799
	public function xmlrpc_api_url() {
800
		$base = preg_replace(
801
			'#(https?://[^?/]+)(/?.*)?$#',
802
			'\\1',
803
			Constants::get_constant( 'JETPACK__API_BASE' )
804
		);
805
		return untrailingslashit( $base ) . '/xmlrpc.php';
806
	}
807
808
	/**
809
	 * Attempts Jetpack registration which sets up the site for connection. Should
810
	 * remain public because the call to action comes from the current site, not from
811
	 * WordPress.com.
812
	 *
813
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
814
	 * @return true|WP_Error The error object.
815
	 */
816
	public function register( $api_endpoint = 'register' ) {
817
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
818
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
819
820
		if (
821
			empty( $secrets['secret_1'] ) ||
822
			empty( $secrets['secret_2'] ) ||
823
			empty( $secrets['exp'] )
824
		) {
825
			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...
826
		}
827
828
		// Better to try (and fail) to set a higher timeout than this system
829
		// supports than to have register fail for more users than it should.
830
		$timeout = $this->set_min_time_limit( 60 ) / 2;
831
832
		$gmt_offset = get_option( 'gmt_offset' );
833
		if ( ! $gmt_offset ) {
834
			$gmt_offset = 0;
835
		}
836
837
		$stats_options = get_option( 'stats_options' );
838
		$stats_id      = isset( $stats_options['blog_id'] )
839
			? $stats_options['blog_id']
840
			: null;
841
842
		/**
843
		 * Filters the request body for additional property addition.
844
		 *
845
		 * @since 7.7.0
846
		 *
847
		 * @param array $post_data request data.
848
		 * @param Array $token_data token data.
849
		 */
850
		$body = apply_filters(
851
			'jetpack_register_request_body',
852
			array(
853
				'siteurl'         => site_url(),
854
				'home'            => home_url(),
855
				'gmt_offset'      => $gmt_offset,
856
				'timezone_string' => (string) get_option( 'timezone_string' ),
857
				'site_name'       => (string) get_option( 'blogname' ),
858
				'secret_1'        => $secrets['secret_1'],
859
				'secret_2'        => $secrets['secret_2'],
860
				'site_lang'       => get_locale(),
861
				'timeout'         => $timeout,
862
				'stats_id'        => $stats_id,
863
				'state'           => get_current_user_id(),
864
				'site_created'    => $this->get_assumed_site_creation_date(),
865
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
866
				'ABSPATH'         => Constants::get_constant( 'ABSPATH' ),
867
			)
868
		);
869
870
		$args = array(
871
			'method'  => 'POST',
872
			'body'    => $body,
873
			'headers' => array(
874
				'Accept' => 'application/json',
875
			),
876
			'timeout' => $timeout,
877
		);
878
879
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
880
881
		// TODO: fix URLs for bad hosts.
882
		$response = Client::_wp_remote_request(
883
			$this->api_url( $api_endpoint ),
884
			$args,
885
			true
886
		);
887
888
		// Make sure the response is valid and does not contain any Jetpack errors.
889
		$registration_details = $this->validate_remote_register_response( $response );
890
891
		if ( is_wp_error( $registration_details ) ) {
892
			return $registration_details;
893
		} elseif ( ! $registration_details ) {
894
			return new \WP_Error(
895
				'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...
896
				'Unknown error registering your Jetpack site.',
897
				wp_remote_retrieve_response_code( $response )
898
			);
899
		}
900
901
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
902
			return new \WP_Error(
903
				'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...
904
				'Unable to validate registration of your Jetpack site.',
905
				wp_remote_retrieve_response_code( $response )
906
			);
907
		}
908
909
		if ( isset( $registration_details->jetpack_public ) ) {
910
			$jetpack_public = (int) $registration_details->jetpack_public;
911
		} else {
912
			$jetpack_public = false;
913
		}
914
915
		\Jetpack_Options::update_options(
916
			array(
917
				'id'         => (int) $registration_details->jetpack_id,
918
				'blog_token' => (string) $registration_details->jetpack_secret,
919
				'public'     => $jetpack_public,
920
			)
921
		);
922
923
		/**
924
		 * Fires when a site is registered on WordPress.com.
925
		 *
926
		 * @since 3.7.0
927
		 *
928
		 * @param int $json->jetpack_id Jetpack Blog ID.
929
		 * @param string $json->jetpack_secret Jetpack Blog Token.
930
		 * @param int|bool $jetpack_public Is the site public.
931
		 */
932
		do_action(
933
			'jetpack_site_registered',
934
			$registration_details->jetpack_id,
935
			$registration_details->jetpack_secret,
936
			$jetpack_public
937
		);
938
939
		if ( isset( $registration_details->token ) ) {
940
			/**
941
			 * Fires when a user token is sent along with the registration data.
942
			 *
943
			 * @since 7.6.0
944
			 *
945
			 * @param object $token the administrator token for the newly registered site.
946
			 */
947
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
948
		}
949
950
		return true;
951
	}
952
953
	/**
954
	 * Takes the response from the Jetpack register new site endpoint and
955
	 * verifies it worked properly.
956
	 *
957
	 * @since 2.6
958
	 *
959
	 * @param Mixed $response the response object, or the error object.
960
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
961
	 **/
962
	protected function validate_remote_register_response( $response ) {
963
		if ( is_wp_error( $response ) ) {
964
			return new \WP_Error(
965
				'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...
966
				$response->get_error_message()
967
			);
968
		}
969
970
		$code   = wp_remote_retrieve_response_code( $response );
971
		$entity = wp_remote_retrieve_body( $response );
972
973
		if ( $entity ) {
974
			$registration_response = json_decode( $entity );
975
		} else {
976
			$registration_response = false;
977
		}
978
979
		$code_type = intval( $code / 100 );
980
		if ( 5 === $code_type ) {
981
			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...
982
		} elseif ( 408 === $code ) {
983
			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...
984
		} elseif ( ! empty( $registration_response->error ) ) {
985
			if (
986
				'xml_rpc-32700' === $registration_response->error
987
				&& ! function_exists( 'xml_parser_create' )
988
			) {
989
				$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' );
990
			} else {
991
				$error_description = isset( $registration_response->error_description )
992
					? (string) $registration_response->error_description
993
					: '';
994
			}
995
996
			return new \WP_Error(
997
				(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...
998
				$error_description,
999
				$code
1000
			);
1001
		} elseif ( 200 !== $code ) {
1002
			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...
1003
		}
1004
1005
		// Jetpack ID error block.
1006
		if ( empty( $registration_response->jetpack_id ) ) {
1007
			return new \WP_Error(
1008
				'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...
1009
				/* translators: %s is an error message string */
1010
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1011
				$entity
1012
			);
1013
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1014
			return new \WP_Error(
1015
				'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...
1016
				/* translators: %s is an error message string */
1017
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1018
				$entity
1019
			);
1020 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1021
			return new \WP_Error(
1022
				'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...
1023
				/* translators: %s is an error message string */
1024
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1025
				$entity
1026
			);
1027
		}
1028
1029
		return $registration_response;
1030
	}
1031
1032
	/**
1033
	 * Adds a used nonce to a list of known nonces.
1034
	 *
1035
	 * @param int    $timestamp the current request timestamp.
1036
	 * @param string $nonce the nonce value.
1037
	 * @return bool whether the nonce is unique or not.
1038
	 */
1039
	public function add_nonce( $timestamp, $nonce ) {
1040
		global $wpdb;
1041
		static $nonces_used_this_request = array();
1042
1043
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
1044
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
1045
		}
1046
1047
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
1048
		$timestamp = (int) $timestamp;
1049
		$nonce     = esc_sql( $nonce );
1050
1051
		// Raw query so we can avoid races: add_option will also update.
1052
		$show_errors = $wpdb->show_errors( false );
1053
1054
		$old_nonce = $wpdb->get_row(
1055
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1056
		);
1057
1058
		if ( is_null( $old_nonce ) ) {
1059
			$return = $wpdb->query(
1060
				$wpdb->prepare(
1061
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1062
					"jetpack_nonce_{$timestamp}_{$nonce}",
1063
					time(),
1064
					'no'
1065
				)
1066
			);
1067
		} else {
1068
			$return = false;
1069
		}
1070
1071
		$wpdb->show_errors( $show_errors );
1072
1073
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1074
1075
		return $return;
1076
	}
1077
1078
	/**
1079
	 * Cleans nonces that were saved when calling ::add_nonce.
1080
	 *
1081
	 * @todo Properly prepare the query before executing it.
1082
	 *
1083
	 * @param bool $all whether to clean even non-expired nonces.
1084
	 */
1085
	public function clean_nonces( $all = false ) {
1086
		global $wpdb;
1087
1088
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1089
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1090
1091
		if ( true !== $all ) {
1092
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1093
			$sql_args[] = time() - 3600;
1094
		}
1095
1096
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1097
1098
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1099
1100
		for ( $i = 0; $i < 1000; $i++ ) {
1101
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1102
				break;
1103
			}
1104
		}
1105
	}
1106
1107
	/**
1108
	 * Sets the Connection custom capabilities.
1109
	 *
1110
	 * @param string[] $caps    Array of the user's capabilities.
1111
	 * @param string   $cap     Capability name.
1112
	 * @param int      $user_id The user ID.
1113
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1114
	 */
1115
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1116
		$is_offline_mode = ( new Status() )->is_offline_mode();
1117
		switch ( $cap ) {
1118
			case 'jetpack_connect':
1119
			case 'jetpack_reconnect':
1120
				if ( $is_offline_mode ) {
1121
					$caps = array( 'do_not_allow' );
1122
					break;
1123
				}
1124
				// Pass through. If it's not offline mode, these should match disconnect.
1125
				// Let users disconnect if it's offline mode, just in case things glitch.
1126
			case 'jetpack_disconnect':
1127
				/**
1128
				 * Filters the jetpack_disconnect capability.
1129
				 *
1130
				 * @since 8.7.0
1131
				 *
1132
				 * @param array An array containing the capability name.
1133
				 */
1134
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1135
				break;
1136
			case 'jetpack_connect_user':
1137
				if ( $is_offline_mode ) {
1138
					$caps = array( 'do_not_allow' );
1139
					break;
1140
				}
1141
				$caps = array( 'read' );
1142
				break;
1143
		}
1144
		return $caps;
1145
	}
1146
1147
	/**
1148
	 * Builds the timeout limit for queries talking with the wpcom servers.
1149
	 *
1150
	 * Based on local php max_execution_time in php.ini
1151
	 *
1152
	 * @since 5.4
1153
	 * @return int
1154
	 **/
1155
	public function get_max_execution_time() {
1156
		$timeout = (int) ini_get( 'max_execution_time' );
1157
1158
		// Ensure exec time set in php.ini.
1159
		if ( ! $timeout ) {
1160
			$timeout = 30;
1161
		}
1162
		return $timeout;
1163
	}
1164
1165
	/**
1166
	 * Sets a minimum request timeout, and returns the current timeout
1167
	 *
1168
	 * @since 5.4
1169
	 * @param Integer $min_timeout the minimum timeout value.
1170
	 **/
1171 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1172
		$timeout = $this->get_max_execution_time();
1173
		if ( $timeout < $min_timeout ) {
1174
			$timeout = $min_timeout;
1175
			set_time_limit( $timeout );
1176
		}
1177
		return $timeout;
1178
	}
1179
1180
	/**
1181
	 * Get our assumed site creation date.
1182
	 * Calculated based on the earlier date of either:
1183
	 * - Earliest admin user registration date.
1184
	 * - Earliest date of post of any post type.
1185
	 *
1186
	 * @since 7.2.0
1187
	 *
1188
	 * @return string Assumed site creation date and time.
1189
	 */
1190
	public function get_assumed_site_creation_date() {
1191
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1192
		if ( ! empty( $cached_date ) ) {
1193
			return $cached_date;
1194
		}
1195
1196
		$earliest_registered_users  = get_users(
1197
			array(
1198
				'role'    => 'administrator',
1199
				'orderby' => 'user_registered',
1200
				'order'   => 'ASC',
1201
				'fields'  => array( 'user_registered' ),
1202
				'number'  => 1,
1203
			)
1204
		);
1205
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1206
1207
		$earliest_posts = get_posts(
1208
			array(
1209
				'posts_per_page' => 1,
1210
				'post_type'      => 'any',
1211
				'post_status'    => 'any',
1212
				'orderby'        => 'date',
1213
				'order'          => 'ASC',
1214
			)
1215
		);
1216
1217
		// If there are no posts at all, we'll count only on user registration date.
1218
		if ( $earliest_posts ) {
1219
			$earliest_post_date = $earliest_posts[0]->post_date;
1220
		} else {
1221
			$earliest_post_date = PHP_INT_MAX;
1222
		}
1223
1224
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1225
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1226
1227
		return $assumed_date;
1228
	}
1229
1230
	/**
1231
	 * Adds the activation source string as a parameter to passed arguments.
1232
	 *
1233
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1234
	 *
1235
	 * @param array $args arguments that need to have the source added.
1236
	 * @return array $amended arguments.
1237
	 */
1238 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1239
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1240
1241
		if ( $activation_source_name ) {
1242
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1243
			$args['_as'] = urlencode( $activation_source_name );
1244
		}
1245
1246
		if ( $activation_source_keyword ) {
1247
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1248
			$args['_ak'] = urlencode( $activation_source_keyword );
1249
		}
1250
1251
		return $args;
1252
	}
1253
1254
	/**
1255
	 * Returns the callable that would be used to generate secrets.
1256
	 *
1257
	 * @return Callable a function that returns a secure string to be used as a secret.
1258
	 */
1259
	protected function get_secret_callable() {
1260
		if ( ! isset( $this->secret_callable ) ) {
1261
			/**
1262
			 * Allows modification of the callable that is used to generate connection secrets.
1263
			 *
1264
			 * @param Callable a function or method that returns a secret string.
1265
			 */
1266
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', array( $this, 'secret_callable_method' ) );
1267
		}
1268
1269
		return $this->secret_callable;
1270
	}
1271
1272
	/**
1273
	 * Runs the wp_generate_password function with the required parameters. This is the
1274
	 * default implementation of the secret callable, can be overridden using the
1275
	 * jetpack_connection_secret_generator filter.
1276
	 *
1277
	 * @return String $secret value.
1278
	 */
1279
	private function secret_callable_method() {
1280
		return wp_generate_password( 32, false );
1281
	}
1282
1283
	/**
1284
	 * Generates two secret tokens and the end of life timestamp for them.
1285
	 *
1286
	 * @param String  $action  The action name.
1287
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be false|integer?

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

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

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

Loading history...
1288
	 * @param Integer $exp     Expiration time in seconds.
1289
	 */
1290
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1291
		if ( false === $user_id ) {
1292
			$user_id = get_current_user_id();
1293
		}
1294
1295
		$callable = $this->get_secret_callable();
1296
1297
		$secrets = \Jetpack_Options::get_raw_option(
1298
			self::SECRETS_OPTION_NAME,
1299
			array()
1300
		);
1301
1302
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1303
1304
		if (
1305
			isset( $secrets[ $secret_name ] ) &&
1306
			$secrets[ $secret_name ]['exp'] > time()
1307
		) {
1308
			return $secrets[ $secret_name ];
1309
		}
1310
1311
		$secret_value = array(
1312
			'secret_1' => call_user_func( $callable ),
1313
			'secret_2' => call_user_func( $callable ),
1314
			'exp'      => time() + $exp,
1315
		);
1316
1317
		$secrets[ $secret_name ] = $secret_value;
1318
1319
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1320
		return $secrets[ $secret_name ];
1321
	}
1322
1323
	/**
1324
	 * Returns two secret tokens and the end of life timestamp for them.
1325
	 *
1326
	 * @param String  $action  The action name.
1327
	 * @param Integer $user_id The user identifier.
1328
	 * @return string|array an array of secrets or an error string.
1329
	 */
1330
	public function get_secrets( $action, $user_id ) {
1331
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1332
		$secrets     = \Jetpack_Options::get_raw_option(
1333
			self::SECRETS_OPTION_NAME,
1334
			array()
1335
		);
1336
1337
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1338
			return self::SECRETS_MISSING;
1339
		}
1340
1341
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1342
			$this->delete_secrets( $action, $user_id );
1343
			return self::SECRETS_EXPIRED;
1344
		}
1345
1346
		return $secrets[ $secret_name ];
1347
	}
1348
1349
	/**
1350
	 * Deletes secret tokens in case they, for example, have expired.
1351
	 *
1352
	 * @param String  $action  The action name.
1353
	 * @param Integer $user_id The user identifier.
1354
	 */
1355
	public function delete_secrets( $action, $user_id ) {
1356
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1357
		$secrets     = \Jetpack_Options::get_raw_option(
1358
			self::SECRETS_OPTION_NAME,
1359
			array()
1360
		);
1361
		if ( isset( $secrets[ $secret_name ] ) ) {
1362
			unset( $secrets[ $secret_name ] );
1363
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1364
		}
1365
	}
1366
1367
	/**
1368
	 * Deletes all connection tokens and transients from the local Jetpack site.
1369
	 * If the plugin object has been provided in the constructor, the function first checks
1370
	 * whether it's the only active connection.
1371
	 * If there are any other connections, the function will do nothing and return `false`
1372
	 * (unless `$ignore_connected_plugins` is set to `true`).
1373
	 *
1374
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1375
	 *
1376
	 * @return bool True if disconnected successfully, false otherwise.
1377
	 */
1378
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1379 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1380
			return false;
1381
		}
1382
1383
		/**
1384
		 * Fires upon the disconnect attempt.
1385
		 * Return `false` to prevent the disconnect.
1386
		 *
1387
		 * @since 8.7.0
1388
		 */
1389
		if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', true, $this ) ) {
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this.

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

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

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

Loading history...
1390
			return false;
1391
		}
1392
1393
		\Jetpack_Options::delete_option(
1394
			array(
1395
				'blog_token',
1396
				'user_token',
1397
				'user_tokens',
1398
				'master_user',
1399
				'time_diff',
1400
				'fallback_no_verify_ssl_certs',
1401
			)
1402
		);
1403
1404
		\Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
1405
1406
		// Delete cached connected user data.
1407
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1408
		delete_transient( $transient_key );
1409
1410
		// Delete all XML-RPC errors.
1411
		Error_Handler::get_instance()->delete_all_errors();
1412
1413
		return true;
1414
	}
1415
1416
	/**
1417
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1418
	 * If the plugin object has been provided in the constructor, the function first check
1419
	 * whether it's the only active connection.
1420
	 * If there are any other connections, the function will do nothing and return `false`
1421
	 * (unless `$ignore_connected_plugins` is set to `true`).
1422
	 *
1423
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1424
	 *
1425
	 * @return bool True if disconnected successfully, false otherwise.
1426
	 */
1427
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1428 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1429
			return false;
1430
		}
1431
1432
		/**
1433
		 * Fires upon the disconnect attempt.
1434
		 * Return `false` to prevent the disconnect.
1435
		 *
1436
		 * @since 8.7.0
1437
		 */
1438
		if ( ! apply_filters( 'jetpack_connection_disconnect_site_wpcom', true, $this ) ) {
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $this.

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

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

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

Loading history...
1439
			return false;
1440
		}
1441
1442
		$xml = new \Jetpack_IXR_Client();
1443
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1444
1445
		return true;
1446
	}
1447
1448
	/**
1449
	 * Disconnect the plugin and remove the tokens.
1450
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1451
	 * This is a proxy method to simplify the Connection package API.
1452
	 *
1453
	 * @see Manager::disable_plugin()
1454
	 * @see Manager::disconnect_site_wpcom()
1455
	 * @see Manager::delete_all_connection_tokens()
1456
	 *
1457
	 * @return bool
1458
	 */
1459
	public function remove_connection() {
1460
		$this->disable_plugin();
1461
		$this->disconnect_site_wpcom();
1462
		$this->delete_all_connection_tokens();
1463
1464
		return true;
1465
	}
1466
1467
	/**
1468
	 * Completely clearing up the connection, and initiating reconnect.
1469
	 *
1470
	 * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
1471
	 */
1472
	public function reconnect() {
1473
		$this->disconnect_site_wpcom( true );
1474
		$this->delete_all_connection_tokens( true );
1475
1476
		return $this->register();
1477
	}
1478
1479
	/**
1480
	 * Validate the tokens, and refresh the invalid ones.
1481
	 *
1482
	 * @return string|true|WP_Error True if connection restored or string indicating what's to be done next. A `WP_Error` object otherwise.
1483
	 */
1484
	public function restore() {
1485
		$invalid_tokens = array();
1486
		$can_restore    = $this->can_restore( $invalid_tokens );
1487
1488
		// Tokens are valid. We can't fix the problem we don't see, so the full reconnection is needed.
1489
		if ( ! $can_restore ) {
1490
			$this->reconnect();
1491
			return 'authorize';
1492
		}
1493
1494
		if ( in_array( 'user', $invalid_tokens, true ) ) {
1495
			self::disconnect_user( null, true );
1496
			return 'authorize';
1497
		}
1498
1499
		if ( in_array( 'blog', $invalid_tokens, true ) ) {
1500
			return self::refresh_blog_token();
1501
		}
1502
1503
		return true;
1504
	}
1505
1506
	/**
1507
	 * Determine whether we can restore the connection, or the full reconnect is needed.
1508
	 *
1509
	 * @param array $invalid_tokens The array the invalid tokens are stored in, provided by reference.
1510
	 *
1511
	 * @return bool `True` if the connection can be restored, `false` otherwise.
1512
	 */
1513
	public function can_restore( &$invalid_tokens ) {
1514
		$invalid_tokens = array();
1515
1516
		$validated_tokens = $this->validate_tokens();
1517
1518
		if ( ! is_array( $validated_tokens ) || count( array_diff_key( array_flip( array( 'blog_token_is_healthy', 'user_token_is_healthy' ) ), $validated_tokens ) ) ) {
1519
			return false;
1520
		}
1521
1522
		if ( true !== $validated_tokens['blog_token_is_healthy'] ) {
1523
			$invalid_tokens[] = 'blog';
1524
		}
1525
1526
		if ( true !== $validated_tokens['user_token_is_healthy'] ) {
1527
			$invalid_tokens[] = 'user';
1528
		}
1529
1530
		return (bool) count( $invalid_tokens );
1531
	}
1532
1533
	/**
1534
	 * Perform the API request to validate the blog and user tokens.
1535
	 *
1536
	 * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
1537
	 *
1538
	 * @return array|false The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
1539
	 */
1540
	public function validate_tokens( $user_id = null ) {
1541
		$url = sprintf(
1542
			'%s://%s/%s/v%s/%s',
1543
			Client::protocol(),
1544
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_HOST' ),
1545
			'wpcom',
1546
			'2',
1547
			'jetpack-token-health'
1548
		);
1549
1550
		$user_token = $this->get_access_token( $user_id ? $user_id : get_current_user_id() );
1551
		$blog_token = $this->get_access_token();
1552
		$method     = 'POST';
1553
		$body       = array(
1554
			'user_token' => $this->get_signed_token( $user_token ),
0 ignored issues
show
Documentation introduced by
$user_token is of type object|false, but the function expects a string.

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...
1555
			'blog_token' => $this->get_signed_token( $blog_token ),
0 ignored issues
show
Documentation introduced by
$blog_token is of type object|false, but the function expects a string.

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...
1556
		);
1557
		$response   = Client::_wp_remote_request( $url, compact( 'body', 'method' ) );
1558
1559
		if ( is_wp_error( $response ) || ! wp_remote_retrieve_body( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
1560
			return false;
1561
		}
1562
1563
		$body = json_decode( wp_remote_retrieve_body( $response ), true );
1564
1565
		return $body ? $body : false;
1566
	}
1567
1568
	/**
1569
	 * Responds to a WordPress.com call to register the current site.
1570
	 * Should be changed to protected.
1571
	 *
1572
	 * @param array $registration_data Array of [ secret_1, user_id ].
1573
	 */
1574
	public function handle_registration( array $registration_data ) {
1575
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1576
		if ( empty( $registration_user_id ) ) {
1577
			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...
1578
		}
1579
1580
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1581
	}
1582
1583
	/**
1584
	 * Verify a Previously Generated Secret.
1585
	 *
1586
	 * @param string $action   The type of secret to verify.
1587
	 * @param string $secret_1 The secret string to compare to what is stored.
1588
	 * @param int    $user_id  The user ID of the owner of the secret.
1589
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1590
	 */
1591
	public function verify_secrets( $action, $secret_1, $user_id ) {
1592
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1593
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1594
			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...
1595
		}
1596
1597
		$user = get_user_by( 'id', $user_id );
1598
1599
		/**
1600
		 * We've begun verifying the previously generated secret.
1601
		 *
1602
		 * @since 7.5.0
1603
		 *
1604
		 * @param string   $action The type of secret to verify.
1605
		 * @param \WP_User $user The user object.
1606
		 */
1607
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1608
1609
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1610
			/**
1611
			 * Verifying of the previously generated secret has failed.
1612
			 *
1613
			 * @since 7.5.0
1614
			 *
1615
			 * @param string    $action  The type of secret to verify.
1616
			 * @param \WP_User  $user The user object.
1617
			 * @param \WP_Error $error The error object.
1618
			 */
1619
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1620
1621
			return $error;
1622
		};
1623
1624
		$stored_secrets = $this->get_secrets( $action, $user_id );
1625
		$this->delete_secrets( $action, $user_id );
1626
1627
		$error = null;
1628
		if ( empty( $secret_1 ) ) {
1629
			$error = $return_error(
1630
				new \WP_Error(
1631
					'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...
1632
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1633
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1634
					400
1635
				)
1636
			);
1637
		} elseif ( ! is_string( $secret_1 ) ) {
1638
			$error = $return_error(
1639
				new \WP_Error(
1640
					'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...
1641
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1642
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1643
					400
1644
				)
1645
			);
1646
		} elseif ( empty( $user_id ) ) {
1647
			// $user_id is passed around during registration as "state".
1648
			$error = $return_error(
1649
				new \WP_Error(
1650
					'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...
1651
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1652
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1653
					400
1654
				)
1655
			);
1656
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1657
			$error = $return_error(
1658
				new \WP_Error(
1659
					'state_malformed',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'state_malformed'.

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

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

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

Loading history...
1660
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1661
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1662
					400
1663
				)
1664
			);
1665
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1666
			$error = $return_error(
1667
				new \WP_Error(
1668
					'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...
1669
					__( 'Verification secrets not found', 'jetpack' ),
1670
					400
1671
				)
1672
			);
1673
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1674
			$error = $return_error(
1675
				new \WP_Error(
1676
					'verify_secrets_expired',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

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

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

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

Loading history...
1677
					__( 'Verification took too long', 'jetpack' ),
1678
					400
1679
				)
1680
			);
1681
		} elseif ( ! $stored_secrets ) {
1682
			$error = $return_error(
1683
				new \WP_Error(
1684
					'verify_secrets_empty',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_empty'.

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

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

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

Loading history...
1685
					__( 'Verification secrets are empty', 'jetpack' ),
1686
					400
1687
				)
1688
			);
1689
		} elseif ( is_wp_error( $stored_secrets ) ) {
1690
			$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...
1691
			$error = $return_error( $stored_secrets );
1692
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1693
			$error = $return_error(
1694
				new \WP_Error(
1695
					'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...
1696
					__( 'Verification secrets are incomplete', 'jetpack' ),
1697
					400
1698
				)
1699
			);
1700
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1701
			$error = $return_error(
1702
				new \WP_Error(
1703
					'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...
1704
					__( 'Secret mismatch', 'jetpack' ),
1705
					400
1706
				)
1707
			);
1708
		}
1709
1710
		// Something went wrong during the checks, returning the error.
1711
		if ( ! empty( $error ) ) {
1712
			return $error;
1713
		}
1714
1715
		/**
1716
		 * We've succeeded at verifying the previously generated secret.
1717
		 *
1718
		 * @since 7.5.0
1719
		 *
1720
		 * @param string   $action The type of secret to verify.
1721
		 * @param \WP_User $user The user object.
1722
		 */
1723
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1724
1725
		return $stored_secrets['secret_2'];
1726
	}
1727
1728
	/**
1729
	 * Responds to a WordPress.com call to authorize the current user.
1730
	 * Should be changed to protected.
1731
	 */
1732
	public function handle_authorization() {
1733
1734
	}
1735
1736
	/**
1737
	 * Obtains the auth token.
1738
	 *
1739
	 * @param array $data The request data.
1740
	 * @return object|\WP_Error Returns the auth token on success.
1741
	 *                          Returns a \WP_Error on failure.
1742
	 */
1743
	public function get_token( $data ) {
1744
		$roles = new Roles();
1745
		$role  = $roles->translate_current_user_to_role();
1746
1747
		if ( ! $role ) {
1748
			return new \WP_Error( 'role', __( 'An administrator for this blog must set up the Jetpack connection.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'role'.

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

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

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

Loading history...
1749
		}
1750
1751
		$client_secret = $this->get_access_token();
1752
		if ( ! $client_secret ) {
1753
			return new \WP_Error( 'client_secret', __( 'You need to register your Jetpack before connecting it.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'client_secret'.

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

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

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

Loading history...
1754
		}
1755
1756
		/**
1757
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1758
		 * data processing.
1759
		 *
1760
		 * @since 8.0.0
1761
		 *
1762
		 * @param string $redirect_url Defaults to the site admin URL.
1763
		 */
1764
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1765
1766
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1767
1768
		/**
1769
		* Filter the URL to redirect the user back to when the authentication process
1770
		* is complete.
1771
		*
1772
		* @since 8.0.0
1773
		*
1774
		* @param string $redirect_url Defaults to the site URL.
1775
		*/
1776
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1777
1778
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1779
			? $data['redirect_uri']
1780
			: add_query_arg(
1781
				array(
1782
					'action'   => 'authorize',
1783
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1784
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1785
				),
1786
				esc_url( $processing_url )
1787
			);
1788
1789
		/**
1790
		 * Filters the token request data.
1791
		 *
1792
		 * @since 8.0.0
1793
		 *
1794
		 * @param array $request_data request data.
1795
		 */
1796
		$body = apply_filters(
1797
			'jetpack_token_request_body',
1798
			array(
1799
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1800
				'client_secret' => $client_secret->secret,
1801
				'grant_type'    => 'authorization_code',
1802
				'code'          => $data['code'],
1803
				'redirect_uri'  => $redirect_uri,
1804
			)
1805
		);
1806
1807
		$args = array(
1808
			'method'  => 'POST',
1809
			'body'    => $body,
1810
			'headers' => array(
1811
				'Accept' => 'application/json',
1812
			),
1813
		);
1814
1815
		add_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1816
		$response = Client::_wp_remote_request( Utils::fix_url_for_bad_hosts( $this->api_url( 'token' ) ), $args );
1817
		remove_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1818
1819
		if ( is_wp_error( $response ) ) {
1820
			return new \WP_Error( 'token_http_request_failed', $response->get_error_message() );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_http_request_failed'.

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

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

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

Loading history...
1821
		}
1822
1823
		$code   = wp_remote_retrieve_response_code( $response );
1824
		$entity = wp_remote_retrieve_body( $response );
1825
1826
		if ( $entity ) {
1827
			$json = json_decode( $entity );
1828
		} else {
1829
			$json = false;
1830
		}
1831
1832 View Code Duplication
		if ( 200 !== $code || ! empty( $json->error ) ) {
1833
			if ( empty( $json->error ) ) {
1834
				return new \WP_Error( 'unknown', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown'.

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

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

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

Loading history...
1835
			}
1836
1837
			/* translators: Error description string. */
1838
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1839
1840
			return new \WP_Error( (string) $json->error, $error_description, $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with (string) $json->error.

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

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

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

Loading history...
1841
		}
1842
1843
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1844
			return new \WP_Error( 'access_token', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'access_token'.

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

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

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

Loading history...
1845
		}
1846
1847
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1848
			return new \WP_Error( 'token_type', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_type'.

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

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

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

Loading history...
1849
		}
1850
1851
		if ( empty( $json->scope ) ) {
1852
			return new \WP_Error( 'scope', 'No Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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

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

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

Loading history...
1853
		}
1854
1855
		// TODO: get rid of the error silencer.
1856
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1857
		@list( $role, $hmac ) = explode( ':', $json->scope );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1858
		if ( empty( $role ) || empty( $hmac ) ) {
1859
			return new \WP_Error( 'scope', 'Malformed Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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

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

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

Loading history...
1860
		}
1861
1862
		if ( $this->sign_role( $role ) !== $json->scope ) {
1863
			return new \WP_Error( 'scope', 'Invalid Scope', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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

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

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

Loading history...
1864
		}
1865
1866
		$cap = $roles->translate_role_to_cap( $role );
1867
		if ( ! $cap ) {
1868
			return new \WP_Error( 'scope', 'No Cap', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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

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

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

Loading history...
1869
		}
1870
1871
		if ( ! current_user_can( $cap ) ) {
1872
			return new \WP_Error( 'scope', 'current_user_cannot', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'scope'.

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

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

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

Loading history...
1873
		}
1874
1875
		/**
1876
		 * Fires after user has successfully received an auth token.
1877
		 *
1878
		 * @since 3.9.0
1879
		 */
1880
		do_action( 'jetpack_user_authorized' );
1881
1882
		return (string) $json->access_token;
1883
	}
1884
1885
	/**
1886
	 * Increases the request timeout value to 30 seconds.
1887
	 *
1888
	 * @return int Returns 30.
1889
	 */
1890
	public function increase_timeout() {
1891
		return 30;
1892
	}
1893
1894
	/**
1895
	 * Builds a URL to the Jetpack connection auth page.
1896
	 *
1897
	 * @param WP_User $user (optional) defaults to the current logged in user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user not be WP_User|null?

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

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

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

Loading history...
1898
	 * @param String  $redirect (optional) a redirect URL to use instead of the default.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $redirect not be string|null?

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

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

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

Loading history...
1899
	 * @return string Connect URL.
1900
	 */
1901
	public function get_authorization_url( $user = null, $redirect = null ) {
1902
1903
		if ( empty( $user ) ) {
1904
			$user = wp_get_current_user();
1905
		}
1906
1907
		$roles       = new Roles();
1908
		$role        = $roles->translate_user_to_role( $user );
1909
		$signed_role = $this->sign_role( $role );
1910
1911
		/**
1912
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1913
		 * data processing.
1914
		 *
1915
		 * @since 8.0.0
1916
		 *
1917
		 * @param string $redirect_url Defaults to the site admin URL.
1918
		 */
1919
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1920
1921
		/**
1922
		 * Filter the URL to redirect the user back to when the authorization process
1923
		 * is complete.
1924
		 *
1925
		 * @since 8.0.0
1926
		 *
1927
		 * @param string $redirect_url Defaults to the site URL.
1928
		 */
1929
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1930
1931
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1932
1933
		/**
1934
		 * Filter the type of authorization.
1935
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1936
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1937
		 *
1938
		 * @since 4.3.3
1939
		 *
1940
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1941
		 */
1942
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1943
1944
		/**
1945
		 * Filters the user connection request data for additional property addition.
1946
		 *
1947
		 * @since 8.0.0
1948
		 *
1949
		 * @param array $request_data request data.
1950
		 */
1951
		$body = apply_filters(
1952
			'jetpack_connect_request_body',
1953
			array(
1954
				'response_type' => 'code',
1955
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1956
				'redirect_uri'  => add_query_arg(
1957
					array(
1958
						'action'   => 'authorize',
1959
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1960
						'redirect' => rawurlencode( $redirect ),
1961
					),
1962
					esc_url( $processing_url )
1963
				),
1964
				'state'         => $user->ID,
1965
				'scope'         => $signed_role,
1966
				'user_email'    => $user->user_email,
1967
				'user_login'    => $user->user_login,
1968
				'is_active'     => $this->is_active(),
1969
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1970
				'auth_type'     => $auth_type,
1971
				'secret'        => $secrets['secret_1'],
1972
				'blogname'      => get_option( 'blogname' ),
1973
				'site_url'      => site_url(),
1974
				'home_url'      => home_url(),
1975
				'site_icon'     => get_site_icon_url(),
1976
				'site_lang'     => get_locale(),
1977
				'site_created'  => $this->get_assumed_site_creation_date(),
1978
			)
1979
		);
1980
1981
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1982
1983
		$api_url = $this->api_url( 'authorize' );
1984
1985
		return add_query_arg( $body, $api_url );
1986
	}
1987
1988
	/**
1989
	 * Authorizes the user by obtaining and storing the user token.
1990
	 *
1991
	 * @param array $data The request data.
1992
	 * @return string|\WP_Error Returns a string on success.
1993
	 *                          Returns a \WP_Error on failure.
1994
	 */
1995
	public function authorize( $data = array() ) {
1996
		/**
1997
		 * Action fired when user authorization starts.
1998
		 *
1999
		 * @since 8.0.0
2000
		 */
2001
		do_action( 'jetpack_authorize_starting' );
2002
2003
		$roles = new Roles();
2004
		$role  = $roles->translate_current_user_to_role();
2005
2006
		if ( ! $role ) {
2007
			return new \WP_Error( 'no_role', 'Invalid request.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_role'.

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

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

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

Loading history...
2008
		}
2009
2010
		$cap = $roles->translate_role_to_cap( $role );
2011
		if ( ! $cap ) {
2012
			return new \WP_Error( 'no_cap', 'Invalid request.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_cap'.

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

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

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

Loading history...
2013
		}
2014
2015
		if ( ! empty( $data['error'] ) ) {
2016
			return new \WP_Error( $data['error'], 'Error included in the request.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $data['error'].

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

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

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

Loading history...
2017
		}
2018
2019
		if ( ! isset( $data['state'] ) ) {
2020
			return new \WP_Error( 'no_state', 'Request must include state.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_state'.

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

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

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

Loading history...
2021
		}
2022
2023
		if ( ! ctype_digit( $data['state'] ) ) {
2024
			return new \WP_Error( $data['error'], 'State must be an integer.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $data['error'].

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

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

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

Loading history...
2025
		}
2026
2027
		$current_user_id = get_current_user_id();
2028
		if ( $current_user_id !== (int) $data['state'] ) {
2029
			return new \WP_Error( 'wrong_state', 'State does not match current user.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'wrong_state'.

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

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

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

Loading history...
2030
		}
2031
2032
		if ( empty( $data['code'] ) ) {
2033
			return new \WP_Error( 'no_code', 'Request must include an authorization code.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_code'.

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

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

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

Loading history...
2034
		}
2035
2036
		$token = $this->get_token( $data );
2037
2038 View Code Duplication
		if ( is_wp_error( $token ) ) {
2039
			$code = $token->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

Loading history...
2040
			if ( empty( $code ) ) {
2041
				$code = 'invalid_token';
2042
			}
2043
			return new \WP_Error( $code, $token->get_error_message(), 400 );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

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

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

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

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

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

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

Loading history...
2044
		}
2045
2046
		if ( ! $token ) {
2047
			return new \WP_Error( 'no_token', 'Error generating token.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_token'.

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

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

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

Loading history...
2048
		}
2049
2050
		$is_master_user = ! $this->is_active();
2051
2052
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
2053
2054
		if ( ! $is_master_user ) {
2055
			/**
2056
			 * Action fired when a secondary user has been authorized.
2057
			 *
2058
			 * @since 8.0.0
2059
			 */
2060
			do_action( 'jetpack_authorize_ending_linked' );
2061
			return 'linked';
2062
		}
2063
2064
		/**
2065
		 * Action fired when the master user has been authorized.
2066
		 *
2067
		 * @since 8.0.0
2068
		 *
2069
		 * @param array $data The request data.
2070
		 */
2071
		do_action( 'jetpack_authorize_ending_authorized', $data );
2072
2073
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
2074
2075
		// Start nonce cleaner.
2076
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2077
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
2078
2079
		return 'authorized';
2080
	}
2081
2082
	/**
2083
	 * Disconnects from the Jetpack servers.
2084
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2085
	 */
2086
	public function disconnect_site() {
2087
2088
	}
2089
2090
	/**
2091
	 * The Base64 Encoding of the SHA1 Hash of the Input.
2092
	 *
2093
	 * @param string $text The string to hash.
2094
	 * @return string
2095
	 */
2096
	public function sha1_base64( $text ) {
2097
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2098
	}
2099
2100
	/**
2101
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
2102
	 *
2103
	 * @param string $domain The domain to check.
2104
	 *
2105
	 * @return bool|WP_Error
2106
	 */
2107
	public function is_usable_domain( $domain ) {
2108
2109
		// If it's empty, just fail out.
2110
		if ( ! $domain ) {
2111
			return new \WP_Error(
2112
				'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...
2113
				/* translators: %1$s is a domain name. */
2114
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
2115
			);
2116
		}
2117
2118
		/**
2119
		 * Skips the usuable domain check when connecting a site.
2120
		 *
2121
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
2122
		 *
2123
		 * @since 4.1.0
2124
		 *
2125
		 * @param bool If the check should be skipped. Default false.
2126
		 */
2127
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
2128
			return true;
2129
		}
2130
2131
		// None of the explicit localhosts.
2132
		$forbidden_domains = array(
2133
			'wordpress.com',
2134
			'localhost',
2135
			'localhost.localdomain',
2136
			'127.0.0.1',
2137
			'local.wordpress.test',         // VVV pattern.
2138
			'local.wordpress-trunk.test',   // VVV pattern.
2139
			'src.wordpress-develop.test',   // VVV pattern.
2140
			'build.wordpress-develop.test', // VVV pattern.
2141
		);
2142 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
2143
			return new \WP_Error(
2144
				'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...
2145
				sprintf(
2146
					/* translators: %1$s is a domain name. */
2147
					__(
2148
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
2149
						'jetpack'
2150
					),
2151
					$domain
2152
				)
2153
			);
2154
		}
2155
2156
		// No .test or .local domains.
2157 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
2158
			return new \WP_Error(
2159
				'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...
2160
				sprintf(
2161
					/* translators: %1$s is a domain name. */
2162
					__(
2163
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
2164
						'jetpack'
2165
					),
2166
					$domain
2167
				)
2168
			);
2169
		}
2170
2171
		// No WPCOM subdomains.
2172 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
2173
			return new \WP_Error(
2174
				'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...
2175
				sprintf(
2176
					/* translators: %1$s is a domain name. */
2177
					__(
2178
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
2179
						'jetpack'
2180
					),
2181
					$domain
2182
				)
2183
			);
2184
		}
2185
2186
		// If PHP was compiled without support for the Filter module (very edge case).
2187
		if ( ! function_exists( 'filter_var' ) ) {
2188
			// Just pass back true for now, and let wpcom sort it out.
2189
			return true;
2190
		}
2191
2192
		return true;
2193
	}
2194
2195
	/**
2196
	 * Gets the requested token.
2197
	 *
2198
	 * Tokens are one of two types:
2199
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
2200
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
2201
	 *    are not associated with a user account. They represent the site's connection with
2202
	 *    the Jetpack servers.
2203
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
2204
	 *
2205
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
2206
	 * token, and $private is a secret that should never be displayed anywhere or sent
2207
	 * over the network; it's used only for signing things.
2208
	 *
2209
	 * Blog Tokens can be "Normal" or "Special".
2210
	 * * Normal: The result of a normal connection flow. They look like
2211
	 *   "{$random_string_1}.{$random_string_2}"
2212
	 *   That is, $token_key and $private are both random strings.
2213
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
2214
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
2215
	 *   constant (rare).
2216
	 * * Special: A connection token for sites that have gone through an alternative
2217
	 *   connection flow. They look like:
2218
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
2219
	 *   That is, $private is a random string and $token_key has a special structure with
2220
	 *   lots of semicolons.
2221
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
2222
	 *   JETPACK_BLOG_TOKEN constant.
2223
	 *
2224
	 * In particular, note that Normal Blog Tokens never start with ";" and that
2225
	 * Special Blog Tokens always do.
2226
	 *
2227
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
2228
	 * order:
2229
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
2230
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
2231
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
2232
	 *
2233
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
2234
	 * @param string|false $token_key If provided, check that the token matches the provided input.
2235
	 * @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.
2236
	 *
2237
	 * @return object|false
2238
	 */
2239
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
2240
		$possible_special_tokens = array();
2241
		$possible_normal_tokens  = array();
2242
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
2243
2244
		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...
2245
			if ( ! $user_tokens ) {
2246
				return $suppress_errors ? false : new \WP_Error( 'no_user_tokens', __( 'No user tokens found', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_user_tokens'.

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

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

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

Loading history...
2247
			}
2248
			if ( self::JETPACK_MASTER_USER === $user_id ) {
2249
				$user_id = \Jetpack_Options::get_option( 'master_user' );
2250
				if ( ! $user_id ) {
2251
					return $suppress_errors ? false : new \WP_Error( 'empty_master_user_option', __( 'No primary user defined', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'empty_master_user_option'.

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

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

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

Loading history...
2252
				}
2253
			}
2254
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
2255
				// translators: %s is the user ID.
2256
				return $suppress_errors ? false : new \WP_Error( 'no_token_for_user', sprintf( __( 'No token for user %d', 'jetpack' ), $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_token_for_user'.

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

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

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

Loading history...
2257
			}
2258
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
2259 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
2260
				// translators: %s is the user ID.
2261
				return $suppress_errors ? false : new \WP_Error( 'token_malformed', sprintf( __( 'Token for user %d is malformed', 'jetpack' ), $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'token_malformed'.

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

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

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

Loading history...
2262
			}
2263
			if ( $user_token_chunks[2] !== (string) $user_id ) {
2264
				// translators: %1$d is the ID of the requested user. %2$d is the user ID found in the token.
2265
				return $suppress_errors ? false : new \WP_Error( 'user_id_mismatch', sprintf( __( 'Requesting user_id %1$d does not match token user_id %2$d', 'jetpack' ), $user_id, $user_token_chunks[2] ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'user_id_mismatch'.

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

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

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

Loading history...
2266
			}
2267
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
2268
		} else {
2269
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
2270
			if ( $stored_blog_token ) {
2271
				$possible_normal_tokens[] = $stored_blog_token;
2272
			}
2273
2274
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
2275
2276
			if ( $defined_tokens_string ) {
2277
				$defined_tokens = explode( ',', $defined_tokens_string );
2278
				foreach ( $defined_tokens as $defined_token ) {
2279
					if ( ';' === $defined_token[0] ) {
2280
						$possible_special_tokens[] = $defined_token;
2281
					} else {
2282
						$possible_normal_tokens[] = $defined_token;
2283
					}
2284
				}
2285
			}
2286
		}
2287
2288
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2289
			$possible_tokens = $possible_normal_tokens;
2290
		} else {
2291
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
2292
		}
2293
2294
		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...
2295
			// If no user tokens were found, it would have failed earlier, so this is about blog token.
2296
			return $suppress_errors ? false : new \WP_Error( 'no_possible_tokens', __( 'No blog token found', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_possible_tokens'.

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

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

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

Loading history...
2297
		}
2298
2299
		$valid_token = false;
2300
2301
		if ( false === $token_key ) {
2302
			// Use first token.
2303
			$valid_token = $possible_tokens[0];
2304
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2305
			// Use first normal token.
2306
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
2307
		} else {
2308
			// Use the token matching $token_key or false if none.
2309
			// Ensure we check the full key.
2310
			$token_check = rtrim( $token_key, '.' ) . '.';
2311
2312
			foreach ( $possible_tokens as $possible_token ) {
2313
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
2314
					$valid_token = $possible_token;
2315
					break;
2316
				}
2317
			}
2318
		}
2319
2320
		if ( ! $valid_token ) {
2321
			if ( $user_id ) {
2322
				// translators: %d is the user ID.
2323
				return $suppress_errors ? false : new \WP_Error( 'no_valid_token', sprintf( __( 'Invalid token for user %d', 'jetpack' ), $user_id ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_valid_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...
2324
			} else {
2325
				return $suppress_errors ? false : new \WP_Error( 'no_valid_token', __( 'Invalid blog token', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_valid_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...
2326
			}
2327
		}
2328
2329
		return (object) array(
2330
			'secret'           => $valid_token,
2331
			'external_user_id' => (int) $user_id,
2332
		);
2333
	}
2334
2335
	/**
2336
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2337
	 * since it is passed by reference to various methods.
2338
	 * Capture it here so we can verify the signature later.
2339
	 *
2340
	 * @param array $methods an array of available XMLRPC methods.
2341
	 * @return array the same array, since this method doesn't add or remove anything.
2342
	 */
2343
	public function xmlrpc_methods( $methods ) {
2344
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
2345
		return $methods;
2346
	}
2347
2348
	/**
2349
	 * Resets the raw post data parameter for testing purposes.
2350
	 */
2351
	public function reset_raw_post_data() {
2352
		$this->raw_post_data = null;
2353
	}
2354
2355
	/**
2356
	 * Registering an additional method.
2357
	 *
2358
	 * @param array $methods an array of available XMLRPC methods.
2359
	 * @return array the amended array in case the method is added.
2360
	 */
2361
	public function public_xmlrpc_methods( $methods ) {
2362
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2363
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2364
		}
2365
		return $methods;
2366
	}
2367
2368
	/**
2369
	 * Handles a getOptions XMLRPC method call.
2370
	 *
2371
	 * @param array $args method call arguments.
2372
	 * @return an amended XMLRPC server options array.
2373
	 */
2374
	public function jetpack_get_options( $args ) {
2375
		global $wp_xmlrpc_server;
2376
2377
		$wp_xmlrpc_server->escape( $args );
2378
2379
		$username = $args[1];
2380
		$password = $args[2];
2381
2382
		$user = $wp_xmlrpc_server->login( $username, $password );
2383
		if ( ! $user ) {
2384
			return $wp_xmlrpc_server->error;
2385
		}
2386
2387
		$options   = array();
2388
		$user_data = $this->get_connected_user_data();
2389
		if ( is_array( $user_data ) ) {
2390
			$options['jetpack_user_id']         = array(
2391
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2392
				'readonly' => true,
2393
				'value'    => $user_data['ID'],
2394
			);
2395
			$options['jetpack_user_login']      = array(
2396
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2397
				'readonly' => true,
2398
				'value'    => $user_data['login'],
2399
			);
2400
			$options['jetpack_user_email']      = array(
2401
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2402
				'readonly' => true,
2403
				'value'    => $user_data['email'],
2404
			);
2405
			$options['jetpack_user_site_count'] = array(
2406
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2407
				'readonly' => true,
2408
				'value'    => $user_data['site_count'],
2409
			);
2410
		}
2411
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2412
		$args                           = stripslashes_deep( $args );
2413
		return $wp_xmlrpc_server->wp_getOptions( $args );
2414
	}
2415
2416
	/**
2417
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2418
	 *
2419
	 * @param array $options standard Core options.
2420
	 * @return array amended options.
2421
	 */
2422
	public function xmlrpc_options( $options ) {
2423
		$jetpack_client_id = false;
2424
		if ( $this->is_active() ) {
2425
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2426
		}
2427
		$options['jetpack_version'] = array(
2428
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2429
			'readonly' => true,
2430
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2431
		);
2432
2433
		$options['jetpack_client_id'] = array(
2434
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2435
			'readonly' => true,
2436
			'value'    => $jetpack_client_id,
2437
		);
2438
		return $options;
2439
	}
2440
2441
	/**
2442
	 * Resets the saved authentication state in between testing requests.
2443
	 */
2444
	public function reset_saved_auth_state() {
2445
		$this->xmlrpc_verification = null;
2446
	}
2447
2448
	/**
2449
	 * Sign a user role with the master access token.
2450
	 * If not specified, will default to the current user.
2451
	 *
2452
	 * @access public
2453
	 *
2454
	 * @param string $role    User role.
2455
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
2456
	 * @return string Signed user role.
2457
	 */
2458
	public function sign_role( $role, $user_id = null ) {
2459
		if ( empty( $user_id ) ) {
2460
			$user_id = (int) get_current_user_id();
2461
		}
2462
2463
		if ( ! $user_id ) {
2464
			return false;
2465
		}
2466
2467
		$token = $this->get_access_token();
2468
		if ( ! $token || is_wp_error( $token ) ) {
2469
			return false;
2470
		}
2471
2472
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2473
	}
2474
2475
	/**
2476
	 * Set the plugin instance.
2477
	 *
2478
	 * @param Plugin $plugin_instance The plugin instance.
2479
	 *
2480
	 * @return $this
2481
	 */
2482
	public function set_plugin_instance( Plugin $plugin_instance ) {
2483
		$this->plugin = $plugin_instance;
2484
2485
		return $this;
2486
	}
2487
2488
	/**
2489
	 * Retrieve the plugin management object.
2490
	 *
2491
	 * @return Plugin
2492
	 */
2493
	public function get_plugin() {
2494
		return $this->plugin;
2495
	}
2496
2497
	/**
2498
	 * Get all connected plugins information, excluding those disconnected by user.
2499
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2500
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2501
	 * so please make sure not to run the method too early in the code.
2502
	 *
2503
	 * @return array|WP_Error
2504
	 */
2505
	public function get_connected_plugins() {
2506
		$maybe_plugins = Plugin_Storage::get_all( true );
2507
2508
		if ( $maybe_plugins instanceof WP_Error ) {
2509
			return $maybe_plugins;
2510
		}
2511
2512
		return $maybe_plugins;
2513
	}
2514
2515
	/**
2516
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2517
	 * Note: this method does not remove any access tokens.
2518
	 *
2519
	 * @return bool
2520
	 */
2521
	public function disable_plugin() {
2522
		if ( ! $this->plugin ) {
2523
			return false;
2524
		}
2525
2526
		return $this->plugin->disable();
2527
	}
2528
2529
	/**
2530
	 * Force plugin reconnect after user-initiated disconnect.
2531
	 * After its called, the plugin will be allowed to use the connection again.
2532
	 * Note: this method does not initialize access tokens.
2533
	 *
2534
	 * @return bool
2535
	 */
2536
	public function enable_plugin() {
2537
		if ( ! $this->plugin ) {
2538
			return false;
2539
		}
2540
2541
		return $this->plugin->enable();
2542
	}
2543
2544
	/**
2545
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2546
	 * If no plugin slug was passed into the constructor, always returns true.
2547
	 *
2548
	 * @return bool
2549
	 */
2550
	public function is_plugin_enabled() {
2551
		if ( ! $this->plugin ) {
2552
			return true;
2553
		}
2554
2555
		return $this->plugin->is_enabled();
2556
	}
2557
2558
	/**
2559
	 * Perform the API request to refrsh the blog token.
2560
	 * Note that we are making this request on behalf of the Jetpack master user,
2561
	 * given they were (most probably) the ones that registered the site at the first place.
2562
	 *
2563
	 * @return WP_Error|bool The result of updating the blog_token option.
2564
	 */
2565
	public static function refresh_blog_token() {
2566
		$url     = sprintf(
2567
			'%s://%s/%s/v%s/%s',
2568
			Client::protocol(),
2569
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_HOST' ),
2570
			'wpcom',
2571
			'2',
2572
			'jetpack-refresh-blog-token'
2573
		);
2574
		$method  = 'GET';
2575
		$user_id = JETPACK_MASTER_USER;
2576
2577
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2578
2579
		if ( is_wp_error( $response ) ) {
2580
			return new \WP_Error( 'refresh_blog_token_http_request_failed', $response->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

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

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

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

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

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

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

Loading history...
2581
		}
2582
2583
		$code   = wp_remote_retrieve_response_code( $response );
2584
		$entity = wp_remote_retrieve_body( $response );
2585
2586
		if ( $entity ) {
2587
			$json = json_decode( $entity );
2588
		} else {
2589
			$json = false;
2590
		}
2591
2592 View Code Duplication
		if ( 200 !== $code || ! empty( $json->error ) ) {
2593
			if ( empty( $json->error ) ) {
2594
				return new \WP_Error( 'unknown', '', $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown'.

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

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

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

Loading history...
2595
			}
2596
2597
			/* translators: Error description string. */
2598
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
2599
2600
			return new \WP_Error( (string) $json->error, $error_description, $code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with (string) $json->error.

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

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

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

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

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

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

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

Loading history...
2605
		}
2606
2607
		return \Jetpack_Options::update_option( 'blog_token', (string) $json->jetpack_secret );
2608
	}
2609
2610
	/**
2611
	 * Fetches a signed token.
2612
	 *
2613
	 * @param string $token the token.
2614
	 * @return string a signed token
2615
	 */
2616
	public function get_signed_token( $token ) {
2617
		list( $token_key, $token_secret ) = explode( '.', $token->secret );
2618
2619
		$token_key = sprintf(
2620
			'%s:%d:%d',
2621
			$token_key,
2622
			Constants::get_constant( 'JETPACK__API_VERSION' ),
2623
			$token->external_user_id
2624
		);
2625
2626
		$timestamp = time();
2627
2628 View Code Duplication
		if ( function_exists( 'wp_generate_password' ) ) {
2629
			$nonce = wp_generate_password( 10, false );
2630
		} else {
2631
			$nonce = substr( sha1( wp_rand( 0, 1000000 ) ), 0, 10 );
2632
		}
2633
2634
		$normalized_request_string = join(
2635
			"\n",
2636
			array(
2637
				$token_key,
2638
				$timestamp,
2639
				$nonce,
2640
			)
2641
		) . "\n";
2642
2643
		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2644
		$signature = base64_encode( hash_hmac( 'sha1', $normalized_request_string, $token_secret, true ) );
2645
2646
		$auth = array(
2647
			'token'     => $token_key,
2648
			'timestamp' => $timestamp,
2649
			'nonce'     => $nonce,
2650
			'signature' => $signature,
2651
		);
2652
2653
		$header_pieces = array();
2654
		foreach ( $auth as $key => $value ) {
2655
			$header_pieces[] = sprintf( '%s="%s"', $key, $value );
2656
		}
2657
2658
		return join( ' ', $header_pieces );
2659
	}
2660
2661
}
2662