Completed
Push — try/jetpack-stories-block-mobi... ( 2fea66 )
by
unknown
126:35 queued 116:47
created

packages/connection/src/class-manager.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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

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

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

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

Loading history...
2343
			} else {
2344
				return $suppress_errors ? false : new \WP_Error( 'no_valid_blog_token', __( 'Invalid blog token', 'jetpack' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'no_valid_blog_token'.

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

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

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

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