Completed
Push — add/connection-error-handling ( 525cd7...e29761 )
by
unknown
07:01
created

Manager::get_connection_owner_id()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
nc 2
nop 0
dl 9
loc 9
rs 9.9666
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\Tracking;
13
14
/**
15
 * The Jetpack Connection Manager class that is used as a single gateway between WordPress.com
16
 * and Jetpack.
17
 */
18
class Manager {
19
20
	const SECRETS_MISSING        = 'secrets_missing';
21
	const SECRETS_EXPIRED        = 'secrets_expired';
22
	const SECRETS_OPTION_NAME    = 'jetpack_secrets';
23
	const MAGIC_NORMAL_TOKEN_KEY = ';normal;';
24
	const JETPACK_MASTER_USER    = true;
25
26
	/**
27
	 * The procedure that should be run to generate secrets.
28
	 *
29
	 * @var Callable
30
	 */
31
	protected $secret_callable;
32
33
	/**
34
	 * A copy of the raw POST data for signature verification purposes.
35
	 *
36
	 * @var String
37
	 */
38
	protected $raw_post_data;
39
40
	/**
41
	 * Verification data needs to be stored to properly verify everything.
42
	 *
43
	 * @var Object
44
	 */
45
	private $xmlrpc_verification = null;
46
47
	/**
48
	 * Plugin management object.
49
	 *
50
	 * @var Plugin
51
	 */
52
	private $plugin = null;
53
54
	/**
55
	 * Initialize the object.
56
	 * Make sure to call the "Configure" first.
57
	 *
58
	 * @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...
59
	 *
60
	 * @see \Automattic\Jetpack\Config
61
	 */
62
	public function __construct( $plugin_slug = null ) {
63
		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...
64
			$this->set_plugin_instance( new Plugin( $plugin_slug ) );
65
		}
66
	}
67
68
	/**
69
	 * Initializes required listeners. This is done separately from the constructors
70
	 * because some objects sometimes need to instantiate separate objects of this class.
71
	 *
72
	 * @todo Implement a proper nonce verification.
73
	 */
74
	public static function configure() {
75
		$manager = new self();
76
77
		$manager->setup_xmlrpc_handlers(
78
			$_GET, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
79
			$manager->is_active(),
80
			$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...
81
		);
82
83
		if ( $manager->is_active() ) {
84
			add_filter( 'xmlrpc_methods', array( $manager, 'public_xmlrpc_methods' ) );
85
		} else {
86
			add_action( 'rest_api_init', array( $manager, 'initialize_rest_api_registration_connector' ) );
87
		}
88
89
		add_action( 'jetpack_clean_nonces', array( $manager, 'clean_nonces' ) );
90
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
91
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
92
		}
93
94
		add_filter(
95
			'jetpack_constant_default_value',
96
			__NAMESPACE__ . '\Utils::jetpack_api_constant_filter',
97
			10,
98
			2
99
		);
100
101
		add_action( 'plugins_loaded', __NAMESPACE__ . '\Plugin_Storage::configure', 100 );
102
103
		$manager->error_handler = new Error_Handler();
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...
104
		add_action( 'admin_notices', array( $manager->error_handler, 'admin_notices' ) );
105
106
	}
107
108
	/**
109
	 * Sets up the XMLRPC request handlers.
110
	 *
111
	 * @param array                  $request_params incoming request parameters.
112
	 * @param Boolean                $is_active whether the connection is currently active.
113
	 * @param Boolean                $is_signed whether the signature check has been successful.
114
	 * @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...
115
	 */
116
	public function setup_xmlrpc_handlers(
117
		$request_params,
118
		$is_active,
119
		$is_signed,
120
		\Jetpack_XMLRPC_Server $xmlrpc_server = null
121
	) {
122
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ), 1000, 2 );
123
124
		if (
125
			! isset( $request_params['for'] )
126
			|| 'jetpack' !== $request_params['for']
127
		) {
128
			return false;
129
		}
130
131
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms.
132
		if (
133
			isset( $request_params['jetpack'] )
134
			&& 'comms' === $request_params['jetpack']
135
		) {
136
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
137
				// Use the real constant here for WordPress' sake.
138
				define( 'XMLRPC_REQUEST', true );
139
			}
140
141
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
142
143
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
144
		}
145
146
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
147
			return false;
148
		}
149
		// Display errors can cause the XML to be not well formed.
150
		@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...
151
152
		if ( $xmlrpc_server ) {
153
			$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...
154
		} else {
155
			$this->xmlrpc_server = new \Jetpack_XMLRPC_Server();
156
		}
157
158
		$this->require_jetpack_authentication();
159
160
		if ( $is_active ) {
161
			// Hack to preserve $HTTP_RAW_POST_DATA.
162
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
163
164
			if ( $is_signed ) {
165
				// The actual API methods.
166
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
167
			} else {
168
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
169
				// active Jetpack connection, so that additional users can link their account.
170
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
171
			}
172
		} else {
173
			// The bootstrap API methods.
174
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
175
176
			if ( $is_signed ) {
177
				// The jetpack Provision method is available for blog-token-signed requests.
178
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
179
			} else {
180
				new XMLRPC_Connector( $this );
181
			}
182
		}
183
184
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
185
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
186
		return true;
187
	}
188
189
	/**
190
	 * Initializes the REST API connector on the init hook.
191
	 */
192
	public function initialize_rest_api_registration_connector() {
193
		new REST_Connector( $this );
194
	}
195
196
	/**
197
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
198
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
199
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
200
	 * which is accessible via a different URI. Most of the below is copied directly
201
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
202
	 *
203
	 * @todo Tighten $wp_xmlrpc_server_class a bit to make sure it doesn't do bad things.
204
	 */
205
	public function alternate_xmlrpc() {
206
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
207
		// phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
208
		global $HTTP_RAW_POST_DATA;
209
210
		// Some browser-embedded clients send cookies. We don't want them.
211
		$_COOKIE = array();
212
213
		// A fix for mozBlog and other cases where '<?xml' isn't on the very first line.
214
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
215
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
216
		}
217
218
		// phpcs:enable
219
220
		include_once ABSPATH . 'wp-admin/includes/admin.php';
221
		include_once ABSPATH . WPINC . '/class-IXR.php';
222
		include_once ABSPATH . WPINC . '/class-wp-xmlrpc-server.php';
223
224
		/**
225
		 * Filters the class used for handling XML-RPC requests.
226
		 *
227
		 * @since 3.1.0
228
		 *
229
		 * @param string $class The name of the XML-RPC server class.
230
		 */
231
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
232
		$wp_xmlrpc_server       = new $wp_xmlrpc_server_class();
233
234
		// Fire off the request.
235
		nocache_headers();
236
		$wp_xmlrpc_server->serve_request();
237
238
		exit;
239
	}
240
241
	/**
242
	 * Removes all XML-RPC methods that are not `jetpack.*`.
243
	 * Only used in our alternate XML-RPC endpoint, where we want to
244
	 * ensure that Core and other plugins' methods are not exposed.
245
	 *
246
	 * @param array $methods a list of registered WordPress XMLRPC methods.
247
	 * @return array filtered $methods
248
	 */
249
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
250
		$jetpack_methods = array();
251
252
		foreach ( $methods as $method => $callback ) {
253
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
254
				$jetpack_methods[ $method ] = $callback;
255
			}
256
		}
257
258
		return $jetpack_methods;
259
	}
260
261
	/**
262
	 * Removes all other authentication methods not to allow other
263
	 * methods to validate unauthenticated requests.
264
	 */
265
	public function require_jetpack_authentication() {
266
		// Don't let anyone authenticate.
267
		$_COOKIE = array();
268
		remove_all_filters( 'authenticate' );
269
		remove_all_actions( 'wp_login_failed' );
270
271
		if ( $this->is_active() ) {
272
			// Allow Jetpack authentication.
273
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
274
		}
275
	}
276
277
	/**
278
	 * Authenticates XML-RPC and other requests from the Jetpack Server
279
	 *
280
	 * @param WP_User|Mixed $user user object if authenticated.
281
	 * @param String        $username username.
282
	 * @param String        $password password string.
283
	 * @return WP_User|Mixed authenticated user or error.
284
	 */
285
	public function authenticate_jetpack( $user, $username, $password ) {
286
		if ( is_a( $user, '\\WP_User' ) ) {
287
			return $user;
288
		}
289
290
		$token_details = $this->verify_xml_rpc_signature();
291
292
		if ( ! $token_details ) {
293
			return $user;
294
		}
295
296
		if ( 'user' !== $token_details['type'] ) {
297
			return $user;
298
		}
299
300
		if ( ! $token_details['user_id'] ) {
301
			return $user;
302
		}
303
304
		nocache_headers();
305
306
		return new \WP_User( $token_details['user_id'] );
307
	}
308
309
	/**
310
	 * Verifies the signature of the current request.
311
	 *
312
	 * @return false|array
313
	 */
314
	public function verify_xml_rpc_signature() {
315
		if ( is_null( $this->xmlrpc_verification ) ) {
316
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
317
318
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
319
				/**
320
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
321
				 *
322
				 * @since 7.5.0
323
				 *
324
				 * @param WP_Error $signature_verification_error The verification error
325
				 */
326
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
327
328
				$error_handler = new Error_Handler();
329
				$error_handler->report_error( $this->xmlrpc_verification );
330
331
			}
332
		}
333
334
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
335
	}
336
337
	/**
338
	 * Verifies the signature of the current request.
339
	 *
340
	 * This function has side effects and should not be used. Instead,
341
	 * use the memoized version `->verify_xml_rpc_signature()`.
342
	 *
343
	 * @internal
344
	 * @todo Refactor to use proper nonce verification.
345
	 */
346
	private function internal_verify_xml_rpc_signature() {
347
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
348
		// It's not for us.
349
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
350
			return false;
351
		}
352
353
		$signature_details = array(
354
			'token'     => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
355
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
356
			'nonce'     => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
357
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
358
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
359
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
360
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
361
		);
362
363
		// var_dump($_POST); die;
364
365
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
366
		@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...
367
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
368
369
		$jetpack_api_version = Constants::get_constant( 'JETPACK__API_VERSION' );
370
371
		if (
372
			empty( $token_key )
373
		||
374
			empty( $version ) || strval( $jetpack_api_version ) !== $version ) {
375
			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...
376
		}
377
378
		if ( '0' === $user_id ) {
379
			$token_type = 'blog';
380
			$user_id    = 0;
381
		} else {
382
			$token_type = 'user';
383
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
384
				return new \WP_Error(
385
					'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...
386
					'Malformed user_id in request',
387
					compact( 'signature_details' )
388
				);
389
			}
390
			$user_id = (int) $user_id;
391
392
			$user = new \WP_User( $user_id );
393
			if ( ! $user || ! $user->exists() ) {
394
				return new \WP_Error(
395
					'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...
396
					sprintf( 'User %d does not exist', $user_id ),
397
					compact( 'signature_details' )
398
				);
399
			}
400
		}
401
402
		$token = $this->get_access_token( $user_id, $token_key, false );
403
		if ( is_wp_error( $token ) ) {
404
			$token->add_data( compact( 'signature_details' ) );
405
			return $token;
406
		} elseif ( ! $token ) {
407
			return new \WP_Error(
408
				'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...
409
				sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ),
410
				compact( 'signature_details' )
411
			);
412
		}
413
414
		$jetpack_signature = new \Jetpack_Signature( $token->secret, (int) \Jetpack_Options::get_option( 'time_diff' ) );
415
		// phpcs:disable WordPress.Security.NonceVerification.Missing
416
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
417
			$post_data   = $_POST;
418
			$file_hashes = array();
419
			foreach ( $post_data as $post_data_key => $post_data_value ) {
420
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
421
					continue;
422
				}
423
				$post_data_key                 = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
424
				$file_hashes[ $post_data_key ] = $post_data_value;
425
			}
426
427
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
428
				unset( $post_data[ "_jetpack_file_hmac_{$post_data_key}" ] );
429
				$post_data[ $post_data_key ] = $post_data_value;
430
			}
431
432
			ksort( $post_data );
433
434
			$body = http_build_query( stripslashes_deep( $post_data ) );
435
		} elseif ( is_null( $this->raw_post_data ) ) {
436
			$body = file_get_contents( 'php://input' );
437
		} else {
438
			$body = null;
439
		}
440
		// phpcs:enable
441
442
		$signature = $jetpack_signature->sign_current_request(
443
			array( 'body' => is_null( $body ) ? $this->raw_post_data : $body )
444
		);
445
446
		$signature_details['url'] = $jetpack_signature->current_request_url;
447
448
		if ( ! $signature ) {
449
			return new \WP_Error(
450
				'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...
451
				'Unknown signature error',
452
				compact( 'signature_details' )
453
			);
454
		} elseif ( is_wp_error( $signature ) ) {
455
			return $signature;
456
		}
457
458
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
459
		$timestamp = (int) $_GET['timestamp'];
460
		$nonce     = stripslashes( (string) $_GET['nonce'] );
461
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
462
463
		// Use up the nonce regardless of whether the signature matches.
464
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
465
			return new \WP_Error(
466
				'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...
467
				'Could not add nonce',
468
				compact( 'signature_details' )
469
			);
470
		}
471
472
		// Be careful about what you do with this debugging data.
473
		// If a malicious requester has access to the expected signature,
474
		// bad things might be possible.
475
		$signature_details['expected'] = $signature;
476
477
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
478
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
479
			return new \WP_Error(
480
				'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...
481
				'Signature mismatch',
482
				compact( 'signature_details' )
483
			);
484
		}
485
486
		/**
487
		 * Action for additional token checking.
488
		 *
489
		 * @since 7.7.0
490
		 *
491
		 * @param array $post_data request data.
492
		 * @param array $token_data token data.
493
		 */
494
		return apply_filters(
495
			'jetpack_signature_check_token',
496
			array(
497
				'type'      => $token_type,
498
				'token_key' => $token_key,
499
				'user_id'   => $token->external_user_id,
500
			),
501
			$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...
502
			$this->raw_post_data
503
		);
504
	}
505
506
	/**
507
	 * Returns true if the current site is connected to WordPress.com.
508
	 *
509
	 * @return Boolean is the site connected?
510
	 */
511
	public function is_active() {
512
		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...
513
	}
514
515
	/**
516
	 * Returns true if the site has both a token and a blog id, which indicates a site has been registered.
517
	 *
518
	 * @access public
519
	 *
520
	 * @return bool
521
	 */
522
	public function is_registered() {
523
		$blog_id   = \Jetpack_Options::get_option( 'id' );
524
		$has_token = $this->is_active();
525
		return $blog_id && $has_token;
526
	}
527
528
	/**
529
	 * Checks to see if the connection owner of the site is missing.
530
	 *
531
	 * @return bool
532
	 */
533
	public function is_missing_connection_owner() {
534
		$connection_owner = $this->get_connection_owner_id();
535
		if ( ! get_user_by( 'id', $connection_owner ) ) {
536
			return true;
537
		}
538
539
		return false;
540
	}
541
542
	/**
543
	 * Returns true if the user with the specified identifier is connected to
544
	 * WordPress.com.
545
	 *
546
	 * @param Integer|Boolean $user_id the user identifier.
547
	 * @return Boolean is the user connected?
548
	 */
549
	public function is_user_connected( $user_id = false ) {
550
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
551
		if ( ! $user_id ) {
552
			return false;
553
		}
554
555
		return (bool) $this->get_access_token( $user_id );
556
	}
557
558
	/**
559
	 * Returns the local user ID of the connection owner.
560
	 *
561
	 * @return string|int Returns the ID of the connection owner or False if no connection owner found.
562
	 */
563 View Code Duplication
	public function get_connection_owner_id() {
564
		$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...
565
		$connection_owner = false;
566
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
567
			$connection_owner = $user_token->external_user_id;
568
		}
569
570
		return $connection_owner;
571
	}
572
573
	/**
574
	 * Returns an array of user_id's that have user tokens for communicating with wpcom.
575
	 * Able to select by specific capability.
576
	 *
577
	 * @param string $capability The capability of the user.
578
	 * @return array Array of WP_User objects if found.
579
	 */
580
	public function get_connected_users( $capability = 'any' ) {
581
		$connected_users    = array();
582
		$connected_user_ids = array_keys( \Jetpack_Options::get_option( 'user_tokens' ) );
583
584
		if ( ! empty( $connected_user_ids ) ) {
585
			foreach ( $connected_user_ids as $id ) {
586
				// Check for capability.
587
				if ( 'any' !== $capability && ! user_can( $id, $capability ) ) {
588
					continue;
589
				}
590
591
				$connected_users[] = get_userdata( $id );
592
			}
593
		}
594
595
		return $connected_users;
596
	}
597
598
	/**
599
	 * Get the wpcom user data of the current|specified connected user.
600
	 *
601
	 * @todo Refactor to properly load the XMLRPC client independently.
602
	 *
603
	 * @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...
604
	 * @return Object the user object.
605
	 */
606 View Code Duplication
	public function get_connected_user_data( $user_id = null ) {
607
		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...
608
			$user_id = get_current_user_id();
609
		}
610
611
		$transient_key    = "jetpack_connected_user_data_$user_id";
612
		$cached_user_data = get_transient( $transient_key );
613
614
		if ( $cached_user_data ) {
615
			return $cached_user_data;
616
		}
617
618
		$xml = new \Jetpack_IXR_Client(
619
			array(
620
				'user_id' => $user_id,
621
			)
622
		);
623
		$xml->query( 'wpcom.getUser' );
624
		if ( ! $xml->isError() ) {
625
			$user_data = $xml->getResponse();
626
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
627
			return $user_data;
628
		}
629
630
		return false;
631
	}
632
633
	/**
634
	 * Returns a user object of the connection owner.
635
	 *
636
	 * @return object|false False if no connection owner found.
637
	 */
638 View Code Duplication
	public function get_connection_owner() {
639
		$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...
640
641
		$connection_owner = false;
642
		if ( $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) ) {
643
			$connection_owner = get_userdata( $user_token->external_user_id );
644
		}
645
646
		return $connection_owner;
647
	}
648
649
	/**
650
	 * Returns true if the provided user is the Jetpack connection owner.
651
	 * If user ID is not specified, the current user will be used.
652
	 *
653
	 * @param Integer|Boolean $user_id the user identifier. False for current user.
654
	 * @return Boolean True the user the connection owner, false otherwise.
655
	 */
656 View Code Duplication
	public function is_connection_owner( $user_id = false ) {
657
		if ( ! $user_id ) {
658
			$user_id = get_current_user_id();
659
		}
660
661
		$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...
662
663
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && $user_id === $user_token->external_user_id;
664
	}
665
666
	/**
667
	 * Connects the user with a specified ID to a WordPress.com user using the
668
	 * remote login flow.
669
	 *
670
	 * @access public
671
	 *
672
	 * @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...
673
	 * @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...
674
	 *                              admin_url().
675
	 * @return WP_Error only in case of a failed user lookup.
676
	 */
677
	public function connect_user( $user_id = null, $redirect_url = null ) {
678
		$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...
679
		if ( null === $user_id ) {
680
			$user = wp_get_current_user();
681
		} else {
682
			$user = get_user_by( 'ID', $user_id );
683
		}
684
685
		if ( empty( $user ) ) {
686
			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...
687
		}
688
689
		if ( null === $redirect_url ) {
690
			$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...
691
		}
692
693
		// Using wp_redirect intentionally because we're redirecting outside.
694
		wp_redirect( $this->get_authorization_url( $user ) ); // phpcs:ignore WordPress.Security.SafeRedirect
695
		exit();
696
	}
697
698
	/**
699
	 * Unlinks the current user from the linked WordPress.com user.
700
	 *
701
	 * @access public
702
	 * @static
703
	 *
704
	 * @todo Refactor to properly load the XMLRPC client independently.
705
	 *
706
	 * @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...
707
	 * @return Boolean Whether the disconnection of the user was successful.
708
	 */
709
	public static function disconnect_user( $user_id = null ) {
710
		$tokens = \Jetpack_Options::get_option( 'user_tokens' );
711
		if ( ! $tokens ) {
712
			return false;
713
		}
714
715
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
716
717
		if ( \Jetpack_Options::get_option( 'master_user' ) === $user_id ) {
718
			return false;
719
		}
720
721
		if ( ! isset( $tokens[ $user_id ] ) ) {
722
			return false;
723
		}
724
725
		$xml = new \Jetpack_IXR_Client( compact( 'user_id' ) );
726
		$xml->query( 'jetpack.unlink_user', $user_id );
727
728
		unset( $tokens[ $user_id ] );
729
730
		\Jetpack_Options::update_option( 'user_tokens', $tokens );
731
732
		/**
733
		 * Fires after the current user has been unlinked from WordPress.com.
734
		 *
735
		 * @since 4.1.0
736
		 *
737
		 * @param int $user_id The current user's ID.
738
		 */
739
		do_action( 'jetpack_unlinked_user', $user_id );
740
741
		return true;
742
	}
743
744
	/**
745
	 * Returns the requested Jetpack API URL.
746
	 *
747
	 * @param String $relative_url the relative API path.
748
	 * @return String API URL.
749
	 */
750
	public function api_url( $relative_url ) {
751
		$api_base    = Constants::get_constant( 'JETPACK__API_BASE' );
752
		$api_version = '/' . Constants::get_constant( 'JETPACK__API_VERSION' ) . '/';
753
754
		/**
755
		 * Filters whether the connection manager should use the iframe authorization
756
		 * flow instead of the regular redirect-based flow.
757
		 *
758
		 * @since 8.3.0
759
		 *
760
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
761
		 */
762
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
763
764
		// Do not modify anything that is not related to authorize requests.
765
		if ( 'authorize' === $relative_url && $iframe_flow ) {
766
			$relative_url = 'authorize_iframe';
767
		}
768
769
		/**
770
		 * Filters the API URL that Jetpack uses for server communication.
771
		 *
772
		 * @since 8.0.0
773
		 *
774
		 * @param String $url the generated URL.
775
		 * @param String $relative_url the relative URL that was passed as an argument.
776
		 * @param String $api_base the API base string that is being used.
777
		 * @param String $api_version the API version string that is being used.
778
		 */
779
		return apply_filters(
780
			'jetpack_api_url',
781
			rtrim( $api_base . $relative_url, '/\\' ) . $api_version,
782
			$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...
783
			$api_base,
784
			$api_version
785
		);
786
	}
787
788
	/**
789
	 * Returns the Jetpack XMLRPC WordPress.com API endpoint URL.
790
	 *
791
	 * @return String XMLRPC API URL.
792
	 */
793
	public function xmlrpc_api_url() {
794
		$base = preg_replace(
795
			'#(https?://[^?/]+)(/?.*)?$#',
796
			'\\1',
797
			Constants::get_constant( 'JETPACK__API_BASE' )
798
		);
799
		return untrailingslashit( $base ) . '/xmlrpc.php';
800
	}
801
802
	/**
803
	 * Attempts Jetpack registration which sets up the site for connection. Should
804
	 * remain public because the call to action comes from the current site, not from
805
	 * WordPress.com.
806
	 *
807
	 * @param String $api_endpoint (optional) an API endpoint to use, defaults to 'register'.
808
	 * @return Integer zero on success, or a bitmask on failure.
809
	 */
810
	public function register( $api_endpoint = 'register' ) {
811
		add_action( 'pre_update_jetpack_option_register', array( '\\Jetpack_Options', 'delete_option' ) );
812
		$secrets = $this->generate_secrets( 'register', get_current_user_id(), 600 );
813
814
		if (
815
			empty( $secrets['secret_1'] ) ||
816
			empty( $secrets['secret_2'] ) ||
817
			empty( $secrets['exp'] )
818
		) {
819
			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...
820
		}
821
822
		// Better to try (and fail) to set a higher timeout than this system
823
		// supports than to have register fail for more users than it should.
824
		$timeout = $this->set_min_time_limit( 60 ) / 2;
825
826
		$gmt_offset = get_option( 'gmt_offset' );
827
		if ( ! $gmt_offset ) {
828
			$gmt_offset = 0;
829
		}
830
831
		$stats_options = get_option( 'stats_options' );
832
		$stats_id      = isset( $stats_options['blog_id'] )
833
			? $stats_options['blog_id']
834
			: null;
835
836
		/**
837
		 * Filters the request body for additional property addition.
838
		 *
839
		 * @since 7.7.0
840
		 *
841
		 * @param array $post_data request data.
842
		 * @param Array $token_data token data.
843
		 */
844
		$body = apply_filters(
845
			'jetpack_register_request_body',
846
			array(
847
				'siteurl'         => site_url(),
848
				'home'            => home_url(),
849
				'gmt_offset'      => $gmt_offset,
850
				'timezone_string' => (string) get_option( 'timezone_string' ),
851
				'site_name'       => (string) get_option( 'blogname' ),
852
				'secret_1'        => $secrets['secret_1'],
853
				'secret_2'        => $secrets['secret_2'],
854
				'site_lang'       => get_locale(),
855
				'timeout'         => $timeout,
856
				'stats_id'        => $stats_id,
857
				'state'           => get_current_user_id(),
858
				'site_created'    => $this->get_assumed_site_creation_date(),
859
				'jetpack_version' => Constants::get_constant( 'JETPACK__VERSION' ),
860
				'ABSPATH'         => Constants::get_constant( 'ABSPATH' ),
861
			)
862
		);
863
864
		$args = array(
865
			'method'  => 'POST',
866
			'body'    => $body,
867
			'headers' => array(
868
				'Accept' => 'application/json',
869
			),
870
			'timeout' => $timeout,
871
		);
872
873
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
874
875
		// TODO: fix URLs for bad hosts.
876
		$response = Client::_wp_remote_request(
877
			$this->api_url( $api_endpoint ),
878
			$args,
879
			true
880
		);
881
882
		// Make sure the response is valid and does not contain any Jetpack errors.
883
		$registration_details = $this->validate_remote_register_response( $response );
884
885
		if ( is_wp_error( $registration_details ) ) {
886
			return $registration_details;
887
		} elseif ( ! $registration_details ) {
888
			return new \WP_Error(
889
				'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...
890
				'Unknown error registering your Jetpack site.',
891
				wp_remote_retrieve_response_code( $response )
892
			);
893
		}
894
895
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
896
			return new \WP_Error(
897
				'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...
898
				'Unable to validate registration of your Jetpack site.',
899
				wp_remote_retrieve_response_code( $response )
900
			);
901
		}
902
903
		if ( isset( $registration_details->jetpack_public ) ) {
904
			$jetpack_public = (int) $registration_details->jetpack_public;
905
		} else {
906
			$jetpack_public = false;
907
		}
908
909
		\Jetpack_Options::update_options(
910
			array(
911
				'id'         => (int) $registration_details->jetpack_id,
912
				'blog_token' => (string) $registration_details->jetpack_secret,
913
				'public'     => $jetpack_public,
914
			)
915
		);
916
917
		/**
918
		 * Fires when a site is registered on WordPress.com.
919
		 *
920
		 * @since 3.7.0
921
		 *
922
		 * @param int $json->jetpack_id Jetpack Blog ID.
923
		 * @param string $json->jetpack_secret Jetpack Blog Token.
924
		 * @param int|bool $jetpack_public Is the site public.
925
		 */
926
		do_action(
927
			'jetpack_site_registered',
928
			$registration_details->jetpack_id,
929
			$registration_details->jetpack_secret,
930
			$jetpack_public
931
		);
932
933
		if ( isset( $registration_details->token ) ) {
934
			/**
935
			 * Fires when a user token is sent along with the registration data.
936
			 *
937
			 * @since 7.6.0
938
			 *
939
			 * @param object $token the administrator token for the newly registered site.
940
			 */
941
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
942
		}
943
944
		return true;
945
	}
946
947
	/**
948
	 * Takes the response from the Jetpack register new site endpoint and
949
	 * verifies it worked properly.
950
	 *
951
	 * @since 2.6
952
	 *
953
	 * @param Mixed $response the response object, or the error object.
954
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
955
	 **/
956
	protected function validate_remote_register_response( $response ) {
957
		if ( is_wp_error( $response ) ) {
958
			return new \WP_Error(
959
				'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...
960
				$response->get_error_message()
961
			);
962
		}
963
964
		$code   = wp_remote_retrieve_response_code( $response );
965
		$entity = wp_remote_retrieve_body( $response );
966
967
		if ( $entity ) {
968
			$registration_response = json_decode( $entity );
969
		} else {
970
			$registration_response = false;
971
		}
972
973
		$code_type = intval( $code / 100 );
974
		if ( 5 === $code_type ) {
975
			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...
976
		} elseif ( 408 === $code ) {
977
			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...
978
		} elseif ( ! empty( $registration_response->error ) ) {
979
			if (
980
				'xml_rpc-32700' === $registration_response->error
981
				&& ! function_exists( 'xml_parser_create' )
982
			) {
983
				$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' );
984
			} else {
985
				$error_description = isset( $registration_response->error_description )
986
					? (string) $registration_response->error_description
987
					: '';
988
			}
989
990
			return new \WP_Error(
991
				(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...
992
				$error_description,
993
				$code
994
			);
995
		} elseif ( 200 !== $code ) {
996
			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...
997
		}
998
999
		// Jetpack ID error block.
1000
		if ( empty( $registration_response->jetpack_id ) ) {
1001
			return new \WP_Error(
1002
				'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...
1003
				/* translators: %s is an error message string */
1004
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1005
				$entity
1006
			);
1007
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1008
			return new \WP_Error(
1009
				'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...
1010
				/* translators: %s is an error message string */
1011
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1012
				$entity
1013
			);
1014 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1015
			return new \WP_Error(
1016
				'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...
1017
				/* translators: %s is an error message string */
1018
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1019
				$entity
1020
			);
1021
		}
1022
1023
		return $registration_response;
1024
	}
1025
1026
	/**
1027
	 * Adds a used nonce to a list of known nonces.
1028
	 *
1029
	 * @param int    $timestamp the current request timestamp.
1030
	 * @param string $nonce the nonce value.
1031
	 * @return bool whether the nonce is unique or not.
1032
	 */
1033
	public function add_nonce( $timestamp, $nonce ) {
1034
		global $wpdb;
1035
		static $nonces_used_this_request = array();
1036
1037
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
1038
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
1039
		}
1040
1041
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
1042
		$timestamp = (int) $timestamp;
1043
		$nonce     = esc_sql( $nonce );
1044
1045
		// Raw query so we can avoid races: add_option will also update.
1046
		$show_errors = $wpdb->show_errors( false );
1047
1048
		$old_nonce = $wpdb->get_row(
1049
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1050
		);
1051
1052
		if ( is_null( $old_nonce ) ) {
1053
			$return = $wpdb->query(
1054
				$wpdb->prepare(
1055
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1056
					"jetpack_nonce_{$timestamp}_{$nonce}",
1057
					time(),
1058
					'no'
1059
				)
1060
			);
1061
		} else {
1062
			$return = false;
1063
		}
1064
1065
		$wpdb->show_errors( $show_errors );
1066
1067
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1068
1069
		return $return;
1070
	}
1071
1072
	/**
1073
	 * Cleans nonces that were saved when calling ::add_nonce.
1074
	 *
1075
	 * @todo Properly prepare the query before executing it.
1076
	 *
1077
	 * @param bool $all whether to clean even non-expired nonces.
1078
	 */
1079
	public function clean_nonces( $all = false ) {
1080
		global $wpdb;
1081
1082
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1083
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1084
1085
		if ( true !== $all ) {
1086
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1087
			$sql_args[] = time() - 3600;
1088
		}
1089
1090
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1091
1092
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1093
1094
		for ( $i = 0; $i < 1000; $i++ ) {
1095
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1096
				break;
1097
			}
1098
		}
1099
	}
1100
1101
	/**
1102
	 * Builds the timeout limit for queries talking with the wpcom servers.
1103
	 *
1104
	 * Based on local php max_execution_time in php.ini
1105
	 *
1106
	 * @since 5.4
1107
	 * @return int
1108
	 **/
1109
	public function get_max_execution_time() {
1110
		$timeout = (int) ini_get( 'max_execution_time' );
1111
1112
		// Ensure exec time set in php.ini.
1113
		if ( ! $timeout ) {
1114
			$timeout = 30;
1115
		}
1116
		return $timeout;
1117
	}
1118
1119
	/**
1120
	 * Sets a minimum request timeout, and returns the current timeout
1121
	 *
1122
	 * @since 5.4
1123
	 * @param Integer $min_timeout the minimum timeout value.
1124
	 **/
1125 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1126
		$timeout = $this->get_max_execution_time();
1127
		if ( $timeout < $min_timeout ) {
1128
			$timeout = $min_timeout;
1129
			set_time_limit( $timeout );
1130
		}
1131
		return $timeout;
1132
	}
1133
1134
	/**
1135
	 * Get our assumed site creation date.
1136
	 * Calculated based on the earlier date of either:
1137
	 * - Earliest admin user registration date.
1138
	 * - Earliest date of post of any post type.
1139
	 *
1140
	 * @since 7.2.0
1141
	 *
1142
	 * @return string Assumed site creation date and time.
1143
	 */
1144
	public function get_assumed_site_creation_date() {
1145
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1146
		if ( ! empty( $cached_date ) ) {
1147
			return $cached_date;
1148
		}
1149
1150
		$earliest_registered_users  = get_users(
1151
			array(
1152
				'role'    => 'administrator',
1153
				'orderby' => 'user_registered',
1154
				'order'   => 'ASC',
1155
				'fields'  => array( 'user_registered' ),
1156
				'number'  => 1,
1157
			)
1158
		);
1159
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1160
1161
		$earliest_posts = get_posts(
1162
			array(
1163
				'posts_per_page' => 1,
1164
				'post_type'      => 'any',
1165
				'post_status'    => 'any',
1166
				'orderby'        => 'date',
1167
				'order'          => 'ASC',
1168
			)
1169
		);
1170
1171
		// If there are no posts at all, we'll count only on user registration date.
1172
		if ( $earliest_posts ) {
1173
			$earliest_post_date = $earliest_posts[0]->post_date;
1174
		} else {
1175
			$earliest_post_date = PHP_INT_MAX;
1176
		}
1177
1178
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1179
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1180
1181
		return $assumed_date;
1182
	}
1183
1184
	/**
1185
	 * Adds the activation source string as a parameter to passed arguments.
1186
	 *
1187
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1188
	 *
1189
	 * @param array $args arguments that need to have the source added.
1190
	 * @return array $amended arguments.
1191
	 */
1192 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1193
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1194
1195
		if ( $activation_source_name ) {
1196
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1197
			$args['_as'] = urlencode( $activation_source_name );
1198
		}
1199
1200
		if ( $activation_source_keyword ) {
1201
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1202
			$args['_ak'] = urlencode( $activation_source_keyword );
1203
		}
1204
1205
		return $args;
1206
	}
1207
1208
	/**
1209
	 * Returns the callable that would be used to generate secrets.
1210
	 *
1211
	 * @return Callable a function that returns a secure string to be used as a secret.
1212
	 */
1213
	protected function get_secret_callable() {
1214
		if ( ! isset( $this->secret_callable ) ) {
1215
			/**
1216
			 * Allows modification of the callable that is used to generate connection secrets.
1217
			 *
1218
			 * @param Callable a function or method that returns a secret string.
1219
			 */
1220
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', array( $this, 'secret_callable_method' ) );
1221
		}
1222
1223
		return $this->secret_callable;
1224
	}
1225
1226
	/**
1227
	 * Runs the wp_generate_password function with the required parameters. This is the
1228
	 * default implementation of the secret callable, can be overridden using the
1229
	 * jetpack_connection_secret_generator filter.
1230
	 *
1231
	 * @return String $secret value.
1232
	 */
1233
	private function secret_callable_method() {
1234
		return wp_generate_password( 32, false );
1235
	}
1236
1237
	/**
1238
	 * Generates two secret tokens and the end of life timestamp for them.
1239
	 *
1240
	 * @param String  $action  The action name.
1241
	 * @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...
1242
	 * @param Integer $exp     Expiration time in seconds.
1243
	 */
1244
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1245
		if ( false === $user_id ) {
1246
			$user_id = get_current_user_id();
1247
		}
1248
1249
		$callable = $this->get_secret_callable();
1250
1251
		$secrets = \Jetpack_Options::get_raw_option(
1252
			self::SECRETS_OPTION_NAME,
1253
			array()
1254
		);
1255
1256
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1257
1258
		if (
1259
			isset( $secrets[ $secret_name ] ) &&
1260
			$secrets[ $secret_name ]['exp'] > time()
1261
		) {
1262
			return $secrets[ $secret_name ];
1263
		}
1264
1265
		$secret_value = array(
1266
			'secret_1' => call_user_func( $callable ),
1267
			'secret_2' => call_user_func( $callable ),
1268
			'exp'      => time() + $exp,
1269
		);
1270
1271
		$secrets[ $secret_name ] = $secret_value;
1272
1273
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1274
		return $secrets[ $secret_name ];
1275
	}
1276
1277
	/**
1278
	 * Returns two secret tokens and the end of life timestamp for them.
1279
	 *
1280
	 * @param String  $action  The action name.
1281
	 * @param Integer $user_id The user identifier.
1282
	 * @return string|array an array of secrets or an error string.
1283
	 */
1284
	public function get_secrets( $action, $user_id ) {
1285
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1286
		$secrets     = \Jetpack_Options::get_raw_option(
1287
			self::SECRETS_OPTION_NAME,
1288
			array()
1289
		);
1290
1291
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1292
			return self::SECRETS_MISSING;
1293
		}
1294
1295
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1296
			$this->delete_secrets( $action, $user_id );
1297
			return self::SECRETS_EXPIRED;
1298
		}
1299
1300
		return $secrets[ $secret_name ];
1301
	}
1302
1303
	/**
1304
	 * Deletes secret tokens in case they, for example, have expired.
1305
	 *
1306
	 * @param String  $action  The action name.
1307
	 * @param Integer $user_id The user identifier.
1308
	 */
1309
	public function delete_secrets( $action, $user_id ) {
1310
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1311
		$secrets     = \Jetpack_Options::get_raw_option(
1312
			self::SECRETS_OPTION_NAME,
1313
			array()
1314
		);
1315
		if ( isset( $secrets[ $secret_name ] ) ) {
1316
			unset( $secrets[ $secret_name ] );
1317
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1318
		}
1319
	}
1320
1321
	/**
1322
	 * Deletes all connection tokens and transients from the local Jetpack site.
1323
	 */
1324
	public function delete_all_connection_tokens() {
1325
		\Jetpack_Options::delete_option(
1326
			array(
1327
				'blog_token',
1328
				'user_token',
1329
				'user_tokens',
1330
				'master_user',
1331
				'time_diff',
1332
				'fallback_no_verify_ssl_certs',
1333
			)
1334
		);
1335
1336
		\Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
1337
1338
		// Delete cached connected user data.
1339
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1340
		delete_transient( $transient_key );
1341
	}
1342
1343
	/**
1344
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1345
	 */
1346
	public function disconnect_site_wpcom() {
1347
		$xml = new \Jetpack_IXR_Client();
1348
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1349
	}
1350
1351
	/**
1352
	 * Responds to a WordPress.com call to register the current site.
1353
	 * Should be changed to protected.
1354
	 *
1355
	 * @param array $registration_data Array of [ secret_1, user_id ].
1356
	 */
1357
	public function handle_registration( array $registration_data ) {
1358
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1359
		if ( empty( $registration_user_id ) ) {
1360
			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...
1361
		}
1362
1363
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1364
	}
1365
1366
	/**
1367
	 * Verify a Previously Generated Secret.
1368
	 *
1369
	 * @param string $action   The type of secret to verify.
1370
	 * @param string $secret_1 The secret string to compare to what is stored.
1371
	 * @param int    $user_id  The user ID of the owner of the secret.
1372
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1373
	 */
1374
	public function verify_secrets( $action, $secret_1, $user_id ) {
1375
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1376
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1377
			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...
1378
		}
1379
1380
		$user = get_user_by( 'id', $user_id );
1381
1382
		/**
1383
		 * We've begun verifying the previously generated secret.
1384
		 *
1385
		 * @since 7.5.0
1386
		 *
1387
		 * @param string   $action The type of secret to verify.
1388
		 * @param \WP_User $user The user object.
1389
		 */
1390
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1391
1392
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1393
			/**
1394
			 * Verifying of the previously generated secret has failed.
1395
			 *
1396
			 * @since 7.5.0
1397
			 *
1398
			 * @param string    $action  The type of secret to verify.
1399
			 * @param \WP_User  $user The user object.
1400
			 * @param \WP_Error $error The error object.
1401
			 */
1402
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1403
1404
			return $error;
1405
		};
1406
1407
		$stored_secrets = $this->get_secrets( $action, $user_id );
1408
		$this->delete_secrets( $action, $user_id );
1409
1410
		$error = null;
1411
		if ( empty( $secret_1 ) ) {
1412
			$error = $return_error(
1413
				new \WP_Error(
1414
					'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...
1415
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1416
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1417
					400
1418
				)
1419
			);
1420
		} elseif ( ! is_string( $secret_1 ) ) {
1421
			$error = $return_error(
1422
				new \WP_Error(
1423
					'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...
1424
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1425
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1426
					400
1427
				)
1428
			);
1429
		} elseif ( empty( $user_id ) ) {
1430
			// $user_id is passed around during registration as "state".
1431
			$error = $return_error(
1432
				new \WP_Error(
1433
					'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...
1434
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1435
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1436
					400
1437
				)
1438
			);
1439
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1440
			$error = $return_error(
1441
				new \WP_Error(
1442
					'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...
1443
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1444
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1445
					400
1446
				)
1447
			);
1448
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1449
			$error = $return_error(
1450
				new \WP_Error(
1451
					'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...
1452
					__( 'Verification secrets not found', 'jetpack' ),
1453
					400
1454
				)
1455
			);
1456
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1457
			$error = $return_error(
1458
				new \WP_Error(
1459
					'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...
1460
					__( 'Verification took too long', 'jetpack' ),
1461
					400
1462
				)
1463
			);
1464
		} elseif ( ! $stored_secrets ) {
1465
			$error = $return_error(
1466
				new \WP_Error(
1467
					'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...
1468
					__( 'Verification secrets are empty', 'jetpack' ),
1469
					400
1470
				)
1471
			);
1472
		} elseif ( is_wp_error( $stored_secrets ) ) {
1473
			$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...
1474
			$error = $return_error( $stored_secrets );
1475
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1476
			$error = $return_error(
1477
				new \WP_Error(
1478
					'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...
1479
					__( 'Verification secrets are incomplete', 'jetpack' ),
1480
					400
1481
				)
1482
			);
1483
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1484
			$error = $return_error(
1485
				new \WP_Error(
1486
					'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...
1487
					__( 'Secret mismatch', 'jetpack' ),
1488
					400
1489
				)
1490
			);
1491
		}
1492
1493
		// Something went wrong during the checks, returning the error.
1494
		if ( ! empty( $error ) ) {
1495
			return $error;
1496
		}
1497
1498
		/**
1499
		 * We've succeeded at verifying the previously generated secret.
1500
		 *
1501
		 * @since 7.5.0
1502
		 *
1503
		 * @param string   $action The type of secret to verify.
1504
		 * @param \WP_User $user The user object.
1505
		 */
1506
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1507
1508
		return $stored_secrets['secret_2'];
1509
	}
1510
1511
	/**
1512
	 * Responds to a WordPress.com call to authorize the current user.
1513
	 * Should be changed to protected.
1514
	 */
1515
	public function handle_authorization() {
1516
1517
	}
1518
1519
	/**
1520
	 * Obtains the auth token.
1521
	 *
1522
	 * @param array $data The request data.
1523
	 * @return object|\WP_Error Returns the auth token on success.
1524
	 *                          Returns a \WP_Error on failure.
1525
	 */
1526
	public function get_token( $data ) {
1527
		$roles = new Roles();
1528
		$role  = $roles->translate_current_user_to_role();
1529
1530
		if ( ! $role ) {
1531
			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...
1532
		}
1533
1534
		$client_secret = $this->get_access_token();
1535
		if ( ! $client_secret ) {
1536
			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...
1537
		}
1538
1539
		/**
1540
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1541
		 * data processing.
1542
		 *
1543
		 * @since 8.0.0
1544
		 *
1545
		 * @param string $redirect_url Defaults to the site admin URL.
1546
		 */
1547
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1548
1549
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1550
1551
		/**
1552
		* Filter the URL to redirect the user back to when the authentication process
1553
		* is complete.
1554
		*
1555
		* @since 8.0.0
1556
		*
1557
		* @param string $redirect_url Defaults to the site URL.
1558
		*/
1559
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1560
1561
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1562
			? $data['redirect_uri']
1563
			: add_query_arg(
1564
				array(
1565
					'action'   => 'authorize',
1566
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1567
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1568
				),
1569
				esc_url( $processing_url )
1570
			);
1571
1572
		/**
1573
		 * Filters the token request data.
1574
		 *
1575
		 * @since 8.0.0
1576
		 *
1577
		 * @param array $request_data request data.
1578
		 */
1579
		$body = apply_filters(
1580
			'jetpack_token_request_body',
1581
			array(
1582
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1583
				'client_secret' => $client_secret->secret,
1584
				'grant_type'    => 'authorization_code',
1585
				'code'          => $data['code'],
1586
				'redirect_uri'  => $redirect_uri,
1587
			)
1588
		);
1589
1590
		$args = array(
1591
			'method'  => 'POST',
1592
			'body'    => $body,
1593
			'headers' => array(
1594
				'Accept' => 'application/json',
1595
			),
1596
		);
1597
1598
		add_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1599
		$response = Client::_wp_remote_request( Utils::fix_url_for_bad_hosts( $this->api_url( 'token' ) ), $args );
1600
		remove_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1601
1602
		if ( is_wp_error( $response ) ) {
1603
			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...
1604
		}
1605
1606
		$code   = wp_remote_retrieve_response_code( $response );
1607
		$entity = wp_remote_retrieve_body( $response );
1608
1609
		if ( $entity ) {
1610
			$json = json_decode( $entity );
1611
		} else {
1612
			$json = false;
1613
		}
1614
1615
		if ( 200 !== $code || ! empty( $json->error ) ) {
1616
			if ( empty( $json->error ) ) {
1617
				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...
1618
			}
1619
1620
			/* translators: Error description string. */
1621
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1622
1623
			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...
1624
		}
1625
1626
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1627
			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...
1628
		}
1629
1630
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1631
			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...
1632
		}
1633
1634
		if ( empty( $json->scope ) ) {
1635
			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...
1636
		}
1637
1638
		// TODO: get rid of the error silencer.
1639
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1640
		@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...
1641
		if ( empty( $role ) || empty( $hmac ) ) {
1642
			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...
1643
		}
1644
1645
		if ( $this->sign_role( $role ) !== $json->scope ) {
1646
			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...
1647
		}
1648
1649
		$cap = $roles->translate_role_to_cap( $role );
1650
		if ( ! $cap ) {
1651
			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...
1652
		}
1653
1654
		if ( ! current_user_can( $cap ) ) {
1655
			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...
1656
		}
1657
1658
		/**
1659
		 * Fires after user has successfully received an auth token.
1660
		 *
1661
		 * @since 3.9.0
1662
		 */
1663
		do_action( 'jetpack_user_authorized' );
1664
1665
		return (string) $json->access_token;
1666
	}
1667
1668
	/**
1669
	 * Increases the request timeout value to 30 seconds.
1670
	 *
1671
	 * @return int Returns 30.
1672
	 */
1673
	public function increase_timeout() {
1674
		return 30;
1675
	}
1676
1677
	/**
1678
	 * Builds a URL to the Jetpack connection auth page.
1679
	 *
1680
	 * @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...
1681
	 * @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...
1682
	 * @return string Connect URL.
1683
	 */
1684
	public function get_authorization_url( $user = null, $redirect = null ) {
1685
1686
		if ( empty( $user ) ) {
1687
			$user = wp_get_current_user();
1688
		}
1689
1690
		$roles       = new Roles();
1691
		$role        = $roles->translate_user_to_role( $user );
1692
		$signed_role = $this->sign_role( $role );
1693
1694
		/**
1695
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1696
		 * data processing.
1697
		 *
1698
		 * @since 8.0.0
1699
		 *
1700
		 * @param string $redirect_url Defaults to the site admin URL.
1701
		 */
1702
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1703
1704
		/**
1705
		 * Filter the URL to redirect the user back to when the authorization process
1706
		 * is complete.
1707
		 *
1708
		 * @since 8.0.0
1709
		 *
1710
		 * @param string $redirect_url Defaults to the site URL.
1711
		 */
1712
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1713
1714
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1715
1716
		/**
1717
		 * Filter the type of authorization.
1718
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1719
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1720
		 *
1721
		 * @since 4.3.3
1722
		 *
1723
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1724
		 */
1725
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1726
1727
		/**
1728
		 * Filters the user connection request data for additional property addition.
1729
		 *
1730
		 * @since 8.0.0
1731
		 *
1732
		 * @param array $request_data request data.
1733
		 */
1734
		$body = apply_filters(
1735
			'jetpack_connect_request_body',
1736
			array(
1737
				'response_type' => 'code',
1738
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1739
				'redirect_uri'  => add_query_arg(
1740
					array(
1741
						'action'   => 'authorize',
1742
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1743
						'redirect' => rawurlencode( $redirect ),
1744
					),
1745
					esc_url( $processing_url )
1746
				),
1747
				'state'         => $user->ID,
1748
				'scope'         => $signed_role,
1749
				'user_email'    => $user->user_email,
1750
				'user_login'    => $user->user_login,
1751
				'is_active'     => $this->is_active(),
1752
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1753
				'auth_type'     => $auth_type,
1754
				'secret'        => $secrets['secret_1'],
1755
				'blogname'      => get_option( 'blogname' ),
1756
				'site_url'      => site_url(),
1757
				'home_url'      => home_url(),
1758
				'site_icon'     => get_site_icon_url(),
1759
				'site_lang'     => get_locale(),
1760
				'site_created'  => $this->get_assumed_site_creation_date(),
1761
			)
1762
		);
1763
1764
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1765
1766
		$api_url = $this->api_url( 'authorize' );
1767
1768
		return add_query_arg( $body, $api_url );
1769
	}
1770
1771
	/**
1772
	 * Authorizes the user by obtaining and storing the user token.
1773
	 *
1774
	 * @param array $data The request data.
1775
	 * @return string|\WP_Error Returns a string on success.
1776
	 *                          Returns a \WP_Error on failure.
1777
	 */
1778
	public function authorize( $data = array() ) {
1779
		/**
1780
		 * Action fired when user authorization starts.
1781
		 *
1782
		 * @since 8.0.0
1783
		 */
1784
		do_action( 'jetpack_authorize_starting' );
1785
1786
		$roles = new Roles();
1787
		$role  = $roles->translate_current_user_to_role();
1788
1789
		if ( ! $role ) {
1790
			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...
1791
		}
1792
1793
		$cap = $roles->translate_role_to_cap( $role );
1794
		if ( ! $cap ) {
1795
			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...
1796
		}
1797
1798
		if ( ! empty( $data['error'] ) ) {
1799
			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...
1800
		}
1801
1802
		if ( ! isset( $data['state'] ) ) {
1803
			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...
1804
		}
1805
1806
		if ( ! ctype_digit( $data['state'] ) ) {
1807
			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...
1808
		}
1809
1810
		$current_user_id = get_current_user_id();
1811
		if ( $current_user_id !== (int) $data['state'] ) {
1812
			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...
1813
		}
1814
1815
		if ( empty( $data['code'] ) ) {
1816
			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...
1817
		}
1818
1819
		$token = $this->get_token( $data );
1820
1821 View Code Duplication
		if ( is_wp_error( $token ) ) {
1822
			$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...
1823
			if ( empty( $code ) ) {
1824
				$code = 'invalid_token';
1825
			}
1826
			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...
1827
		}
1828
1829
		if ( ! $token ) {
1830
			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...
1831
		}
1832
1833
		$is_master_user = ! $this->is_active();
1834
1835
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
1836
1837
		if ( ! $is_master_user ) {
1838
			/**
1839
			 * Action fired when a secondary user has been authorized.
1840
			 *
1841
			 * @since 8.0.0
1842
			 */
1843
			do_action( 'jetpack_authorize_ending_linked' );
1844
			return 'linked';
1845
		}
1846
1847
		/**
1848
		 * Action fired when the master user has been authorized.
1849
		 *
1850
		 * @since 8.0.0
1851
		 *
1852
		 * @param array $data The request data.
1853
		 */
1854
		do_action( 'jetpack_authorize_ending_authorized', $data );
1855
1856
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
1857
1858
		// Start nonce cleaner.
1859
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
1860
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
1861
1862
		return 'authorized';
1863
	}
1864
1865
	/**
1866
	 * Disconnects from the Jetpack servers.
1867
	 * Forgets all connection details and tells the Jetpack servers to do the same.
1868
	 */
1869
	public function disconnect_site() {
1870
1871
	}
1872
1873
	/**
1874
	 * The Base64 Encoding of the SHA1 Hash of the Input.
1875
	 *
1876
	 * @param string $text The string to hash.
1877
	 * @return string
1878
	 */
1879
	public function sha1_base64( $text ) {
1880
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1881
	}
1882
1883
	/**
1884
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
1885
	 *
1886
	 * @param string $domain The domain to check.
1887
	 *
1888
	 * @return bool|WP_Error
1889
	 */
1890
	public function is_usable_domain( $domain ) {
1891
1892
		// If it's empty, just fail out.
1893
		if ( ! $domain ) {
1894
			return new \WP_Error(
1895
				'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...
1896
				/* translators: %1$s is a domain name. */
1897
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
1898
			);
1899
		}
1900
1901
		/**
1902
		 * Skips the usuable domain check when connecting a site.
1903
		 *
1904
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
1905
		 *
1906
		 * @since 4.1.0
1907
		 *
1908
		 * @param bool If the check should be skipped. Default false.
1909
		 */
1910
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
1911
			return true;
1912
		}
1913
1914
		// None of the explicit localhosts.
1915
		$forbidden_domains = array(
1916
			'wordpress.com',
1917
			'localhost',
1918
			'localhost.localdomain',
1919
			'127.0.0.1',
1920
			'local.wordpress.test',         // VVV pattern.
1921
			'local.wordpress-trunk.test',   // VVV pattern.
1922
			'src.wordpress-develop.test',   // VVV pattern.
1923
			'build.wordpress-develop.test', // VVV pattern.
1924
		);
1925 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
1926
			return new \WP_Error(
1927
				'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...
1928
				sprintf(
1929
					/* translators: %1$s is a domain name. */
1930
					__(
1931
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
1932
						'jetpack'
1933
					),
1934
					$domain
1935
				)
1936
			);
1937
		}
1938
1939
		// No .test or .local domains.
1940 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
1941
			return new \WP_Error(
1942
				'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...
1943
				sprintf(
1944
					/* translators: %1$s is a domain name. */
1945
					__(
1946
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
1947
						'jetpack'
1948
					),
1949
					$domain
1950
				)
1951
			);
1952
		}
1953
1954
		// No WPCOM subdomains.
1955 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
1956
			return new \WP_Error(
1957
				'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...
1958
				sprintf(
1959
					/* translators: %1$s is a domain name. */
1960
					__(
1961
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
1962
						'jetpack'
1963
					),
1964
					$domain
1965
				)
1966
			);
1967
		}
1968
1969
		// If PHP was compiled without support for the Filter module (very edge case).
1970
		if ( ! function_exists( 'filter_var' ) ) {
1971
			// Just pass back true for now, and let wpcom sort it out.
1972
			return true;
1973
		}
1974
1975
		return true;
1976
	}
1977
1978
	/**
1979
	 * Gets the requested token.
1980
	 *
1981
	 * Tokens are one of two types:
1982
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
1983
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
1984
	 *    are not associated with a user account. They represent the site's connection with
1985
	 *    the Jetpack servers.
1986
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
1987
	 *
1988
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
1989
	 * token, and $private is a secret that should never be displayed anywhere or sent
1990
	 * over the network; it's used only for signing things.
1991
	 *
1992
	 * Blog Tokens can be "Normal" or "Special".
1993
	 * * Normal: The result of a normal connection flow. They look like
1994
	 *   "{$random_string_1}.{$random_string_2}"
1995
	 *   That is, $token_key and $private are both random strings.
1996
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
1997
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
1998
	 *   constant (rare).
1999
	 * * Special: A connection token for sites that have gone through an alternative
2000
	 *   connection flow. They look like:
2001
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
2002
	 *   That is, $private is a random string and $token_key has a special structure with
2003
	 *   lots of semicolons.
2004
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
2005
	 *   JETPACK_BLOG_TOKEN constant.
2006
	 *
2007
	 * In particular, note that Normal Blog Tokens never start with ";" and that
2008
	 * Special Blog Tokens always do.
2009
	 *
2010
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
2011
	 * order:
2012
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
2013
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
2014
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
2015
	 *
2016
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
2017
	 * @param string|false $token_key If provided, check that the token matches the provided input.
2018
	 * @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.
2019
	 *
2020
	 * @return object|false
2021
	 */
2022
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
2023
		$possible_special_tokens = array();
2024
		$possible_normal_tokens  = array();
2025
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
2026
2027
		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...
2028
			if ( ! $user_tokens ) {
2029
				return $suppress_errors ? false : new \WP_Error( 'no_user_tokens' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_user_tokens'.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
2046
			}
2047
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
2048
		} else {
2049
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
2050
			if ( $stored_blog_token ) {
2051
				$possible_normal_tokens[] = $stored_blog_token;
2052
			}
2053
2054
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
2055
2056
			if ( $defined_tokens_string ) {
2057
				$defined_tokens = explode( ',', $defined_tokens_string );
2058
				foreach ( $defined_tokens as $defined_token ) {
2059
					if ( ';' === $defined_token[0] ) {
2060
						$possible_special_tokens[] = $defined_token;
2061
					} else {
2062
						$possible_normal_tokens[] = $defined_token;
2063
					}
2064
				}
2065
			}
2066
		}
2067
2068
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2069
			$possible_tokens = $possible_normal_tokens;
2070
		} else {
2071
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
2072
		}
2073
2074
		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...
2075
			return $suppress_errors ? false : new \WP_Error( 'no_possible_tokens' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_possible_tokens'.

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

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

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

Loading history...
2076
		}
2077
2078
		$valid_token = false;
2079
2080
		if ( false === $token_key ) {
2081
			// Use first token.
2082
			$valid_token = $possible_tokens[0];
2083
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2084
			// Use first normal token.
2085
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
2086
		} else {
2087
			// Use the token matching $token_key or false if none.
2088
			// Ensure we check the full key.
2089
			$token_check = rtrim( $token_key, '.' ) . '.';
2090
2091
			foreach ( $possible_tokens as $possible_token ) {
2092
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
2093
					$valid_token = $possible_token;
2094
					break;
2095
				}
2096
			}
2097
		}
2098
2099
		if ( ! $valid_token ) {
2100
			return $suppress_errors ? false : new \WP_Error( 'no_valid_token' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_valid_token'.

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

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

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

Loading history...
2101
		}
2102
2103
		return (object) array(
2104
			'secret'           => $valid_token,
2105
			'external_user_id' => (int) $user_id,
2106
		);
2107
	}
2108
2109
	/**
2110
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2111
	 * since it is passed by reference to various methods.
2112
	 * Capture it here so we can verify the signature later.
2113
	 *
2114
	 * @param array $methods an array of available XMLRPC methods.
2115
	 * @return array the same array, since this method doesn't add or remove anything.
2116
	 */
2117
	public function xmlrpc_methods( $methods ) {
2118
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
2119
		return $methods;
2120
	}
2121
2122
	/**
2123
	 * Resets the raw post data parameter for testing purposes.
2124
	 */
2125
	public function reset_raw_post_data() {
2126
		$this->raw_post_data = null;
2127
	}
2128
2129
	/**
2130
	 * Registering an additional method.
2131
	 *
2132
	 * @param array $methods an array of available XMLRPC methods.
2133
	 * @return array the amended array in case the method is added.
2134
	 */
2135
	public function public_xmlrpc_methods( $methods ) {
2136
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2137
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2138
		}
2139
		return $methods;
2140
	}
2141
2142
	/**
2143
	 * Handles a getOptions XMLRPC method call.
2144
	 *
2145
	 * @param array $args method call arguments.
2146
	 * @return an amended XMLRPC server options array.
2147
	 */
2148
	public function jetpack_get_options( $args ) {
2149
		global $wp_xmlrpc_server;
2150
2151
		$wp_xmlrpc_server->escape( $args );
2152
2153
		$username = $args[1];
2154
		$password = $args[2];
2155
2156
		$user = $wp_xmlrpc_server->login( $username, $password );
2157
		if ( ! $user ) {
2158
			return $wp_xmlrpc_server->error;
2159
		}
2160
2161
		$options   = array();
2162
		$user_data = $this->get_connected_user_data();
2163
		if ( is_array( $user_data ) ) {
2164
			$options['jetpack_user_id']         = array(
2165
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2166
				'readonly' => true,
2167
				'value'    => $user_data['ID'],
2168
			);
2169
			$options['jetpack_user_login']      = array(
2170
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2171
				'readonly' => true,
2172
				'value'    => $user_data['login'],
2173
			);
2174
			$options['jetpack_user_email']      = array(
2175
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2176
				'readonly' => true,
2177
				'value'    => $user_data['email'],
2178
			);
2179
			$options['jetpack_user_site_count'] = array(
2180
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2181
				'readonly' => true,
2182
				'value'    => $user_data['site_count'],
2183
			);
2184
		}
2185
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2186
		$args                           = stripslashes_deep( $args );
2187
		return $wp_xmlrpc_server->wp_getOptions( $args );
2188
	}
2189
2190
	/**
2191
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2192
	 *
2193
	 * @param array $options standard Core options.
2194
	 * @return array amended options.
2195
	 */
2196
	public function xmlrpc_options( $options ) {
2197
		$jetpack_client_id = false;
2198
		if ( $this->is_active() ) {
2199
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2200
		}
2201
		$options['jetpack_version'] = array(
2202
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2203
			'readonly' => true,
2204
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2205
		);
2206
2207
		$options['jetpack_client_id'] = array(
2208
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2209
			'readonly' => true,
2210
			'value'    => $jetpack_client_id,
2211
		);
2212
		return $options;
2213
	}
2214
2215
	/**
2216
	 * Resets the saved authentication state in between testing requests.
2217
	 */
2218
	public function reset_saved_auth_state() {
2219
		$this->xmlrpc_verification = null;
2220
	}
2221
2222
	/**
2223
	 * Sign a user role with the master access token.
2224
	 * If not specified, will default to the current user.
2225
	 *
2226
	 * @access public
2227
	 *
2228
	 * @param string $role    User role.
2229
	 * @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...
2230
	 * @return string Signed user role.
2231
	 */
2232
	public function sign_role( $role, $user_id = null ) {
2233
		if ( empty( $user_id ) ) {
2234
			$user_id = (int) get_current_user_id();
2235
		}
2236
2237
		if ( ! $user_id ) {
2238
			return false;
2239
		}
2240
2241
		$token = $this->get_access_token();
2242
		if ( ! $token || is_wp_error( $token ) ) {
2243
			return false;
2244
		}
2245
2246
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2247
	}
2248
2249
	/**
2250
	 * Set the plugin instance.
2251
	 *
2252
	 * @param Plugin $plugin_instance The plugin instance.
2253
	 *
2254
	 * @return $this
2255
	 */
2256
	public function set_plugin_instance( Plugin $plugin_instance ) {
2257
		$this->plugin = $plugin_instance;
2258
2259
		return $this;
2260
	}
2261
2262
	/**
2263
	 * Retrieve the plugin management object.
2264
	 *
2265
	 * @return Plugin
2266
	 */
2267
	public function get_plugin() {
2268
		return $this->plugin;
2269
	}
2270
2271
	/**
2272
	 * Get all connected plugins information.
2273
	 *
2274
	 * @return array|\WP_Error
2275
	 */
2276
	public function get_connected_plugins() {
2277
		return Plugin_Storage::get_all();
2278
	}
2279
2280
}
2281