Completed
Push — update/instagram-oembed-simpli... ( f48bfe...478cfa )
by Bernhard
08:24
created

packages/connection/src/class-manager.php (1 issue)

Labels
Severity

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\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Tracking;
14
use Jetpack_Options;
15
use WP_Error;
16
use WP_User;
17
use Automattic\Jetpack\Heartbeat;
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 ) || strval( $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() : intval( $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
			)
881
		);
882
883
		$args = array(
884
			'method'  => 'POST',
885
			'body'    => $body,
886
			'headers' => array(
887
				'Accept' => 'application/json',
888
			),
889
			'timeout' => $timeout,
890
		);
891
892
		$args['body'] = $this->apply_activation_source_to_args( $args['body'] );
893
894
		// TODO: fix URLs for bad hosts.
895
		$response = Client::_wp_remote_request(
896
			$this->api_url( $api_endpoint ),
897
			$args,
898
			true
899
		);
900
901
		// Make sure the response is valid and does not contain any Jetpack errors.
902
		$registration_details = $this->validate_remote_register_response( $response );
903
904
		if ( is_wp_error( $registration_details ) ) {
905
			return $registration_details;
906
		} elseif ( ! $registration_details ) {
907
			return new \WP_Error(
908
				'unknown_error',
909
				'Unknown error registering your Jetpack site.',
910
				wp_remote_retrieve_response_code( $response )
911
			);
912
		}
913
914
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
915
			return new \WP_Error(
916
				'jetpack_secret',
917
				'Unable to validate registration of your Jetpack site.',
918
				wp_remote_retrieve_response_code( $response )
919
			);
920
		}
921
922
		if ( isset( $registration_details->jetpack_public ) ) {
923
			$jetpack_public = (int) $registration_details->jetpack_public;
924
		} else {
925
			$jetpack_public = false;
926
		}
927
928
		\Jetpack_Options::update_options(
929
			array(
930
				'id'         => (int) $registration_details->jetpack_id,
931
				'blog_token' => (string) $registration_details->jetpack_secret,
932
				'public'     => $jetpack_public,
933
			)
934
		);
935
936
		/**
937
		 * Fires when a site is registered on WordPress.com.
938
		 *
939
		 * @since 3.7.0
940
		 *
941
		 * @param int $json->jetpack_id Jetpack Blog ID.
942
		 * @param string $json->jetpack_secret Jetpack Blog Token.
943
		 * @param int|bool $jetpack_public Is the site public.
944
		 */
945
		do_action(
946
			'jetpack_site_registered',
947
			$registration_details->jetpack_id,
948
			$registration_details->jetpack_secret,
949
			$jetpack_public
950
		);
951
952
		if ( isset( $registration_details->token ) ) {
953
			/**
954
			 * Fires when a user token is sent along with the registration data.
955
			 *
956
			 * @since 7.6.0
957
			 *
958
			 * @param object $token the administrator token for the newly registered site.
959
			 */
960
			do_action( 'jetpack_site_registered_user_token', $registration_details->token );
961
		}
962
963
		return true;
964
	}
965
966
	/**
967
	 * Takes the response from the Jetpack register new site endpoint and
968
	 * verifies it worked properly.
969
	 *
970
	 * @since 2.6
971
	 *
972
	 * @param Mixed $response the response object, or the error object.
973
	 * @return string|WP_Error A JSON object on success or WP_Error on failures
974
	 **/
975
	protected function validate_remote_register_response( $response ) {
976
		if ( is_wp_error( $response ) ) {
977
			return new \WP_Error(
978
				'register_http_request_failed',
979
				$response->get_error_message()
980
			);
981
		}
982
983
		$code   = wp_remote_retrieve_response_code( $response );
984
		$entity = wp_remote_retrieve_body( $response );
985
986
		if ( $entity ) {
987
			$registration_response = json_decode( $entity );
988
		} else {
989
			$registration_response = false;
990
		}
991
992
		$code_type = intval( $code / 100 );
993
		if ( 5 === $code_type ) {
994
			return new \WP_Error( 'wpcom_5??', $code );
995
		} elseif ( 408 === $code ) {
996
			return new \WP_Error( 'wpcom_408', $code );
997
		} elseif ( ! empty( $registration_response->error ) ) {
998
			if (
999
				'xml_rpc-32700' === $registration_response->error
1000
				&& ! function_exists( 'xml_parser_create' )
1001
			) {
1002
				$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' );
1003
			} else {
1004
				$error_description = isset( $registration_response->error_description )
1005
					? (string) $registration_response->error_description
1006
					: '';
1007
			}
1008
1009
			return new \WP_Error(
1010
				(string) $registration_response->error,
1011
				$error_description,
1012
				$code
1013
			);
1014
		} elseif ( 200 !== $code ) {
1015
			return new \WP_Error( 'wpcom_bad_response', $code );
1016
		}
1017
1018
		// Jetpack ID error block.
1019
		if ( empty( $registration_response->jetpack_id ) ) {
1020
			return new \WP_Error(
1021
				'jetpack_id',
1022
				/* translators: %s is an error message string */
1023
				sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1024
				$entity
1025
			);
1026
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
1027
			return new \WP_Error(
1028
				'jetpack_id',
1029
				/* translators: %s is an error message string */
1030
				sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1031
				$entity
1032
			);
1033 View Code Duplication
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
1034
			return new \WP_Error(
1035
				'jetpack_id',
1036
				/* translators: %s is an error message string */
1037
				sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ), $entity ),
1038
				$entity
1039
			);
1040
		}
1041
1042
		return $registration_response;
1043
	}
1044
1045
	/**
1046
	 * Adds a used nonce to a list of known nonces.
1047
	 *
1048
	 * @param int    $timestamp the current request timestamp.
1049
	 * @param string $nonce the nonce value.
1050
	 * @return bool whether the nonce is unique or not.
1051
	 */
1052
	public function add_nonce( $timestamp, $nonce ) {
1053
		global $wpdb;
1054
		static $nonces_used_this_request = array();
1055
1056
		if ( isset( $nonces_used_this_request[ "$timestamp:$nonce" ] ) ) {
1057
			return $nonces_used_this_request[ "$timestamp:$nonce" ];
1058
		}
1059
1060
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce.
1061
		$timestamp = (int) $timestamp;
1062
		$nonce     = esc_sql( $nonce );
1063
1064
		// Raw query so we can avoid races: add_option will also update.
1065
		$show_errors = $wpdb->show_errors( false );
1066
1067
		$old_nonce = $wpdb->get_row(
1068
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
1069
		);
1070
1071
		if ( is_null( $old_nonce ) ) {
1072
			$return = $wpdb->query(
1073
				$wpdb->prepare(
1074
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
1075
					"jetpack_nonce_{$timestamp}_{$nonce}",
1076
					time(),
1077
					'no'
1078
				)
1079
			);
1080
		} else {
1081
			$return = false;
1082
		}
1083
1084
		$wpdb->show_errors( $show_errors );
1085
1086
		$nonces_used_this_request[ "$timestamp:$nonce" ] = $return;
1087
1088
		return $return;
1089
	}
1090
1091
	/**
1092
	 * Cleans nonces that were saved when calling ::add_nonce.
1093
	 *
1094
	 * @todo Properly prepare the query before executing it.
1095
	 *
1096
	 * @param bool $all whether to clean even non-expired nonces.
1097
	 */
1098
	public function clean_nonces( $all = false ) {
1099
		global $wpdb;
1100
1101
		$sql      = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
1102
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
1103
1104
		if ( true !== $all ) {
1105
			$sql       .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
1106
			$sql_args[] = time() - 3600;
1107
		}
1108
1109
		$sql .= ' ORDER BY `option_id` LIMIT 100';
1110
1111
		$sql = $wpdb->prepare( $sql, $sql_args ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1112
1113
		for ( $i = 0; $i < 1000; $i++ ) {
1114
			if ( ! $wpdb->query( $sql ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1115
				break;
1116
			}
1117
		}
1118
	}
1119
1120
	/**
1121
	 * Sets the Connection custom capabilities.
1122
	 *
1123
	 * @param string[] $caps    Array of the user's capabilities.
1124
	 * @param string   $cap     Capability name.
1125
	 * @param int      $user_id The user ID.
1126
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1127
	 */
1128
	public function jetpack_connection_custom_caps( $caps, $cap, $user_id, $args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1129
		$is_offline_mode = ( new Status() )->is_offline_mode();
1130
		switch ( $cap ) {
1131
			case 'jetpack_connect':
1132
			case 'jetpack_reconnect':
1133
				if ( $is_offline_mode ) {
1134
					$caps = array( 'do_not_allow' );
1135
					break;
1136
				}
1137
				// Pass through. If it's not offline mode, these should match disconnect.
1138
				// Let users disconnect if it's offline mode, just in case things glitch.
1139
			case 'jetpack_disconnect':
1140
				/**
1141
				 * Filters the jetpack_disconnect capability.
1142
				 *
1143
				 * @since 8.7.0
1144
				 *
1145
				 * @param array An array containing the capability name.
1146
				 */
1147
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1148
				break;
1149
			case 'jetpack_connect_user':
1150
				if ( $is_offline_mode ) {
1151
					$caps = array( 'do_not_allow' );
1152
					break;
1153
				}
1154
				$caps = array( 'read' );
1155
				break;
1156
		}
1157
		return $caps;
1158
	}
1159
1160
	/**
1161
	 * Builds the timeout limit for queries talking with the wpcom servers.
1162
	 *
1163
	 * Based on local php max_execution_time in php.ini
1164
	 *
1165
	 * @since 5.4
1166
	 * @return int
1167
	 **/
1168
	public function get_max_execution_time() {
1169
		$timeout = (int) ini_get( 'max_execution_time' );
1170
1171
		// Ensure exec time set in php.ini.
1172
		if ( ! $timeout ) {
1173
			$timeout = 30;
1174
		}
1175
		return $timeout;
1176
	}
1177
1178
	/**
1179
	 * Sets a minimum request timeout, and returns the current timeout
1180
	 *
1181
	 * @since 5.4
1182
	 * @param Integer $min_timeout the minimum timeout value.
1183
	 **/
1184 View Code Duplication
	public function set_min_time_limit( $min_timeout ) {
1185
		$timeout = $this->get_max_execution_time();
1186
		if ( $timeout < $min_timeout ) {
1187
			$timeout = $min_timeout;
1188
			set_time_limit( $timeout );
1189
		}
1190
		return $timeout;
1191
	}
1192
1193
	/**
1194
	 * Get our assumed site creation date.
1195
	 * Calculated based on the earlier date of either:
1196
	 * - Earliest admin user registration date.
1197
	 * - Earliest date of post of any post type.
1198
	 *
1199
	 * @since 7.2.0
1200
	 *
1201
	 * @return string Assumed site creation date and time.
1202
	 */
1203
	public function get_assumed_site_creation_date() {
1204
		$cached_date = get_transient( 'jetpack_assumed_site_creation_date' );
1205
		if ( ! empty( $cached_date ) ) {
1206
			return $cached_date;
1207
		}
1208
1209
		$earliest_registered_users  = get_users(
1210
			array(
1211
				'role'    => 'administrator',
1212
				'orderby' => 'user_registered',
1213
				'order'   => 'ASC',
1214
				'fields'  => array( 'user_registered' ),
1215
				'number'  => 1,
1216
			)
1217
		);
1218
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
1219
1220
		$earliest_posts = get_posts(
1221
			array(
1222
				'posts_per_page' => 1,
1223
				'post_type'      => 'any',
1224
				'post_status'    => 'any',
1225
				'orderby'        => 'date',
1226
				'order'          => 'ASC',
1227
			)
1228
		);
1229
1230
		// If there are no posts at all, we'll count only on user registration date.
1231
		if ( $earliest_posts ) {
1232
			$earliest_post_date = $earliest_posts[0]->post_date;
1233
		} else {
1234
			$earliest_post_date = PHP_INT_MAX;
1235
		}
1236
1237
		$assumed_date = min( $earliest_registration_date, $earliest_post_date );
1238
		set_transient( 'jetpack_assumed_site_creation_date', $assumed_date );
1239
1240
		return $assumed_date;
1241
	}
1242
1243
	/**
1244
	 * Adds the activation source string as a parameter to passed arguments.
1245
	 *
1246
	 * @todo Refactor to use rawurlencode() instead of urlencode().
1247
	 *
1248
	 * @param array $args arguments that need to have the source added.
1249
	 * @return array $amended arguments.
1250
	 */
1251 View Code Duplication
	public static function apply_activation_source_to_args( $args ) {
1252
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
1253
1254
		if ( $activation_source_name ) {
1255
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1256
			$args['_as'] = urlencode( $activation_source_name );
1257
		}
1258
1259
		if ( $activation_source_keyword ) {
1260
			// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.urlencode_urlencode
1261
			$args['_ak'] = urlencode( $activation_source_keyword );
1262
		}
1263
1264
		return $args;
1265
	}
1266
1267
	/**
1268
	 * Returns the callable that would be used to generate secrets.
1269
	 *
1270
	 * @return Callable a function that returns a secure string to be used as a secret.
1271
	 */
1272
	protected function get_secret_callable() {
1273
		if ( ! isset( $this->secret_callable ) ) {
1274
			/**
1275
			 * Allows modification of the callable that is used to generate connection secrets.
1276
			 *
1277
			 * @param Callable a function or method that returns a secret string.
1278
			 */
1279
			$this->secret_callable = apply_filters( 'jetpack_connection_secret_generator', array( $this, 'secret_callable_method' ) );
1280
		}
1281
1282
		return $this->secret_callable;
1283
	}
1284
1285
	/**
1286
	 * Runs the wp_generate_password function with the required parameters. This is the
1287
	 * default implementation of the secret callable, can be overridden using the
1288
	 * jetpack_connection_secret_generator filter.
1289
	 *
1290
	 * @return String $secret value.
1291
	 */
1292
	private function secret_callable_method() {
1293
		return wp_generate_password( 32, false );
1294
	}
1295
1296
	/**
1297
	 * Generates two secret tokens and the end of life timestamp for them.
1298
	 *
1299
	 * @param String  $action  The action name.
1300
	 * @param Integer $user_id The user identifier.
1301
	 * @param Integer $exp     Expiration time in seconds.
1302
	 */
1303
	public function generate_secrets( $action, $user_id = false, $exp = 600 ) {
1304
		if ( false === $user_id ) {
1305
			$user_id = get_current_user_id();
1306
		}
1307
1308
		$callable = $this->get_secret_callable();
1309
1310
		$secrets = \Jetpack_Options::get_raw_option(
1311
			self::SECRETS_OPTION_NAME,
1312
			array()
1313
		);
1314
1315
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1316
1317
		if (
1318
			isset( $secrets[ $secret_name ] ) &&
1319
			$secrets[ $secret_name ]['exp'] > time()
1320
		) {
1321
			return $secrets[ $secret_name ];
1322
		}
1323
1324
		$secret_value = array(
1325
			'secret_1' => call_user_func( $callable ),
1326
			'secret_2' => call_user_func( $callable ),
1327
			'exp'      => time() + $exp,
1328
		);
1329
1330
		$secrets[ $secret_name ] = $secret_value;
1331
1332
		\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1333
		return $secrets[ $secret_name ];
1334
	}
1335
1336
	/**
1337
	 * Returns two secret tokens and the end of life timestamp for them.
1338
	 *
1339
	 * @param String  $action  The action name.
1340
	 * @param Integer $user_id The user identifier.
1341
	 * @return string|array an array of secrets or an error string.
1342
	 */
1343
	public function get_secrets( $action, $user_id ) {
1344
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1345
		$secrets     = \Jetpack_Options::get_raw_option(
1346
			self::SECRETS_OPTION_NAME,
1347
			array()
1348
		);
1349
1350
		if ( ! isset( $secrets[ $secret_name ] ) ) {
1351
			return self::SECRETS_MISSING;
1352
		}
1353
1354
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
1355
			$this->delete_secrets( $action, $user_id );
1356
			return self::SECRETS_EXPIRED;
1357
		}
1358
1359
		return $secrets[ $secret_name ];
1360
	}
1361
1362
	/**
1363
	 * Deletes secret tokens in case they, for example, have expired.
1364
	 *
1365
	 * @param String  $action  The action name.
1366
	 * @param Integer $user_id The user identifier.
1367
	 */
1368
	public function delete_secrets( $action, $user_id ) {
1369
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
1370
		$secrets     = \Jetpack_Options::get_raw_option(
1371
			self::SECRETS_OPTION_NAME,
1372
			array()
1373
		);
1374
		if ( isset( $secrets[ $secret_name ] ) ) {
1375
			unset( $secrets[ $secret_name ] );
1376
			\Jetpack_Options::update_raw_option( self::SECRETS_OPTION_NAME, $secrets );
1377
		}
1378
	}
1379
1380
	/**
1381
	 * Deletes all connection tokens and transients from the local Jetpack site.
1382
	 * If the plugin object has been provided in the constructor, the function first checks
1383
	 * whether it's the only active connection.
1384
	 * If there are any other connections, the function will do nothing and return `false`
1385
	 * (unless `$ignore_connected_plugins` is set to `true`).
1386
	 *
1387
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1388
	 *
1389
	 * @return bool True if disconnected successfully, false otherwise.
1390
	 */
1391
	public function delete_all_connection_tokens( $ignore_connected_plugins = false ) {
1392 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1393
			return false;
1394
		}
1395
1396
		/**
1397
		 * Fires upon the disconnect attempt.
1398
		 * Return `false` to prevent the disconnect.
1399
		 *
1400
		 * @since 8.7.0
1401
		 */
1402
		if ( ! apply_filters( 'jetpack_connection_delete_all_tokens', true, $this ) ) {
1403
			return false;
1404
		}
1405
1406
		\Jetpack_Options::delete_option(
1407
			array(
1408
				'blog_token',
1409
				'user_token',
1410
				'user_tokens',
1411
				'master_user',
1412
				'time_diff',
1413
				'fallback_no_verify_ssl_certs',
1414
			)
1415
		);
1416
1417
		\Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
1418
1419
		// Delete cached connected user data.
1420
		$transient_key = 'jetpack_connected_user_data_' . get_current_user_id();
1421
		delete_transient( $transient_key );
1422
1423
		// Delete all XML-RPC errors.
1424
		Error_Handler::get_instance()->delete_all_errors();
1425
1426
		return true;
1427
	}
1428
1429
	/**
1430
	 * Tells WordPress.com to disconnect the site and clear all tokens from cached site.
1431
	 * If the plugin object has been provided in the constructor, the function first check
1432
	 * whether it's the only active connection.
1433
	 * If there are any other connections, the function will do nothing and return `false`
1434
	 * (unless `$ignore_connected_plugins` is set to `true`).
1435
	 *
1436
	 * @param bool $ignore_connected_plugins Delete the tokens even if there are other connected plugins.
1437
	 *
1438
	 * @return bool True if disconnected successfully, false otherwise.
1439
	 */
1440
	public function disconnect_site_wpcom( $ignore_connected_plugins = false ) {
1441 View Code Duplication
		if ( ! $ignore_connected_plugins && null !== $this->plugin && ! $this->plugin->is_only() ) {
1442
			return false;
1443
		}
1444
1445
		/**
1446
		 * Fires upon the disconnect attempt.
1447
		 * Return `false` to prevent the disconnect.
1448
		 *
1449
		 * @since 8.7.0
1450
		 */
1451
		if ( ! apply_filters( 'jetpack_connection_disconnect_site_wpcom', true, $this ) ) {
1452
			return false;
1453
		}
1454
1455
		$xml = new \Jetpack_IXR_Client();
1456
		$xml->query( 'jetpack.deregister', get_current_user_id() );
1457
1458
		return true;
1459
	}
1460
1461
	/**
1462
	 * Disconnect the plugin and remove the tokens.
1463
	 * This function will automatically perform "soft" or "hard" disconnect depending on whether other plugins are using the connection.
1464
	 * This is a proxy method to simplify the Connection package API.
1465
	 *
1466
	 * @see Manager::disable_plugin()
1467
	 * @see Manager::disconnect_site_wpcom()
1468
	 * @see Manager::delete_all_connection_tokens()
1469
	 *
1470
	 * @return bool
1471
	 */
1472
	public function remove_connection() {
1473
		$this->disable_plugin();
1474
		$this->disconnect_site_wpcom();
1475
		$this->delete_all_connection_tokens();
1476
1477
		return true;
1478
	}
1479
1480
	/**
1481
	 * Completely clearing up the connection, and initiating reconnect.
1482
	 *
1483
	 * @return true|WP_Error True if reconnected successfully, a `WP_Error` object otherwise.
1484
	 */
1485
	public function reconnect() {
1486
		( new Tracking() )->record_user_event( 'restore_connection_reconnect' );
1487
1488
		$this->disconnect_site_wpcom( true );
1489
		$this->delete_all_connection_tokens( true );
1490
1491
		return $this->register();
1492
	}
1493
1494
	/**
1495
	 * Validate the tokens, and refresh the invalid ones.
1496
	 *
1497
	 * @return string|true|WP_Error True if connection restored or string indicating what's to be done next. A `WP_Error` object otherwise.
1498
	 */
1499
	public function restore() {
1500
		$invalid_tokens = array();
1501
		$can_restore    = $this->can_restore( $invalid_tokens );
1502
1503
		// Tokens are valid. We can't fix the problem we don't see, so the full reconnection is needed.
1504
		if ( ! $can_restore ) {
1505
			$result = $this->reconnect();
1506
			return true === $result ? 'authorize' : $result;
1507
		}
1508
1509
		if ( in_array( 'blog', $invalid_tokens, true ) ) {
1510
			return self::refresh_blog_token();
1511
		}
1512
1513
		if ( in_array( 'user', $invalid_tokens, true ) ) {
1514
			return true === self::refresh_user_token() ? 'authorize' : false;
1515
		}
1516
1517
		return false;
1518
	}
1519
1520
	/**
1521
	 * Determine whether we can restore the connection, or the full reconnect is needed.
1522
	 *
1523
	 * @param array $invalid_tokens The array the invalid tokens are stored in, provided by reference.
1524
	 *
1525
	 * @return bool `True` if the connection can be restored, `false` otherwise.
1526
	 */
1527
	public function can_restore( &$invalid_tokens ) {
1528
		$invalid_tokens = array();
1529
1530
		$validated_tokens = $this->validate_tokens();
1531
1532
		if ( ! is_array( $validated_tokens ) || count( array_diff_key( array_flip( array( 'blog_token', 'user_token' ) ), $validated_tokens ) ) ) {
1533
			return false;
1534
		}
1535
1536
		if ( empty( $validated_tokens['blog_token']['is_healthy'] ) ) {
1537
			$invalid_tokens[] = 'blog';
1538
		}
1539
1540
		if ( empty( $validated_tokens['user_token']['is_healthy'] ) ) {
1541
			$invalid_tokens[] = 'user';
1542
		}
1543
1544
		// If both tokens are invalid, we can't restore the connection.
1545
		return 1 === count( $invalid_tokens );
1546
	}
1547
1548
	/**
1549
	 * Perform the API request to validate the blog and user tokens.
1550
	 *
1551
	 * @param int|null $user_id ID of the user we need to validate token for. Current user's ID by default.
1552
	 *
1553
	 * @return array|false|WP_Error The API response: `array( 'blog_token_is_healthy' => true|false, 'user_token_is_healthy' => true|false )`.
1554
	 */
1555
	public function validate_tokens( $user_id = null ) {
1556
		$blog_id = Jetpack_Options::get_option( 'id' );
1557
		if ( ! $blog_id ) {
1558
			return new WP_Error( 'site_not_registered', 'Site not registered.' );
1559
		}
1560
		$url = sprintf(
1561
			'%s/%s/v%s/%s',
1562
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
1563
			'wpcom',
1564
			'2',
1565
			'sites/' . $blog_id . '/jetpack-token-health'
1566
		);
1567
1568
		$user_token = $this->get_access_token( $user_id ? $user_id : get_current_user_id() );
1569
		$blog_token = $this->get_access_token();
1570
		$method     = 'POST';
1571
		$body       = array(
1572
			'user_token' => $this->get_signed_token( $user_token ),
1573
			'blog_token' => $this->get_signed_token( $blog_token ),
1574
		);
1575
		$response   = Client::_wp_remote_request( $url, compact( 'body', 'method' ) );
1576
1577
		if ( is_wp_error( $response ) || ! wp_remote_retrieve_body( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
1578
			return false;
1579
		}
1580
1581
		$body = json_decode( wp_remote_retrieve_body( $response ), true );
1582
1583
		return $body ? $body : false;
1584
	}
1585
1586
	/**
1587
	 * Responds to a WordPress.com call to register the current site.
1588
	 * Should be changed to protected.
1589
	 *
1590
	 * @param array $registration_data Array of [ secret_1, user_id ].
1591
	 */
1592
	public function handle_registration( array $registration_data ) {
1593
		list( $registration_secret_1, $registration_user_id ) = $registration_data;
1594
		if ( empty( $registration_user_id ) ) {
1595
			return new \WP_Error( 'registration_state_invalid', __( 'Invalid Registration State', 'jetpack' ), 400 );
1596
		}
1597
1598
		return $this->verify_secrets( 'register', $registration_secret_1, (int) $registration_user_id );
1599
	}
1600
1601
	/**
1602
	 * Verify a Previously Generated Secret.
1603
	 *
1604
	 * @param string $action   The type of secret to verify.
1605
	 * @param string $secret_1 The secret string to compare to what is stored.
1606
	 * @param int    $user_id  The user ID of the owner of the secret.
1607
	 * @return \WP_Error|string WP_Error on failure, secret_2 on success.
1608
	 */
1609
	public function verify_secrets( $action, $secret_1, $user_id ) {
1610
		$allowed_actions = array( 'register', 'authorize', 'publicize' );
1611
		if ( ! in_array( $action, $allowed_actions, true ) ) {
1612
			return new \WP_Error( 'unknown_verification_action', 'Unknown Verification Action', 400 );
1613
		}
1614
1615
		$user = get_user_by( 'id', $user_id );
1616
1617
		/**
1618
		 * We've begun verifying the previously generated secret.
1619
		 *
1620
		 * @since 7.5.0
1621
		 *
1622
		 * @param string   $action The type of secret to verify.
1623
		 * @param \WP_User $user The user object.
1624
		 */
1625
		do_action( 'jetpack_verify_secrets_begin', $action, $user );
1626
1627
		$return_error = function( \WP_Error $error ) use ( $action, $user ) {
1628
			/**
1629
			 * Verifying of the previously generated secret has failed.
1630
			 *
1631
			 * @since 7.5.0
1632
			 *
1633
			 * @param string    $action  The type of secret to verify.
1634
			 * @param \WP_User  $user The user object.
1635
			 * @param \WP_Error $error The error object.
1636
			 */
1637
			do_action( 'jetpack_verify_secrets_fail', $action, $user, $error );
1638
1639
			return $error;
1640
		};
1641
1642
		$stored_secrets = $this->get_secrets( $action, $user_id );
1643
		$this->delete_secrets( $action, $user_id );
1644
1645
		$error = null;
1646
		if ( empty( $secret_1 ) ) {
1647
			$error = $return_error(
1648
				new \WP_Error(
1649
					'verify_secret_1_missing',
1650
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1651
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'secret_1' ),
1652
					400
1653
				)
1654
			);
1655
		} elseif ( ! is_string( $secret_1 ) ) {
1656
			$error = $return_error(
1657
				new \WP_Error(
1658
					'verify_secret_1_malformed',
1659
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1660
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'secret_1' ),
1661
					400
1662
				)
1663
			);
1664
		} elseif ( empty( $user_id ) ) {
1665
			// $user_id is passed around during registration as "state".
1666
			$error = $return_error(
1667
				new \WP_Error(
1668
					'state_missing',
1669
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1670
					sprintf( __( 'The required "%s" parameter is missing.', 'jetpack' ), 'state' ),
1671
					400
1672
				)
1673
			);
1674
		} elseif ( ! ctype_digit( (string) $user_id ) ) {
1675
			$error = $return_error(
1676
				new \WP_Error(
1677
					'state_malformed',
1678
					/* translators: "%s" is the name of a paramter. It can be either "secret_1" or "state". */
1679
					sprintf( __( 'The required "%s" parameter is malformed.', 'jetpack' ), 'state' ),
1680
					400
1681
				)
1682
			);
1683
		} elseif ( self::SECRETS_MISSING === $stored_secrets ) {
1684
			$error = $return_error(
1685
				new \WP_Error(
1686
					'verify_secrets_missing',
1687
					__( 'Verification secrets not found', 'jetpack' ),
1688
					400
1689
				)
1690
			);
1691
		} elseif ( self::SECRETS_EXPIRED === $stored_secrets ) {
1692
			$error = $return_error(
1693
				new \WP_Error(
1694
					'verify_secrets_expired',
1695
					__( 'Verification took too long', 'jetpack' ),
1696
					400
1697
				)
1698
			);
1699
		} elseif ( ! $stored_secrets ) {
1700
			$error = $return_error(
1701
				new \WP_Error(
1702
					'verify_secrets_empty',
1703
					__( 'Verification secrets are empty', 'jetpack' ),
1704
					400
1705
				)
1706
			);
1707
		} elseif ( is_wp_error( $stored_secrets ) ) {
1708
			$stored_secrets->add_data( 400 );
1709
			$error = $return_error( $stored_secrets );
1710
		} elseif ( empty( $stored_secrets['secret_1'] ) || empty( $stored_secrets['secret_2'] ) || empty( $stored_secrets['exp'] ) ) {
1711
			$error = $return_error(
1712
				new \WP_Error(
1713
					'verify_secrets_incomplete',
1714
					__( 'Verification secrets are incomplete', 'jetpack' ),
1715
					400
1716
				)
1717
			);
1718
		} elseif ( ! hash_equals( $secret_1, $stored_secrets['secret_1'] ) ) {
1719
			$error = $return_error(
1720
				new \WP_Error(
1721
					'verify_secrets_mismatch',
1722
					__( 'Secret mismatch', 'jetpack' ),
1723
					400
1724
				)
1725
			);
1726
		}
1727
1728
		// Something went wrong during the checks, returning the error.
1729
		if ( ! empty( $error ) ) {
1730
			return $error;
1731
		}
1732
1733
		/**
1734
		 * We've succeeded at verifying the previously generated secret.
1735
		 *
1736
		 * @since 7.5.0
1737
		 *
1738
		 * @param string   $action The type of secret to verify.
1739
		 * @param \WP_User $user The user object.
1740
		 */
1741
		do_action( 'jetpack_verify_secrets_success', $action, $user );
1742
1743
		return $stored_secrets['secret_2'];
1744
	}
1745
1746
	/**
1747
	 * Responds to a WordPress.com call to authorize the current user.
1748
	 * Should be changed to protected.
1749
	 */
1750
	public function handle_authorization() {
1751
1752
	}
1753
1754
	/**
1755
	 * Obtains the auth token.
1756
	 *
1757
	 * @param array $data The request data.
1758
	 * @return object|\WP_Error Returns the auth token on success.
1759
	 *                          Returns a \WP_Error on failure.
1760
	 */
1761
	public function get_token( $data ) {
1762
		$roles = new Roles();
1763
		$role  = $roles->translate_current_user_to_role();
1764
1765
		if ( ! $role ) {
1766
			return new \WP_Error( 'role', __( 'An administrator for this blog must set up the Jetpack connection.', 'jetpack' ) );
1767
		}
1768
1769
		$client_secret = $this->get_access_token();
1770
		if ( ! $client_secret ) {
1771
			return new \WP_Error( 'client_secret', __( 'You need to register your Jetpack before connecting it.', 'jetpack' ) );
1772
		}
1773
1774
		/**
1775
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1776
		 * data processing.
1777
		 *
1778
		 * @since 8.0.0
1779
		 *
1780
		 * @param string $redirect_url Defaults to the site admin URL.
1781
		 */
1782
		$processing_url = apply_filters( 'jetpack_token_processing_url', admin_url( 'admin.php' ) );
1783
1784
		$redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
1785
1786
		/**
1787
		* Filter the URL to redirect the user back to when the authentication process
1788
		* is complete.
1789
		*
1790
		* @since 8.0.0
1791
		*
1792
		* @param string $redirect_url Defaults to the site URL.
1793
		*/
1794
		$redirect = apply_filters( 'jetpack_token_redirect_url', $redirect );
1795
1796
		$redirect_uri = ( 'calypso' === $data['auth_type'] )
1797
			? $data['redirect_uri']
1798
			: add_query_arg(
1799
				array(
1800
					'action'   => 'authorize',
1801
					'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1802
					'redirect' => $redirect ? rawurlencode( $redirect ) : false,
1803
				),
1804
				esc_url( $processing_url )
1805
			);
1806
1807
		/**
1808
		 * Filters the token request data.
1809
		 *
1810
		 * @since 8.0.0
1811
		 *
1812
		 * @param array $request_data request data.
1813
		 */
1814
		$body = apply_filters(
1815
			'jetpack_token_request_body',
1816
			array(
1817
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1818
				'client_secret' => $client_secret->secret,
1819
				'grant_type'    => 'authorization_code',
1820
				'code'          => $data['code'],
1821
				'redirect_uri'  => $redirect_uri,
1822
			)
1823
		);
1824
1825
		$args = array(
1826
			'method'  => 'POST',
1827
			'body'    => $body,
1828
			'headers' => array(
1829
				'Accept' => 'application/json',
1830
			),
1831
		);
1832
1833
		add_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1834
		$response = Client::_wp_remote_request( $this->api_url( 'token' ), $args );
1835
		remove_filter( 'http_request_timeout', array( $this, 'increase_timeout' ), PHP_INT_MAX - 1 );
1836
1837
		if ( is_wp_error( $response ) ) {
1838
			return new \WP_Error( 'token_http_request_failed', $response->get_error_message() );
1839
		}
1840
1841
		$code   = wp_remote_retrieve_response_code( $response );
1842
		$entity = wp_remote_retrieve_body( $response );
1843
1844
		if ( $entity ) {
1845
			$json = json_decode( $entity );
1846
		} else {
1847
			$json = false;
1848
		}
1849
1850 View Code Duplication
		if ( 200 !== $code || ! empty( $json->error ) ) {
1851
			if ( empty( $json->error ) ) {
1852
				return new \WP_Error( 'unknown', '', $code );
1853
			}
1854
1855
			/* translators: Error description string. */
1856
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
1857
1858
			return new \WP_Error( (string) $json->error, $error_description, $code );
1859
		}
1860
1861
		if ( empty( $json->access_token ) || ! is_scalar( $json->access_token ) ) {
1862
			return new \WP_Error( 'access_token', '', $code );
1863
		}
1864
1865
		if ( empty( $json->token_type ) || 'X_JETPACK' !== strtoupper( $json->token_type ) ) {
1866
			return new \WP_Error( 'token_type', '', $code );
1867
		}
1868
1869
		if ( empty( $json->scope ) ) {
1870
			return new \WP_Error( 'scope', 'No Scope', $code );
1871
		}
1872
1873
		// TODO: get rid of the error silencer.
1874
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1875
		@list( $role, $hmac ) = explode( ':', $json->scope );
1876
		if ( empty( $role ) || empty( $hmac ) ) {
1877
			return new \WP_Error( 'scope', 'Malformed Scope', $code );
1878
		}
1879
1880
		if ( $this->sign_role( $role ) !== $json->scope ) {
1881
			return new \WP_Error( 'scope', 'Invalid Scope', $code );
1882
		}
1883
1884
		$cap = $roles->translate_role_to_cap( $role );
1885
		if ( ! $cap ) {
1886
			return new \WP_Error( 'scope', 'No Cap', $code );
1887
		}
1888
1889
		if ( ! current_user_can( $cap ) ) {
1890
			return new \WP_Error( 'scope', 'current_user_cannot', $code );
1891
		}
1892
1893
		return (string) $json->access_token;
1894
	}
1895
1896
	/**
1897
	 * Increases the request timeout value to 30 seconds.
1898
	 *
1899
	 * @return int Returns 30.
1900
	 */
1901
	public function increase_timeout() {
1902
		return 30;
1903
	}
1904
1905
	/**
1906
	 * Builds a URL to the Jetpack connection auth page.
1907
	 *
1908
	 * @param WP_User $user (optional) defaults to the current logged in user.
1909
	 * @param String  $redirect (optional) a redirect URL to use instead of the default.
1910
	 * @return string Connect URL.
1911
	 */
1912
	public function get_authorization_url( $user = null, $redirect = null ) {
1913
1914
		if ( empty( $user ) ) {
1915
			$user = wp_get_current_user();
1916
		}
1917
1918
		$roles       = new Roles();
1919
		$role        = $roles->translate_user_to_role( $user );
1920
		$signed_role = $this->sign_role( $role );
1921
1922
		/**
1923
		 * Filter the URL of the first time the user gets redirected back to your site for connection
1924
		 * data processing.
1925
		 *
1926
		 * @since 8.0.0
1927
		 *
1928
		 * @param string $redirect_url Defaults to the site admin URL.
1929
		 */
1930
		$processing_url = apply_filters( 'jetpack_connect_processing_url', admin_url( 'admin.php' ) );
1931
1932
		/**
1933
		 * Filter the URL to redirect the user back to when the authorization process
1934
		 * is complete.
1935
		 *
1936
		 * @since 8.0.0
1937
		 *
1938
		 * @param string $redirect_url Defaults to the site URL.
1939
		 */
1940
		$redirect = apply_filters( 'jetpack_connect_redirect_url', $redirect );
1941
1942
		$secrets = $this->generate_secrets( 'authorize', $user->ID, 2 * HOUR_IN_SECONDS );
1943
1944
		/**
1945
		 * Filter the type of authorization.
1946
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
1947
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
1948
		 *
1949
		 * @since 4.3.3
1950
		 *
1951
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
1952
		 */
1953
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
1954
1955
		/**
1956
		 * Filters the user connection request data for additional property addition.
1957
		 *
1958
		 * @since 8.0.0
1959
		 *
1960
		 * @param array $request_data request data.
1961
		 */
1962
		$body = apply_filters(
1963
			'jetpack_connect_request_body',
1964
			array(
1965
				'response_type' => 'code',
1966
				'client_id'     => \Jetpack_Options::get_option( 'id' ),
1967
				'redirect_uri'  => add_query_arg(
1968
					array(
1969
						'action'   => 'authorize',
1970
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
1971
						'redirect' => rawurlencode( $redirect ),
1972
					),
1973
					esc_url( $processing_url )
1974
				),
1975
				'state'         => $user->ID,
1976
				'scope'         => $signed_role,
1977
				'user_email'    => $user->user_email,
1978
				'user_login'    => $user->user_login,
1979
				'is_active'     => $this->is_active(),
1980
				'jp_version'    => Constants::get_constant( 'JETPACK__VERSION' ),
1981
				'auth_type'     => $auth_type,
1982
				'secret'        => $secrets['secret_1'],
1983
				'blogname'      => get_option( 'blogname' ),
1984
				'site_url'      => site_url(),
1985
				'home_url'      => home_url(),
1986
				'site_icon'     => get_site_icon_url(),
1987
				'site_lang'     => get_locale(),
1988
				'site_created'  => $this->get_assumed_site_creation_date(),
1989
			)
1990
		);
1991
1992
		$body = $this->apply_activation_source_to_args( urlencode_deep( $body ) );
1993
1994
		$api_url = $this->api_url( 'authorize' );
1995
1996
		return add_query_arg( $body, $api_url );
1997
	}
1998
1999
	/**
2000
	 * Authorizes the user by obtaining and storing the user token.
2001
	 *
2002
	 * @param array $data The request data.
2003
	 * @return string|\WP_Error Returns a string on success.
2004
	 *                          Returns a \WP_Error on failure.
2005
	 */
2006
	public function authorize( $data = array() ) {
2007
		/**
2008
		 * Action fired when user authorization starts.
2009
		 *
2010
		 * @since 8.0.0
2011
		 */
2012
		do_action( 'jetpack_authorize_starting' );
2013
2014
		$roles = new Roles();
2015
		$role  = $roles->translate_current_user_to_role();
2016
2017
		if ( ! $role ) {
2018
			return new \WP_Error( 'no_role', 'Invalid request.', 400 );
2019
		}
2020
2021
		$cap = $roles->translate_role_to_cap( $role );
2022
		if ( ! $cap ) {
2023
			return new \WP_Error( 'no_cap', 'Invalid request.', 400 );
2024
		}
2025
2026
		if ( ! empty( $data['error'] ) ) {
2027
			return new \WP_Error( $data['error'], 'Error included in the request.', 400 );
2028
		}
2029
2030
		if ( ! isset( $data['state'] ) ) {
2031
			return new \WP_Error( 'no_state', 'Request must include state.', 400 );
2032
		}
2033
2034
		if ( ! ctype_digit( $data['state'] ) ) {
2035
			return new \WP_Error( $data['error'], 'State must be an integer.', 400 );
2036
		}
2037
2038
		$current_user_id = get_current_user_id();
2039
		if ( $current_user_id !== (int) $data['state'] ) {
2040
			return new \WP_Error( 'wrong_state', 'State does not match current user.', 400 );
2041
		}
2042
2043
		if ( empty( $data['code'] ) ) {
2044
			return new \WP_Error( 'no_code', 'Request must include an authorization code.', 400 );
2045
		}
2046
2047
		$token = $this->get_token( $data );
2048
2049 View Code Duplication
		if ( is_wp_error( $token ) ) {
2050
			$code = $token->get_error_code();
2051
			if ( empty( $code ) ) {
2052
				$code = 'invalid_token';
2053
			}
2054
			return new \WP_Error( $code, $token->get_error_message(), 400 );
2055
		}
2056
2057
		if ( ! $token ) {
2058
			return new \WP_Error( 'no_token', 'Error generating token.', 400 );
2059
		}
2060
2061
		$is_master_user = ! $this->is_active();
2062
2063
		Utils::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
2064
2065
		/**
2066
		 * Fires after user has successfully received an auth token.
2067
		 *
2068
		 * @since 3.9.0
2069
		 */
2070
		do_action( 'jetpack_user_authorized' );
2071
2072
		if ( ! $is_master_user ) {
2073
			/**
2074
			 * Action fired when a secondary user has been authorized.
2075
			 *
2076
			 * @since 8.0.0
2077
			 */
2078
			do_action( 'jetpack_authorize_ending_linked' );
2079
			return 'linked';
2080
		}
2081
2082
		/**
2083
		 * Action fired when the master user has been authorized.
2084
		 *
2085
		 * @since 8.0.0
2086
		 *
2087
		 * @param array $data The request data.
2088
		 */
2089
		do_action( 'jetpack_authorize_ending_authorized', $data );
2090
2091
		\Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
2092
2093
		// Start nonce cleaner.
2094
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2095
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
2096
2097
		return 'authorized';
2098
	}
2099
2100
	/**
2101
	 * Disconnects from the Jetpack servers.
2102
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2103
	 */
2104
	public function disconnect_site() {
2105
2106
	}
2107
2108
	/**
2109
	 * The Base64 Encoding of the SHA1 Hash of the Input.
2110
	 *
2111
	 * @param string $text The string to hash.
2112
	 * @return string
2113
	 */
2114
	public function sha1_base64( $text ) {
2115
		return base64_encode( sha1( $text, true ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2116
	}
2117
2118
	/**
2119
	 * This function mirrors Jetpack_Data::is_usable_domain() in the WPCOM codebase.
2120
	 *
2121
	 * @param string $domain The domain to check.
2122
	 *
2123
	 * @return bool|WP_Error
2124
	 */
2125
	public function is_usable_domain( $domain ) {
2126
2127
		// If it's empty, just fail out.
2128
		if ( ! $domain ) {
2129
			return new \WP_Error(
2130
				'fail_domain_empty',
2131
				/* translators: %1$s is a domain name. */
2132
				sprintf( __( 'Domain `%1$s` just failed is_usable_domain check as it is empty.', 'jetpack' ), $domain )
2133
			);
2134
		}
2135
2136
		/**
2137
		 * Skips the usuable domain check when connecting a site.
2138
		 *
2139
		 * Allows site administrators with domains that fail gethostname-based checks to pass the request to WP.com
2140
		 *
2141
		 * @since 4.1.0
2142
		 *
2143
		 * @param bool If the check should be skipped. Default false.
2144
		 */
2145
		if ( apply_filters( 'jetpack_skip_usuable_domain_check', false ) ) {
2146
			return true;
2147
		}
2148
2149
		// None of the explicit localhosts.
2150
		$forbidden_domains = array(
2151
			'wordpress.com',
2152
			'localhost',
2153
			'localhost.localdomain',
2154
			'127.0.0.1',
2155
			'local.wordpress.test',         // VVV pattern.
2156
			'local.wordpress-trunk.test',   // VVV pattern.
2157
			'src.wordpress-develop.test',   // VVV pattern.
2158
			'build.wordpress-develop.test', // VVV pattern.
2159
		);
2160 View Code Duplication
		if ( in_array( $domain, $forbidden_domains, true ) ) {
2161
			return new \WP_Error(
2162
				'fail_domain_forbidden',
2163
				sprintf(
2164
					/* translators: %1$s is a domain name. */
2165
					__(
2166
						'Domain `%1$s` just failed is_usable_domain check as it is in the forbidden array.',
2167
						'jetpack'
2168
					),
2169
					$domain
2170
				)
2171
			);
2172
		}
2173
2174
		// No .test or .local domains.
2175 View Code Duplication
		if ( preg_match( '#\.(test|local)$#i', $domain ) ) {
2176
			return new \WP_Error(
2177
				'fail_domain_tld',
2178
				sprintf(
2179
					/* translators: %1$s is a domain name. */
2180
					__(
2181
						'Domain `%1$s` just failed is_usable_domain check as it uses an invalid top level domain.',
2182
						'jetpack'
2183
					),
2184
					$domain
2185
				)
2186
			);
2187
		}
2188
2189
		// No WPCOM subdomains.
2190 View Code Duplication
		if ( preg_match( '#\.WordPress\.com$#i', $domain ) ) {
2191
			return new \WP_Error(
2192
				'fail_subdomain_wpcom',
2193
				sprintf(
2194
					/* translators: %1$s is a domain name. */
2195
					__(
2196
						'Domain `%1$s` just failed is_usable_domain check as it is a subdomain of WordPress.com.',
2197
						'jetpack'
2198
					),
2199
					$domain
2200
				)
2201
			);
2202
		}
2203
2204
		// If PHP was compiled without support for the Filter module (very edge case).
2205
		if ( ! function_exists( 'filter_var' ) ) {
2206
			// Just pass back true for now, and let wpcom sort it out.
2207
			return true;
2208
		}
2209
2210
		return true;
2211
	}
2212
2213
	/**
2214
	 * Gets the requested token.
2215
	 *
2216
	 * Tokens are one of two types:
2217
	 * 1. Blog Tokens: These are the "main" tokens. Each site typically has one Blog Token,
2218
	 *    though some sites can have multiple "Special" Blog Tokens (see below). These tokens
2219
	 *    are not associated with a user account. They represent the site's connection with
2220
	 *    the Jetpack servers.
2221
	 * 2. User Tokens: These are "sub-"tokens. Each connected user account has one User Token.
2222
	 *
2223
	 * All tokens look like "{$token_key}.{$private}". $token_key is a public ID for the
2224
	 * token, and $private is a secret that should never be displayed anywhere or sent
2225
	 * over the network; it's used only for signing things.
2226
	 *
2227
	 * Blog Tokens can be "Normal" or "Special".
2228
	 * * Normal: The result of a normal connection flow. They look like
2229
	 *   "{$random_string_1}.{$random_string_2}"
2230
	 *   That is, $token_key and $private are both random strings.
2231
	 *   Sites only have one Normal Blog Token. Normal Tokens are found in either
2232
	 *   Jetpack_Options::get_option( 'blog_token' ) (usual) or the JETPACK_BLOG_TOKEN
2233
	 *   constant (rare).
2234
	 * * Special: A connection token for sites that have gone through an alternative
2235
	 *   connection flow. They look like:
2236
	 *   ";{$special_id}{$special_version};{$wpcom_blog_id};.{$random_string}"
2237
	 *   That is, $private is a random string and $token_key has a special structure with
2238
	 *   lots of semicolons.
2239
	 *   Most sites have zero Special Blog Tokens. Special tokens are only found in the
2240
	 *   JETPACK_BLOG_TOKEN constant.
2241
	 *
2242
	 * In particular, note that Normal Blog Tokens never start with ";" and that
2243
	 * Special Blog Tokens always do.
2244
	 *
2245
	 * When searching for a matching Blog Tokens, Blog Tokens are examined in the following
2246
	 * order:
2247
	 * 1. Defined Special Blog Tokens (via the JETPACK_BLOG_TOKEN constant)
2248
	 * 2. Stored Normal Tokens (via Jetpack_Options::get_option( 'blog_token' ))
2249
	 * 3. Defined Normal Tokens (via the JETPACK_BLOG_TOKEN constant)
2250
	 *
2251
	 * @param int|false    $user_id   false: Return the Blog Token. int: Return that user's User Token.
2252
	 * @param string|false $token_key If provided, check that the token matches the provided input.
2253
	 * @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.
2254
	 *
2255
	 * @return object|false
2256
	 */
2257
	public function get_access_token( $user_id = false, $token_key = false, $suppress_errors = true ) {
2258
		$possible_special_tokens = array();
2259
		$possible_normal_tokens  = array();
2260
		$user_tokens             = \Jetpack_Options::get_option( 'user_tokens' );
2261
2262
		if ( $user_id ) {
2263
			if ( ! $user_tokens ) {
2264
				return $suppress_errors ? false : new \WP_Error( 'no_user_tokens', __( 'No user tokens found', 'jetpack' ) );
2265
			}
2266
			if ( self::CONNECTION_OWNER === $user_id ) {
2267
				$user_id = \Jetpack_Options::get_option( 'master_user' );
2268
				if ( ! $user_id ) {
2269
					return $suppress_errors ? false : new \WP_Error( 'empty_master_user_option', __( 'No primary user defined', 'jetpack' ) );
2270
				}
2271
			}
2272
			if ( ! isset( $user_tokens[ $user_id ] ) || ! $user_tokens[ $user_id ] ) {
2273
				// translators: %s is the user ID.
2274
				return $suppress_errors ? false : new \WP_Error( 'no_token_for_user', sprintf( __( 'No token for user %d', 'jetpack' ), $user_id ) );
2275
			}
2276
			$user_token_chunks = explode( '.', $user_tokens[ $user_id ] );
2277 View Code Duplication
			if ( empty( $user_token_chunks[1] ) || empty( $user_token_chunks[2] ) ) {
2278
				// translators: %s is the user ID.
2279
				return $suppress_errors ? false : new \WP_Error( 'token_malformed', sprintf( __( 'Token for user %d is malformed', 'jetpack' ), $user_id ) );
2280
			}
2281
			if ( $user_token_chunks[2] !== (string) $user_id ) {
2282
				// translators: %1$d is the ID of the requested user. %2$d is the user ID found in the token.
2283
				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] ) );
2284
			}
2285
			$possible_normal_tokens[] = "{$user_token_chunks[0]}.{$user_token_chunks[1]}";
2286
		} else {
2287
			$stored_blog_token = \Jetpack_Options::get_option( 'blog_token' );
2288
			if ( $stored_blog_token ) {
2289
				$possible_normal_tokens[] = $stored_blog_token;
2290
			}
2291
2292
			$defined_tokens_string = Constants::get_constant( 'JETPACK_BLOG_TOKEN' );
2293
2294
			if ( $defined_tokens_string ) {
2295
				$defined_tokens = explode( ',', $defined_tokens_string );
2296
				foreach ( $defined_tokens as $defined_token ) {
2297
					if ( ';' === $defined_token[0] ) {
2298
						$possible_special_tokens[] = $defined_token;
2299
					} else {
2300
						$possible_normal_tokens[] = $defined_token;
2301
					}
2302
				}
2303
			}
2304
		}
2305
2306
		if ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2307
			$possible_tokens = $possible_normal_tokens;
2308
		} else {
2309
			$possible_tokens = array_merge( $possible_special_tokens, $possible_normal_tokens );
2310
		}
2311
2312
		if ( ! $possible_tokens ) {
2313
			// If no user tokens were found, it would have failed earlier, so this is about blog token.
2314
			return $suppress_errors ? false : new \WP_Error( 'no_possible_tokens', __( 'No blog token found', 'jetpack' ) );
2315
		}
2316
2317
		$valid_token = false;
2318
2319
		if ( false === $token_key ) {
2320
			// Use first token.
2321
			$valid_token = $possible_tokens[0];
2322
		} elseif ( self::MAGIC_NORMAL_TOKEN_KEY === $token_key ) {
2323
			// Use first normal token.
2324
			$valid_token = $possible_tokens[0]; // $possible_tokens only contains normal tokens because of earlier check.
2325
		} else {
2326
			// Use the token matching $token_key or false if none.
2327
			// Ensure we check the full key.
2328
			$token_check = rtrim( $token_key, '.' ) . '.';
2329
2330
			foreach ( $possible_tokens as $possible_token ) {
2331
				if ( hash_equals( substr( $possible_token, 0, strlen( $token_check ) ), $token_check ) ) {
2332
					$valid_token = $possible_token;
2333
					break;
2334
				}
2335
			}
2336
		}
2337
2338
		if ( ! $valid_token ) {
2339
			if ( $user_id ) {
2340
				// translators: %d is the user ID.
2341
				return $suppress_errors ? false : new \WP_Error( 'no_valid_token', sprintf( __( 'Invalid token for user %d', 'jetpack' ), $user_id ) );
2342
			} else {
2343
				return $suppress_errors ? false : new \WP_Error( 'no_valid_token', __( 'Invalid blog token', 'jetpack' ) );
2344
			}
2345
		}
2346
2347
		return (object) array(
2348
			'secret'           => $valid_token,
2349
			'external_user_id' => (int) $user_id,
2350
		);
2351
	}
2352
2353
	/**
2354
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths
2355
	 * since it is passed by reference to various methods.
2356
	 * Capture it here so we can verify the signature later.
2357
	 *
2358
	 * @param array $methods an array of available XMLRPC methods.
2359
	 * @return array the same array, since this method doesn't add or remove anything.
2360
	 */
2361
	public function xmlrpc_methods( $methods ) {
2362
		$this->raw_post_data = $GLOBALS['HTTP_RAW_POST_DATA'];
2363
		return $methods;
2364
	}
2365
2366
	/**
2367
	 * Resets the raw post data parameter for testing purposes.
2368
	 */
2369
	public function reset_raw_post_data() {
2370
		$this->raw_post_data = null;
2371
	}
2372
2373
	/**
2374
	 * Registering an additional method.
2375
	 *
2376
	 * @param array $methods an array of available XMLRPC methods.
2377
	 * @return array the amended array in case the method is added.
2378
	 */
2379
	public function public_xmlrpc_methods( $methods ) {
2380
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
2381
			$methods['wp.getOptions'] = array( $this, 'jetpack_get_options' );
2382
		}
2383
		return $methods;
2384
	}
2385
2386
	/**
2387
	 * Handles a getOptions XMLRPC method call.
2388
	 *
2389
	 * @param array $args method call arguments.
2390
	 * @return an amended XMLRPC server options array.
2391
	 */
2392
	public function jetpack_get_options( $args ) {
2393
		global $wp_xmlrpc_server;
2394
2395
		$wp_xmlrpc_server->escape( $args );
2396
2397
		$username = $args[1];
2398
		$password = $args[2];
2399
2400
		$user = $wp_xmlrpc_server->login( $username, $password );
2401
		if ( ! $user ) {
2402
			return $wp_xmlrpc_server->error;
2403
		}
2404
2405
		$options   = array();
2406
		$user_data = $this->get_connected_user_data();
2407
		if ( is_array( $user_data ) ) {
2408
			$options['jetpack_user_id']         = array(
2409
				'desc'     => __( 'The WP.com user ID of the connected user', 'jetpack' ),
2410
				'readonly' => true,
2411
				'value'    => $user_data['ID'],
2412
			);
2413
			$options['jetpack_user_login']      = array(
2414
				'desc'     => __( 'The WP.com username of the connected user', 'jetpack' ),
2415
				'readonly' => true,
2416
				'value'    => $user_data['login'],
2417
			);
2418
			$options['jetpack_user_email']      = array(
2419
				'desc'     => __( 'The WP.com user email of the connected user', 'jetpack' ),
2420
				'readonly' => true,
2421
				'value'    => $user_data['email'],
2422
			);
2423
			$options['jetpack_user_site_count'] = array(
2424
				'desc'     => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
2425
				'readonly' => true,
2426
				'value'    => $user_data['site_count'],
2427
			);
2428
		}
2429
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
2430
		$args                           = stripslashes_deep( $args );
2431
		return $wp_xmlrpc_server->wp_getOptions( $args );
2432
	}
2433
2434
	/**
2435
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
2436
	 *
2437
	 * @param array $options standard Core options.
2438
	 * @return array amended options.
2439
	 */
2440
	public function xmlrpc_options( $options ) {
2441
		$jetpack_client_id = false;
2442
		if ( $this->is_active() ) {
2443
			$jetpack_client_id = \Jetpack_Options::get_option( 'id' );
2444
		}
2445
		$options['jetpack_version'] = array(
2446
			'desc'     => __( 'Jetpack Plugin Version', 'jetpack' ),
2447
			'readonly' => true,
2448
			'value'    => Constants::get_constant( 'JETPACK__VERSION' ),
2449
		);
2450
2451
		$options['jetpack_client_id'] = array(
2452
			'desc'     => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
2453
			'readonly' => true,
2454
			'value'    => $jetpack_client_id,
2455
		);
2456
		return $options;
2457
	}
2458
2459
	/**
2460
	 * Resets the saved authentication state in between testing requests.
2461
	 */
2462
	public function reset_saved_auth_state() {
2463
		$this->xmlrpc_verification = null;
2464
	}
2465
2466
	/**
2467
	 * Sign a user role with the master access token.
2468
	 * If not specified, will default to the current user.
2469
	 *
2470
	 * @access public
2471
	 *
2472
	 * @param string $role    User role.
2473
	 * @param int    $user_id ID of the user.
2474
	 * @return string Signed user role.
2475
	 */
2476
	public function sign_role( $role, $user_id = null ) {
2477
		if ( empty( $user_id ) ) {
2478
			$user_id = (int) get_current_user_id();
2479
		}
2480
2481
		if ( ! $user_id ) {
2482
			return false;
2483
		}
2484
2485
		$token = $this->get_access_token();
2486
		if ( ! $token || is_wp_error( $token ) ) {
2487
			return false;
2488
		}
2489
2490
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2491
	}
2492
2493
	/**
2494
	 * Set the plugin instance.
2495
	 *
2496
	 * @param Plugin $plugin_instance The plugin instance.
2497
	 *
2498
	 * @return $this
2499
	 */
2500
	public function set_plugin_instance( Plugin $plugin_instance ) {
2501
		$this->plugin = $plugin_instance;
2502
2503
		return $this;
2504
	}
2505
2506
	/**
2507
	 * Retrieve the plugin management object.
2508
	 *
2509
	 * @return Plugin
2510
	 */
2511
	public function get_plugin() {
2512
		return $this->plugin;
2513
	}
2514
2515
	/**
2516
	 * Get all connected plugins information, excluding those disconnected by user.
2517
	 * WARNING: the method cannot be called until Plugin_Storage::configure is called, which happens on plugins_loaded
2518
	 * Even if you don't use Jetpack Config, it may be introduced later by other plugins,
2519
	 * so please make sure not to run the method too early in the code.
2520
	 *
2521
	 * @return array|WP_Error
2522
	 */
2523
	public function get_connected_plugins() {
2524
		$maybe_plugins = Plugin_Storage::get_all( true );
2525
2526
		if ( $maybe_plugins instanceof WP_Error ) {
2527
			return $maybe_plugins;
2528
		}
2529
2530
		return $maybe_plugins;
2531
	}
2532
2533
	/**
2534
	 * Force plugin disconnect. After its called, the plugin will not be allowed to use the connection.
2535
	 * Note: this method does not remove any access tokens.
2536
	 *
2537
	 * @return bool
2538
	 */
2539
	public function disable_plugin() {
2540
		if ( ! $this->plugin ) {
2541
			return false;
2542
		}
2543
2544
		return $this->plugin->disable();
2545
	}
2546
2547
	/**
2548
	 * Force plugin reconnect after user-initiated disconnect.
2549
	 * After its called, the plugin will be allowed to use the connection again.
2550
	 * Note: this method does not initialize access tokens.
2551
	 *
2552
	 * @return bool
2553
	 */
2554
	public function enable_plugin() {
2555
		if ( ! $this->plugin ) {
2556
			return false;
2557
		}
2558
2559
		return $this->plugin->enable();
2560
	}
2561
2562
	/**
2563
	 * Whether the plugin is allowed to use the connection, or it's been disconnected by user.
2564
	 * If no plugin slug was passed into the constructor, always returns true.
2565
	 *
2566
	 * @return bool
2567
	 */
2568
	public function is_plugin_enabled() {
2569
		if ( ! $this->plugin ) {
2570
			return true;
2571
		}
2572
2573
		return $this->plugin->is_enabled();
2574
	}
2575
2576
	/**
2577
	 * Perform the API request to refresh the blog token.
2578
	 * Note that we are making this request on behalf of the Jetpack master user,
2579
	 * given they were (most probably) the ones that registered the site at the first place.
2580
	 *
2581
	 * @return WP_Error|bool The result of updating the blog_token option.
2582
	 */
2583
	public static function refresh_blog_token() {
2584
		( new Tracking() )->record_user_event( 'restore_connection_refresh_blog_token' );
2585
2586
		$blog_id = Jetpack_Options::get_option( 'id' );
2587
		if ( ! $blog_id ) {
2588
			return new WP_Error( 'site_not_registered', 'Site not registered.' );
2589
		}
2590
2591
		$url     = sprintf(
2592
			'%s/%s/v%s/%s',
2593
			Constants::get_constant( 'JETPACK__WPCOM_JSON_API_BASE' ),
2594
			'wpcom',
2595
			'2',
2596
			'sites/' . $blog_id . '/jetpack-refresh-blog-token'
2597
		);
2598
		$method  = 'POST';
2599
		$user_id = get_current_user_id();
2600
2601
		$response = Client::remote_request( compact( 'url', 'method', 'user_id' ) );
2602
2603
		if ( is_wp_error( $response ) ) {
2604
			return new WP_Error( 'refresh_blog_token_http_request_failed', $response->get_error_message() );
0 ignored issues
show
The method get_error_message() does not seem to exist on object<WP_Error>.

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

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

Loading history...
2605
		}
2606
2607
		$code   = wp_remote_retrieve_response_code( $response );
2608
		$entity = wp_remote_retrieve_body( $response );
2609
2610
		if ( $entity ) {
2611
			$json = json_decode( $entity );
2612
		} else {
2613
			$json = false;
2614
		}
2615
2616 View Code Duplication
		if ( 200 !== $code ) {
2617
			if ( empty( $json->code ) ) {
2618
				return new WP_Error( 'unknown', '', $code );
2619
			}
2620
2621
			/* translators: Error description string. */
2622
			$error_description = isset( $json->message ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->message ) : '';
2623
2624
			return new WP_Error( (string) $json->code, $error_description, $code );
2625
		}
2626
2627
		if ( empty( $json->jetpack_secret ) || ! is_scalar( $json->jetpack_secret ) ) {
2628
			return new WP_Error( 'jetpack_secret', '', $code );
2629
		}
2630
2631
		return Jetpack_Options::update_option( 'blog_token', (string) $json->jetpack_secret );
2632
	}
2633
2634
	/**
2635
	 * Disconnect the user from WP.com, and initiate the reconnect process.
2636
	 *
2637
	 * @return bool
2638
	 */
2639
	public static function refresh_user_token() {
2640
		( new Tracking() )->record_user_event( 'restore_connection_refresh_user_token' );
2641
2642
		self::disconnect_user( null, true );
2643
2644
		return true;
2645
	}
2646
2647
	/**
2648
	 * Fetches a signed token.
2649
	 *
2650
	 * @param object $token the token.
2651
	 * @return WP_Error|string a signed token
2652
	 */
2653
	public function get_signed_token( $token ) {
2654
		if ( ! isset( $token->secret ) || empty( $token->secret ) ) {
2655
			return new WP_Error( 'invalid_token' );
2656
		}
2657
2658
		list( $token_key, $token_secret ) = explode( '.', $token->secret );
2659
2660
		$token_key = sprintf(
2661
			'%s:%d:%d',
2662
			$token_key,
2663
			Constants::get_constant( 'JETPACK__API_VERSION' ),
2664
			$token->external_user_id
2665
		);
2666
2667
		$timestamp = time();
2668
2669 View Code Duplication
		if ( function_exists( 'wp_generate_password' ) ) {
2670
			$nonce = wp_generate_password( 10, false );
2671
		} else {
2672
			$nonce = substr( sha1( wp_rand( 0, 1000000 ) ), 0, 10 );
2673
		}
2674
2675
		$normalized_request_string = join(
2676
			"\n",
2677
			array(
2678
				$token_key,
2679
				$timestamp,
2680
				$nonce,
2681
			)
2682
		) . "\n";
2683
2684
		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2685
		$signature = base64_encode( hash_hmac( 'sha1', $normalized_request_string, $token_secret, true ) );
2686
2687
		$auth = array(
2688
			'token'     => $token_key,
2689
			'timestamp' => $timestamp,
2690
			'nonce'     => $nonce,
2691
			'signature' => $signature,
2692
		);
2693
2694
		$header_pieces = array();
2695
		foreach ( $auth as $key => $value ) {
2696
			$header_pieces[] = sprintf( '%s="%s"', $key, $value );
2697
		}
2698
2699
		return join( ' ', $header_pieces );
2700
	}
2701
2702
	/**
2703
	 * If connection is active, add the list of plugins using connection to the heartbeat (except Jetpack itself)
2704
	 *
2705
	 * @param array $stats The Heartbeat stats array.
2706
	 * @return array $stats
2707
	 */
2708
	public function add_stats_to_heartbeat( $stats ) {
2709
2710
		if ( ! $this->is_active() ) {
2711
			return $stats;
2712
		}
2713
2714
		$active_plugins_using_connection = Plugin_Storage::get_all();
2715
		foreach ( array_keys( $active_plugins_using_connection ) as $plugin_slug ) {
2716
			if ( 'jetpack' !== $plugin_slug ) {
2717
				$stats_group             = isset( $active_plugins_using_connection['jetpack'] ) ? 'combined-connection' : 'standalone-connection';
2718
				$stats[ $stats_group ][] = $plugin_slug;
2719
			}
2720
		}
2721
		return $stats;
2722
	}
2723
2724
}
2725