Completed
Push — add/sync-action ( 45ef1e...ba7a9e )
by
unknown
65:55 queued 56:50
created

Jetpack_SSO::clear_wpcom_profile_cookies()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 21
Code Lines 15

Duplication

Lines 18
Ratio 85.71 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 15
c 1
b 0
f 1
nc 4
nop 0
dl 18
loc 21
rs 9.3142
1
<?php
2
3
/**
4
 * Module Name: Single Sign On
5
 * Module Description: Secure user authentication with WordPress.com.
6
 * Jumpstart Description: Lets you log in to all your Jetpack-enabled sites with one click using your WordPress.com account.
7
 * Sort Order: 30
8
 * Recommendation Order: 5
9
 * First Introduced: 2.6
10
 * Requires Connection: Yes
11
 * Auto Activate: No
12
 * Module Tags: Developers
13
 * Feature: Security, Jumpstart
14
 * Additional Search Queries: sso, single sign on, login, log in
15
 */
16
17
class Jetpack_SSO {
18
	static $instance = null;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $instance.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
19
20
	private function __construct() {
21
22
		self::$instance = $this;
23
24
		add_action( 'admin_init',             array( $this, 'maybe_authorize_user_after_sso' ), 1 );
25
		add_action( 'admin_init',             array( $this, 'register_settings' ) );
26
		add_action( 'login_init',             array( $this, 'login_init' ) );
27
		add_action( 'delete_user',            array( $this, 'delete_connection_for_user' ) );
28
		add_filter( 'jetpack_xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
29
		add_action( 'init',                   array( $this, 'maybe_logout_user' ), 5 );
30
		add_action( 'jetpack_modules_loaded', array( $this, 'module_configure_button' ) );
31
		add_action( 'admin_enqueue_scripts',  array( $this, 'admin_enqueue_scripts' ) );
32
		add_action( 'login_form_logout',      array( $this, 'store_wpcom_profile_cookies_on_logout' ) );
33
		add_action( 'wp_login',               array( 'Jetpack_SSO', 'clear_wpcom_profile_cookies' ) );
34
		add_action( 'jetpack_unlinked_user',  array( $this, 'delete_connection_for_user') );
35
36
		// Adding this action so that on login_init, the action won't be sanitized out of the $action global.
37
		add_action( 'login_form_jetpack-sso', '__return_true' );
38
39
		if (
40
			$this->should_hide_login_form() &&
41
			/**
42
			 * Filter the display of the disclaimer message appearing when default WordPress login form is disabled.
43
			 *
44
			 * @module sso
45
			 *
46
			 * @since 2.8.0
47
			 *
48
			 * @param bool true Should the disclaimer be displayed. Default to true.
49
			 */
50
			apply_filters( 'jetpack_sso_display_disclaimer', true )
51
		) {
52
			add_action( 'login_message', array( $this, 'msg_login_by_jetpack' ) );
53
		}
54
	}
55
56
	/**
57
	 * Returns the single instance of the Jetpack_SSO object
58
	 *
59
	 * @since 2.8
60
	 * @return Jetpack_SSO
61
	 **/
62
	public static function get_instance() {
63
		if ( ! is_null( self::$instance ) ) {
64
			return self::$instance;
65
		}
66
67
		return self::$instance = new Jetpack_SSO;
68
	}
69
70
	/**
71
	 * Add configure button and functionality to the module card on the Jetpack screen
72
	 **/
73
	public static function module_configure_button() {
74
		Jetpack::enable_module_configurable( __FILE__ );
75
		Jetpack::module_configuration_load( __FILE__, array( __CLASS__, 'module_configuration_load' ) );
76
		Jetpack::module_configuration_head( __FILE__, array( __CLASS__, 'module_configuration_head' ) );
77
		Jetpack::module_configuration_screen( __FILE__, array( __CLASS__, 'module_configuration_screen' ) );
78
	}
79
80
	public static function module_configuration_load() {}
81
82
	public static function module_configuration_head() {}
83
84
	public static function module_configuration_screen() {
85
		?>
86
		<form method="post" action="options.php">
87
			<?php settings_fields( 'jetpack-sso' ); ?>
88
			<?php do_settings_sections( 'jetpack-sso' ); ?>
89
			<?php submit_button(); ?>
90
		</form>
91
		<?php
92
	}
93
94
	/**
95
	 * If jetpack_force_logout == 1 in current user meta the user will be forced
96
	 * to logout and reauthenticate with the site.
97
	 **/
98
	public function maybe_logout_user() {
99
		global $current_user;
100
101
		if ( 1 == $current_user->jetpack_force_logout ) {
102
			delete_user_meta( $current_user->ID, 'jetpack_force_logout' );
103
			self::delete_connection_for_user( $current_user->ID );
104
			wp_logout();
105
			wp_safe_redirect( wp_login_url() );
106
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method maybe_logout_user() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
107
		}
108
	}
109
110
111
	/**
112
	 * Adds additional methods the WordPress xmlrpc API for handling SSO specific features
113
	 *
114
	 * @param array $methods
115
	 * @return array
116
	 **/
117
	public function xmlrpc_methods( $methods ) {
118
		$methods['jetpack.userDisconnect'] = array( $this, 'xmlrpc_user_disconnect' );
119
		return $methods;
120
	}
121
122
	/**
123
	 * Marks a user's profile for disconnect from WordPress.com and forces a logout
124
	 * the next time the user visits the site.
125
	 **/
126
	public function xmlrpc_user_disconnect( $user_id ) {
127
		$user_query = new WP_User_Query(
128
			array(
129
				'meta_key' => 'wpcom_user_id',
130
				'meta_value' => $user_id,
131
			)
132
		);
133
		$user = $user_query->get_results();
134
		$user = $user[0];
135
136
		if ( $user instanceof WP_User ) {
0 ignored issues
show
Bug introduced by
The class WP_User does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
137
			$user = wp_set_current_user( $user->ID );
138
			update_user_meta( $user->ID, 'jetpack_force_logout', '1' );
139
			self::delete_connection_for_user( $user->ID );
140
			return true;
141
		}
142
		return false;
143
	}
144
145
	/**
146
	 * Enqueues scripts and styles necessary for SSO login.
147
	 */
148
	public function login_enqueue_scripts() {
149
		global $action;
150
151
		if ( ! in_array( $action, array( 'jetpack-sso', 'login' ) ) ) {
152
			return;
153
		}
154
155
		wp_enqueue_style( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login.css', JETPACK__PLUGIN_FILE ), array( 'login', 'genericons' ), JETPACK__VERSION );
156
		wp_enqueue_script( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login.js', JETPACK__PLUGIN_FILE ), array( 'jquery' ), JETPACK__VERSION );
157
	}
158
159
	/**
160
	 * Enqueue styles neceessary for Jetpack SSO on users' profiles
161
	 */
162
	public function admin_enqueue_scripts() {
163
		$screen = get_current_screen();
164
165
		if ( empty( $screen ) || ! in_array( $screen->base, array( 'edit-user', 'profile' ) ) ) {
166
			return;
167
		}
168
169
		wp_enqueue_style( 'jetpack-sso-profile', plugins_url( 'modules/sso/jetpack-sso-profile.css', JETPACK__PLUGIN_FILE ), array( 'genericons' ), JETPACK__VERSION );
170
	}
171
172
	/**
173
	 * Adds Jetpack SSO classes to login body
174
	 *
175
	 * @param  array $classes Array of classes to add to body tag
176
	 * @return array          Array of classes to add to body tag
177
	 */
178
	public function login_body_class( $classes ) {
179
		global $action;
180
181
		if ( ! in_array( $action, array( 'jetpack-sso', 'login' ) ) ) {
182
			return $classes;
183
		}
184
185
		// If jetpack-sso-default-form, show the default login form.
186
		if ( isset( $_GET['jetpack-sso-default-form'] ) && 1 == $_GET['jetpack-sso-default-form'] ) {
187
			return $classes;
188
		}
189
190
		$classes[] = 'jetpack-sso-body';
191
		return $classes;
192
	}
193
194
	/**
195
	 * Adds settings fields to Settings > General > Single Sign On that allows users to
196
	 * turn off the login form on wp-login.php
197
	 *
198
	 * @since 2.7
199
	 **/
200
	public function register_settings() {
201
202
		add_settings_section(
203
			'jetpack_sso_settings',
204
			__( 'Single Sign On' , 'jetpack' ),
205
			'__return_false',
206
			'jetpack-sso'
207
		);
208
209
		/*
210
		 * Settings > General > Single Sign On
211
		 * Require two step authentication
212
		 */
213
		register_setting(
214
			'jetpack-sso',
215
			'jetpack_sso_require_two_step',
216
			array( $this, 'validate_jetpack_sso_require_two_step' )
217
		);
218
219
		add_settings_field(
220
			'jetpack_sso_require_two_step',
221
			'', // __( 'Require Two-Step Authentication' , 'jetpack' ),
222
			array( $this, 'render_require_two_step' ),
223
			'jetpack-sso',
224
			'jetpack_sso_settings'
225
		);
226
227
		/*
228
		 * Settings > General > Single Sign On
229
		 */
230
		register_setting(
231
			'jetpack-sso',
232
			'jetpack_sso_match_by_email',
233
			array( $this, 'validate_jetpack_sso_match_by_email' )
234
		);
235
236
		add_settings_field(
237
			'jetpack_sso_match_by_email',
238
			'', // __( 'Match by Email' , 'jetpack' ),
239
			array( $this, 'render_match_by_email' ),
240
			'jetpack-sso',
241
			'jetpack_sso_settings'
242
		);
243
	}
244
245
	/**
246
	 * Builds the display for the checkbox allowing user to require two step
247
	 * auth be enabled on WordPress.com accounts before login. Displays in Settings > General
248
	 *
249
	 * @since 2.7
250
	 **/
251
	public function render_require_two_step() {
252
		/** This filter is documented in modules/sso.php */
253
		$require_two_step = ( 1 == apply_filters( 'jetpack_sso_require_two_step', get_option( 'jetpack_sso_require_two_step' ) ) );
254
		$disabled = $require_two_step ? ' disabled="disabled"' : '';
255
		echo '<label>';
256
		echo '<input type="checkbox" name="jetpack_sso_require_two_step" ' . checked( $require_two_step, true, false ) . "$disabled>";
257
		esc_html_e( 'Require Two-Step Authentication' , 'jetpack' );
258
		echo '</label>';
259
	}
260
261
	/**
262
	 * Validate the require  two step checkbox in Settings > General
263
	 *
264
	 * @since 2.7
265
	 * @return boolean
266
	 **/
267
	public function validate_jetpack_sso_require_two_step( $input ) {
268
		return ( ! empty( $input ) ) ? 1 : 0;
269
	}
270
271
	/**
272
	 * Builds the display for the checkbox allowing the user to allow matching logins by email
273
	 * Displays in Settings > General
274
	 *
275
	 * @since 2.9
276
	 **/
277
	public function render_match_by_email() {
278
		$match_by_email = 1 == $this->match_by_email();
279
		$disabled = $match_by_email ? ' disabled="disabled"' : '';
280
		echo '<label>';
281
		echo '<input type="checkbox" name="jetpack_sso_match_by_email"' . checked( $match_by_email, true, false ) . "$disabled>";
282
		esc_html_e( 'Match by Email', 'jetpack' );
283
		echo '</label>';
284
	}
285
286
	/**
287
	 * Validate the match by email check in Settings > General
288
	 *
289
	 * @since 2.9
290
	 * @return boolean
291
	 **/
292
	public function validate_jetpack_sso_match_by_email( $input ) {
293
		return ( ! empty( $input ) ) ? 1 : 0;
294
	}
295
296
	/**
297
	 * Checks to determine if the user wants to login on wp-login
298
	 *
299
	 * This function mostly exists to cover the exceptions to login
300
	 * that may exist as other parameters to $_GET[action] as $_GET[action]
301
	 * does not have to exist. By default WordPress assumes login if an action
302
	 * is not set, however this may not be true, as in the case of logout
303
	 * where $_GET[loggedout] is instead set
304
	 *
305
	 * @return boolean
306
	 **/
307
	private function wants_to_login() {
308
		$wants_to_login = false;
309
310
		// Cover default WordPress behavior
311
		$action = isset( $_REQUEST['action'] ) ? $_REQUEST['action'] : 'login';
312
313
		// And now the exceptions
314
		$action = isset( $_GET['loggedout'] ) ? 'loggedout' : $action;
315
316
		if ( 'login' == $action ) {
317
			$wants_to_login = true;
318
		}
319
320
		return $wants_to_login;
321
	}
322
323
	private function bypass_login_forward_wpcom() {
324
		/**
325
		 * Redirect the site's log in form to WordPress.com's log in form.
326
		 *
327
		 * @module sso
328
		 *
329
		 * @since 3.1.0
330
		 *
331
		 * @param bool false Should the site's log in form be automatically forwarded to WordPress.com's log in form.
332
		 */
333
		return apply_filters( 'jetpack_sso_bypass_login_forward_wpcom', false );
334
	}
335
336
	function login_init() {
337
		global $action;
338
339
		/**
340
		 * If the user is attempting to logout AND the auto-forward to WordPress.com
341
		 * login is set then we need to ensure we do not auto-forward the user and get
342
		 * them stuck in an infinite logout loop.
343
		 */
344
		if ( isset( $_GET['loggedout'] ) && $this->bypass_login_forward_wpcom() ) {
345
			add_filter( 'jetpack_remove_login_form', '__return_true' );
346
		}
347
348
		/**
349
		 * Check to see if the site admin wants to automagically forward the user
350
		 * to the WordPress.com login page AND  that the request to wp-login.php
351
		 * is not something other than login (Like logout!)
352
		 */
353
		if (
354
			$this->wants_to_login()
355
			&& $this->bypass_login_forward_wpcom()
356
		) {
357
			add_filter( 'allowed_redirect_hosts', array( $this, 'allowed_redirect_hosts' ) );
358
			$this->maybe_save_cookie_redirect();
359
			$reauth = ! empty( $_GET['reauth'] );
360
			wp_safe_redirect( $this->get_sso_url_or_die( $reauth ) );
361
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method login_init() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
362
		}
363
364
		if ( 'login' === $action ) {
365
			$this->display_sso_login_form();
366
		} elseif ( 'jetpack-sso' === $action ) {
367
			if ( isset( $_GET['result'], $_GET['user_id'], $_GET['sso_nonce'] ) && 'success' == $_GET['result'] ) {
368
				$this->handle_login();
369
				$this->display_sso_login_form();
370
			} else {
371
				if ( Jetpack::check_identity_crisis() ) {
372
					wp_die( __( "Error: This site's Jetpack connection is currently experiencing problems.", 'jetpack' ) );
373
				} else {
374
					$this->maybe_save_cookie_redirect();
375
					// Is it wiser to just use wp_redirect than do this runaround to wp_safe_redirect?
376
					add_filter( 'allowed_redirect_hosts', array( $this, 'allowed_redirect_hosts' ) );
377
					$reauth = ! empty( $_GET['reauth'] );
378
					wp_safe_redirect( $this->get_sso_url_or_die( $reauth ) );
379
					exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method login_init() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
380
				}
381
			}
382
		}
383
	}
384
385
	/**
386
	 * Ensures that we can get a nonce from WordPress.com via XML-RPC before setting
387
	 * up the hooks required to display the SSO form.
388
	 */
389
	public function display_sso_login_form() {
390
		$sso_nonce = self::request_initial_nonce();
391
		if ( is_wp_error( $sso_nonce ) ) {
392
			return;
393
		}
394
395
		add_action( 'login_form',            array( $this, 'login_form' ) );
396
		add_filter( 'login_body_class',      array( $this, 'login_body_class' ) );
397
		add_action( 'login_enqueue_scripts', array( $this, 'login_enqueue_scripts' ) );
398
	}
399
400
	/**
401
	 * Conditionally save the redirect_to url as a cookie.
402
	 */
403
	public static function maybe_save_cookie_redirect() {
404
		if ( headers_sent() ) {
405
			return new WP_Error( 'headers_sent', __( 'Cannot deal with cookie redirects, as headers are already sent.', 'jetpack' ) );
406
		}
407
408
		if ( ! empty( $_GET['redirect_to'] ) ) {
409
			// If we have something to redirect to
410
			$url = esc_url_raw( $_GET['redirect_to'] );
411
			setcookie( 'jetpack_sso_redirect_to', $url, time() + HOUR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, false, true );
412
413
		} elseif ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
414
			// Otherwise, if it's already set, purge it.
415
			setcookie( 'jetpack_sso_redirect_to', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
416
		}
417
418
		if ( ! empty( $_GET['rememberme'] ) ) {
419
			setcookie( 'jetpack_sso_remember_me', '1', time() + HOUR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, false, true );
420
		} elseif ( ! empty( $_COOKIE['jetpack_sso_remember_me'] ) ) {
421
			setcookie( 'jetpack_sso_remember_me', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
422
		}
423
	}
424
425
	/**
426
	 * Determine if the login form should be hidden or not
427
	 *
428
	 * Method is private only because it is only used in this class so far.
429
	 * Feel free to change it later
430
	 *
431
	 * @return bool
432
	 **/
433
	private function should_hide_login_form() {
434
		/**
435
		 * Remove the default log in form, only leave the WordPress.com log in button.
436
		 *
437
		 * @module sso
438
		 *
439
		 * @since 3.1.0
440
		 *
441
		 * @param bool get_option( 'jetpack_sso_remove_login_form', false ) Should the default log in form be removed. Default to false.
442
		 */
443
		return apply_filters( 'jetpack_remove_login_form', get_option( 'jetpack_sso_remove_login_form', false ) );
444
	}
445
446
	/**
447
	 * Outputs the Jetpack SSO button and description as well as the toggle link
448
	 * for switching between Jetpack SSO and default login.
449
	 */
450
	function login_form() {
451
		$site_name = get_bloginfo( 'name' );
452
		if ( ! $site_name ) {
453
			$site_name = get_bloginfo( 'url' );
454
		}
455
456
		$display_name = ! empty( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] )
457
			? $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ]
458
			: false;
459
		$gravatar = ! empty( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] )
460
			? $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ]
461
			: false;
462
463
		?>
464
		<div id="jetpack-sso-wrap">
465
			<?php if ( $display_name && $gravatar ) : ?>
466
				<div id="jetpack-sso-wrap__user">
467
					<img width="72" height="72" src="<?php echo esc_html( $gravatar ); ?>" />
468
469
					<h2>
470
						<?php
471
							echo wp_kses(
472
								sprintf( __( 'Log in as <span>%s</span>', 'jetpack' ), esc_html( $display_name ) ),
473
								array( 'span' => true )
474
							);
475
						?>
476
					</h2>
477
				</div>
478
479
			<?php endif; ?>
480
481
482
			<div id="jetpack-sso-wrap__action">
483
				<?php echo $this->build_sso_button( array(), 'is_primary' ); ?>
0 ignored issues
show
Documentation introduced by
'is_primary' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
484
485
				<?php if ( $display_name && $gravatar ) : ?>
486
					<a class="jetpack-sso-wrap__reauth" href="<?php echo $this->build_sso_button_url( array( 'reauth' => '1' ) ); ?>">
487
						<?php esc_html_e( 'Log in as a different WordPress.com user', 'jetpack' ); ?>
488
					</a>
489
				<?php else : ?>
490
					<p>
491
						<?php
492
							echo esc_html(
493
								sprintf(
494
									__( 'You can now save time spent logging in by connecting your WordPress.com account to %s.', 'jetpack' ),
495
									esc_html( $site_name )
496
								)
497
							);
498
						?>
499
					</p>
500
				<?php endif; ?>
501
			</div>
502
503
			<?php if ( ! $this->should_hide_login_form() ) : ?>
504
				<div class="jetpack-sso-or">
505
					<span><?php esc_html_e( 'Or', 'jetpack' ); ?></span>
506
				</div>
507
508
				<a href="<?php echo add_query_arg( 'jetpack-sso-default-form', '1' ); ?>" class="jetpack-sso-toggle wpcom">
509
					<?php
510
						esc_html_e( 'Log in with username and password', 'jetpack' )
511
					?>
512
				</a>
513
514
				<a href="<?php echo add_query_arg( 'jetpack-sso-default-form', '0' ); ?>" class="jetpack-sso-toggle default">
515
					<?php
516
						esc_html_e( 'Log in with WordPress.com', 'jetpack' )
517
					?>
518
				</a>
519
			<?php endif; ?>
520
		</div>
521
		<?php
522
	}
523
524
	/**
525
	 * Clear the cookies that store the profile information for the last
526
	 * WPCOM user to connect.
527
	 */
528
	static function clear_wpcom_profile_cookies() {
529 View Code Duplication
		if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] ) ) {
530
			setcookie(
531
				'jetpack_sso_wpcom_name_' . COOKIEHASH,
532
				' ',
533
				time() - YEAR_IN_SECONDS,
534
				COOKIEPATH,
535
				COOKIE_DOMAIN
536
			);
537
		}
538
539 View Code Duplication
		if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] ) ) {
540
			setcookie(
541
				'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
542
				' ',
543
				time() - YEAR_IN_SECONDS,
544
				COOKIEPATH,
545
				COOKIE_DOMAIN
546
			);
547
		}
548
	}
549
550
	static function delete_connection_for_user( $user_id ) {
551
		if ( ! $wpcom_user_id = get_user_meta( $user_id, 'wpcom_user_id', true ) ) {
552
			return;
553
		}
554
		Jetpack::load_xml_rpc_client();
555
		$xml = new Jetpack_IXR_Client( array(
556
			'wpcom_user_id' => $user_id,
557
		) );
558
		$xml->query( 'jetpack.sso.removeUser', $wpcom_user_id );
559
560
		if ( $xml->isError() ) {
561
			return false;
562
		}
563
564
		// Clean up local data stored for SSO
565
		delete_user_meta( $user_id, 'wpcom_user_id' );
566
		delete_user_meta( $user_id, 'wpcom_user_data'  );
567
		self::clear_wpcom_profile_cookies();
568
569
		return $xml->getResponse();
570
	}
571
572 View Code Duplication
	static function request_initial_nonce() {
573
		Jetpack::load_xml_rpc_client();
574
		$xml = new Jetpack_IXR_Client( array(
575
			'user_id' => get_current_user_id(),
576
		) );
577
		$xml->query( 'jetpack.sso.requestNonce' );
578
579
		if ( $xml->isError() ) {
580
			return new WP_Error( $xml->getErrorCode(), $xml->getErrorMessage() );
581
		}
582
583
		return $xml->getResponse();
584
	}
585
586
	/**
587
	 * The function that actually handles the login!
588
	 */
589
	function handle_login() {
590
		$wpcom_nonce   = sanitize_key( $_GET['sso_nonce'] );
591
		$wpcom_user_id = (int) $_GET['user_id'];
592
593
		Jetpack::load_xml_rpc_client();
594
		$xml = new Jetpack_IXR_Client( array(
595
			'user_id' => get_current_user_id(),
596
		) );
597
		$xml->query( 'jetpack.sso.validateResult', $wpcom_nonce, $wpcom_user_id );
598
599
		if ( $xml->isError() ) {
600
			wp_die( sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() ) );
601
		}
602
603
		$user_data = $xml->getResponse();
604
605
		if ( empty( $user_data ) ) {
606
			wp_die( __( 'Error, invalid response data.', 'jetpack' ) );
607
		}
608
609
		$user_data = (object) $user_data;
610
		$user = null;
611
612
		/**
613
		 * Fires before Jetpack's SSO modifies the log in form.
614
		 *
615
		 * @module sso
616
		 *
617
		 * @since 2.6.0
618
		 *
619
		 * @param object $user_data User login information.
620
		 */
621
		do_action( 'jetpack_sso_pre_handle_login', $user_data );
622
623
		/**
624
		 * Is it required to have 2-step authentication enabled on WordPress.com to use SSO?
625
		 *
626
		 * @module sso
627
		 *
628
		 * @since 2.8.0
629
		 *
630
		 * @param bool get_option( 'jetpack_sso_require_two_step' ) Does SSO require 2-step authentication?
631
		 */
632
		$require_two_step = apply_filters( 'jetpack_sso_require_two_step', get_option( 'jetpack_sso_require_two_step' ) );
633
		if ( $require_two_step && 0 == (int) $user_data->two_step_enabled ) {
634
			$this->user_data = $user_data;
0 ignored issues
show
Bug introduced by
The property user_data does not exist. Did you maybe forget to declare it?

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

class MyClass { }

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

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

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
635
			/** This filter is documented in core/src/wp-includes/pluggable.php */
636
			do_action( 'wp_login_failed', $user_data->login );
637
			add_action( 'login_message', array( $this, 'error_msg_enable_two_step' ) );
638
			return;
639
		}
640
641
		if ( empty( $user ) && isset( $user_data->external_user_id ) ) {
642
			$user = get_user_by( 'id', intval( $user_data->external_user_id ) );
643
			if ( $user ) {
644
				update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
645
			}
646
		}
647
648
		// If we don't have one by wpcom_user_id, try by the email?
649
		if ( empty( $user ) && self::match_by_email() ) {
650
			$user = get_user_by( 'email', $user_data->email );
651
			if ( $user ) {
652
				update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
653
			}
654
		}
655
656
		// If we've still got nothing, create the user.
657
		if ( empty( $user ) && ( get_option( 'users_can_register' ) || self::new_user_override() ) ) {
658
			// If not matching by email we still need to verify the email does not exist
659
			// or this blows up
660
			/**
661
			 * If match_by_email is true, we know the email doesn't exist, as it would have
662
			 * been found in the first pass.  If get_user_by( 'email' ) doesn't find the
663
			 * user, then we know that email is unused, so it's safe to add.
664
			 */
665
			if ( self::match_by_email() || ! get_user_by( 'email', $user_data->email ) ) {
666
				$username = $user_data->login;
667
668
				if ( username_exists( $username ) ) {
669
					$username = $user_data->login . '_' . $user_data->ID;
670
				}
671
672
				$tries = 0;
673
				while ( username_exists( $username ) ) {
674
					$username = $user_data->login . '_' . $user_data->ID . '_' . mt_rand();
675
					if ( $tries++ >= 5 ) {
676
						wp_die( __( "Error: Couldn't create suitable username.", 'jetpack' ) );
677
					}
678
				}
679
680
				$password = wp_generate_password( 20 );
681
				$user_id  = wp_create_user( $username, $password, $user_data->email );
682
				$user     = get_userdata( $user_id );
683
684
				$user->display_name = $user_data->display_name;
685
				$user->first_name   = $user_data->first_name;
686
				$user->last_name    = $user_data->last_name;
687
				$user->url          = $user_data->url;
688
				$user->description  = $user_data->description;
689
				wp_update_user( $user );
690
691
				update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
692
			} else {
693
				$this->user_data = $user_data;
694
				// do_action( 'wp_login_failed', $user_data->login );
695
				add_action( 'login_message', array( $this, 'error_msg_email_already_exists' ) );
696
				return;
697
			}
698
		}
699
700
		/**
701
		 * Fires after we got login information from WordPress.com.
702
		 *
703
		 * @module sso
704
		 *
705
		 * @since 2.6.0
706
		 *
707
		 * @param array $user WordPress.com User information.
708
		 * @param object $user_data User Login information.
709
		 */
710
		do_action( 'jetpack_sso_handle_login', $user, $user_data );
711
712
		if ( $user ) {
713
			// Cache the user's details, so we can present it back to them on their user screen
714
			update_user_meta( $user->ID, 'wpcom_user_data', $user_data );
715
716
			$remember = false;
717 View Code Duplication
			if ( ! empty( $_COOKIE['jetpack_sso_remember_me'] ) ) {
718
				$remember = true;
719
				// And then purge it
720
				setcookie( 'jetpack_sso_remember_me', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
721
			}
722
			/**
723
			 * Filter the remember me value.
724
			 *
725
			 * @module sso
726
			 *
727
			 * @since 2.8.0
728
			 *
729
			 * @param bool $remember Is the remember me option checked?
730
			 */
731
			$remember = apply_filters( 'jetpack_remember_login', $remember );
732
			wp_set_auth_cookie( $user->ID, $remember );
733
734
			/** This filter is documented in core/src/wp-includes/user.php */
735
			do_action( 'wp_login', $user->user_login, $user );
736
737
			$_request_redirect_to = isset( $_REQUEST['redirect_to'] ) ? esc_url_raw( $_REQUEST['redirect_to'] ) : '';
738
			$redirect_to = user_can( $user, 'edit_posts' ) ? admin_url() : self::profile_page_url();
739
740
			// If we have a saved redirect to request in a cookie
741 View Code Duplication
			if ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
742
				// Set that as the requested redirect to
743
				$redirect_to = $_request_redirect_to = esc_url_raw( $_COOKIE['jetpack_sso_redirect_to'] );
744
				// And then purge it
745
				setcookie( 'jetpack_sso_redirect_to', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
746
			}
747
748
			if ( ! Jetpack::is_user_connected( $user->ID ) ) {
749
				$calypso_env = ! empty( $_GET['calypso_env'] )
750
					? sanitize_key( $_GET['calypso_env'] )
751
					: '';
752
753
				wp_safe_redirect(
754
					add_query_arg(
755
						array(
756
							'redirect_to'               => $redirect_to,
757
							'request_redirect_to'       => $_request_redirect_to,
758
							'calypso_env'               => $calypso_env,
759
							'jetpack-sso-auth-redirect' => '1',
760
						),
761
						admin_url()
762
					)
763
				);
764
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method handle_login() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
765
			}
766
767
			wp_safe_redirect(
768
				/** This filter is documented in core/src/wp-login.php */
769
				apply_filters( 'login_redirect', $redirect_to, $_request_redirect_to, $user )
770
			);
771
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method handle_login() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
772
		}
773
774
		$this->user_data = $user_data;
775
		/** This filter is documented in core/src/wp-includes/pluggable.php */
776
		do_action( 'wp_login_failed', $user_data->login );
777
		add_action( 'login_message', array( $this, 'cant_find_user' ) );
778
	}
779
780
	static function profile_page_url() {
781
		return admin_url( 'profile.php' );
782
	}
783
784
	static function match_by_email() {
785
		$match_by_email = ( 1 == get_option( 'jetpack_sso_match_by_email', true ) ) ? true: false;
786
		$match_by_email = defined( 'WPCC_MATCH_BY_EMAIL' ) ? WPCC_MATCH_BY_EMAIL : $match_by_email;
787
788
		/**
789
		 * Link the local account to an account on WordPress.com using the same email address.
790
		 *
791
		 * @module sso
792
		 *
793
		 * @since 2.6.0
794
		 *
795
		 * @param bool $match_by_email Should we link the local account to an account on WordPress.com using the same email address. Default to false.
796
		 */
797
		return apply_filters( 'jetpack_sso_match_by_email', $match_by_email );
798
	}
799
800
	static function new_user_override() {
801
		$new_user_override = defined( 'WPCC_NEW_USER_OVERRIDE' ) ? WPCC_NEW_USER_OVERRIDE : false;
802
803
		/**
804
		 * Allow users to register on your site with a WordPress.com account, even though you disallow normal registrations.
805
		 *
806
		 * @module sso
807
		 *
808
		 * @since 2.6.0
809
		 *
810
		 * @param bool $new_user_override Allow users to register on your site with a WordPress.com account. Default to false.
811
		 */
812
		return apply_filters( 'jetpack_sso_new_user_override', $new_user_override );
813
	}
814
815
	function allowed_redirect_hosts( $hosts ) {
816
		if ( empty( $hosts ) ) {
817
			$hosts = array();
818
		}
819
		$hosts[] = 'wordpress.com';
820
		$hosts[] = 'jetpack.wordpress.com';
821
822
		return array_unique( $hosts );
823
	}
824
825
	/**
826
	 * Builds the "Login to WordPress.com" button that is displayed on the login page as well as user profile page.
827
	 *
828
	 * @param  array   $args       An array of arguments to add to the SSO URL.
829
	 * @param  boolean $is_primary Should the button have the `button-primary` class?
830
	 * @return string              Returns the HTML markup for the button.
831
	 */
832
	function build_sso_button( $args = array(), $is_primary = false ) {
833
		$url = $this->build_sso_button_url( $args );
834
		$classes = $is_primary
835
			? 'jetpack-sso button button-primary'
836
			: 'jetpack-sso button';
837
838
		return sprintf(
839
			'<a href="%1$s" class="%2$s">%3$s</a>',
840
			esc_url( $url ),
841
			$classes,
842
			esc_html__( 'Log in with WordPress.com', 'jetpack' )
843
		);
844
	}
845
846
	/**
847
	 * Builds a URL with `jetpack-sso` action and option args which is used to setup SSO.
848
	 *
849
	 * @param  array  $args An array of arguments to add to the SSO URL.
850
	 * @return string       The URL used for SSO.
851
	 */
852
	function build_sso_button_url( $args = array() ) {
853
		$defaults = array(
854
			'action'  => 'jetpack-sso',
855
		);
856
857
		$args = wp_parse_args( $args, $defaults );
858
859
		if ( ! empty( $_GET['redirect_to'] ) ) {
860
			$args['redirect_to'] = esc_url_raw( $_GET['redirect_to'] );
861
		}
862
863
		return add_query_arg( $args, wp_login_url() );
864
	}
865
866
	/**
867
	 * Retrieves a WordPress.com SSO URL with appropriate query parameters or dies.
868
	 *
869
	 * @param  boolean  $reauth  Should the user be forced to reauthenticate on WordPress.com?
870
	 * @param  array    $args    Optional query parameters.
871
	 * @return string            The WordPress.com SSO URL.
872
	 */
873
	function get_sso_url_or_die( $reauth = false, $args = array() ) {
874
		if ( empty( $reauth ) ) {
875
			$sso_redirect = $this->build_sso_url( $args );
876
		} else {
877
			self::clear_wpcom_profile_cookies();
878
			$sso_redirect = $this->build_reauth_and_sso_url( $args );
879
		}
880
881
		// If there was an error retrieving the SSO URL, then error.
882
		if ( is_wp_error( $sso_redirect ) ) {
883
			wp_die( sprintf( '%s: %s', $sso_redirect->get_error_code(), $sso_redirect->get_error_message() ) );
0 ignored issues
show
Bug introduced by
The method get_error_code cannot be called on $sso_redirect (of type string).

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

Loading history...
Bug introduced by
The method get_error_message cannot be called on $sso_redirect (of type string).

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

Loading history...
884
		}
885
886
		return $sso_redirect;
887
	}
888
889
	/**
890
	 * Build WordPress.com SSO URL with appropriate query parameters.
891
	 *
892
	 * @param  array  $args Optional query parameters.
893
	 * @return string       WordPress.com SSO URL
894
	 */
895
	function build_sso_url( $args = array() ) {
896
		$sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
897
		$defaults = array(
898
			'action'    => 'jetpack-sso',
899
			'site_id'   => Jetpack_Options::get_option( 'id' ),
900
			'sso_nonce' => $sso_nonce,
901
		);
902
903
		$args = wp_parse_args( $args, $defaults );
904
905
		if ( is_wp_error( $args['sso_nonce'] ) ) {
906
			return $args['sso_nonce'];
907
		}
908
909
		return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
910
	}
911
912
	/**
913
	 * Build WordPress.com SSO URL with appropriate query parameters,
914
	 * including the parameters necessary to force the user to reauthenticate
915
	 * on WordPress.com.
916
	 *
917
	 * @param  array  $args Optional query parameters.
918
	 * @return string       WordPress.com SSO URL
919
	 */
920
	function build_reauth_and_sso_url( $args = array() ) {
921
		$sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
922
		$redirect = $this->build_sso_url( array( 'force_auth' => '1', 'sso_nonce' => $sso_nonce ) );
923
924
		if ( is_wp_error( $redirect ) ) {
925
			return $redirect;
926
		}
927
928
		$defaults = array(
929
			'action'      => 'jetpack-sso',
930
			'site_id'     => Jetpack_Options::get_option( 'id' ),
931
			'sso_nonce'   => $sso_nonce,
932
			'reauth'      => '1',
933
			'redirect_to' => urlencode( $redirect ),
934
		);
935
936
		$args = wp_parse_args( $args, $defaults );
937
938
		if ( is_wp_error( $args['sso_nonce'] ) ) {
939
			return $args['sso_nonce'];
940
		}
941
942
		return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
943
	}
944
945
	/**
946
	 * Determines local user associated with a given WordPress.com user ID.
947
	 *
948
	 * @since 2.6.0
949
	 *
950
	 * @param int $wpcom_user_id User ID from WordPress.com
951
	 * @return object Local user object if found, null if not.
952
	 */
953
	static function get_user_by_wpcom_id( $wpcom_user_id ) {
954
		$user_query = new WP_User_Query( array(
955
			'meta_key'   => 'wpcom_user_id',
956
			'meta_value' => intval( $wpcom_user_id ),
957
			'number'     => 1,
958
		) );
959
960
		$users = $user_query->get_results();
961
		return $users ? array_shift( $users ) : null;
962
	}
963
964
	/**
965
	 * Error message displayed on the login form when two step is required and
966
	 * the user's account on WordPress.com does not have two step enabled.
967
	 *
968
	 * @since 2.7
969
	 * @param string $message
970
	 * @return string
971
	 **/
972
	public function error_msg_enable_two_step( $message ) {
973
		$err = __( sprintf( 'This site requires two step authentication be enabled for your user account on WordPress.com. Please visit the <a href="%1$s" target="_blank"> Security Settings</a> page to enable two step', 'https://wordpress.com/me/security/two-step' ) , 'jetpack' );
974
975
		$message .= sprintf( '<p class="message" id="login_error">%s</p>', $err );
976
977
		return $message;
978
	}
979
980
	/**
981
	 * Error message displayed when the user tries to SSO, but match by email
982
	 * is off and they already have an account with their email address on
983
	 * this site.
984
	 *
985
	 * @param string $message
986
	 * @return string
987
	 */
988
	public function error_msg_email_already_exists( $message ) {
989
		$err = __( sprintf( 'You already have an account on this site. Please visit your <a href="%1$s">profile page</a> page to link your account to WordPress.com!', admin_url( 'profile.php' ) ) , 'jetpack' );
990
991
		$message .= sprintf( '<p class="message" id="login_error">%s</p>', $err );
992
993
		return $message;
994
	}
995
996
	/**
997
	 * Message displayed when the site admin has disabled the default WordPress
998
	 * login form in Settings > General > Single Sign On
999
	 *
1000
	 * @since 2.7
1001
	 * @param string $message
1002
	 * @return string
1003
	 **/
1004
	public function msg_login_by_jetpack( $message ) {
1005
1006
		$msg = __( sprintf( 'Jetpack authenticates through WordPress.com — to log in, enter your WordPress.com username and password, or <a href="%1$s" target="_blank">visit WordPress.com</a> to create a free account now.', 'http://wordpress.com/signup' ) , 'jetpack' );
1007
1008
		/**
1009
		 * Filter the message displayed when the default WordPress login form is disabled.
1010
		 *
1011
		 * @module sso
1012
		 *
1013
		 * @since 2.8.0
1014
		 *
1015
		 * @param string $msg Disclaimer when default WordPress login form is disabled.
1016
		 */
1017
		$msg = apply_filters( 'jetpack_sso_disclaimer_message', $msg );
1018
1019
		$message .= sprintf( '<p class="message">%s</p>', $msg );
1020
		return $message;
1021
	}
1022
1023
	/**
1024
	 * Error message displayed on the login form when the user attempts
1025
	 * to post to the login form and it is disabled.
1026
	 *
1027
	 * @since 2.8
1028
	 * @param string $message
1029
	 * @param string
1030
	 **/
1031
	public function error_msg_login_method_not_allowed( $message ) {
1032
		$err = __( 'Login method not allowed' , 'jetpack' );
1033
		$message .= sprintf( '<p class="message" id="login_error">%s</p>', $err );
1034
1035
		return $message;
1036
	}
1037
	function cant_find_user( $message ) {
1038
		if ( self::match_by_email() ) {
1039
			$err_format = __( 'We couldn\'t find an account with the email <strong><code>%1$s</code></strong> to log you in with.  If you already have an account on <strong>%2$s</strong>, please make sure that <strong><code>%1$s</code></strong> is configured as the email address, or that you have connected to WordPress.com on your profile page.', 'jetpack' );
1040
		} else {
1041
			$err_format = __( 'We couldn\'t find any account on <strong>%2$s</strong> that is linked to your WordPress.com account to log you in with.  If you already have an account on <strong>%2$s</strong>, please make sure that you have connected to WordPress.com on your profile page.', 'jetpack' );
1042
		}
1043
		$err = sprintf( $err_format, $this->user_data->email, get_bloginfo( 'name' ) );
1044
		$message .= sprintf( '<p class="message" id="login_error">%s</p>', $err );
1045
		return $message;
1046
	}
1047
1048
	/**
1049
	 * When jetpack-sso-auth-redirect query parameter is set, will redirect user to
1050
	 * WordPress.com authorization flow.
1051
	 *
1052
	 * We redirect here instead of in handle_login() because Jetpack::init()->build_connect_url
1053
	 * calls menu_page_url() which doesn't work properly until admin menus are registered.
1054
	 */
1055
	function maybe_authorize_user_after_sso() {
1056
		if ( empty( $_GET['jetpack-sso-auth-redirect'] ) ) {
1057
			return;
1058
		}
1059
1060
		$redirect_to = ! empty( $_GET['redirect_to'] ) ? esc_url_raw( $_GET['redirect_to'] ) : admin_url();
1061
		$request_redirect_to = ! empty( $_GET['request_redirect_to'] ) ? esc_url_raw( $_GET['request_redirect_to'] ) : $redirect_to;
1062
1063
		/** This filter is documented in core/src/wp-login.php */
1064
		$redirect_after_auth = apply_filters( 'login_redirect', $redirect_to, $request_redirect_to, wp_get_current_user() );
1065
1066
		/**
1067
		 * Since we are passing this redirect to WordPress.com and therefore can not use wp_safe_redirect(),
1068
		 * let's sanitize it here to make sure it's safe. If the redirect is not safe, then use admin_url().
1069
		 */
1070
		$redirect_after_auth = wp_sanitize_redirect( $redirect_after_auth );
1071
		$redirect_after_auth = wp_validate_redirect( $redirect_after_auth, admin_url() );
1072
1073
		/**
1074
		 * Return the raw connect URL with our redirect and attribute connection to SSO.
1075
		 */
1076
		$connect_url = Jetpack::init()->build_connect_url( true, $redirect_after_auth, 'sso' );
1077
1078
		add_filter( 'allowed_redirect_hosts', array( $this, 'allowed_redirect_hosts' ) );
1079
		wp_safe_redirect( $connect_url );
1080
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method maybe_authorize_user_after_sso() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
1081
	}
1082
1083
	/**
1084
	 * Cache user's display name and Gravatar so it can be displayed on the login screen. These cookies are
1085
	 * stored when the user logs out, and then deleted when the user logs in.
1086
	 */
1087
	function store_wpcom_profile_cookies_on_logout() {
1088
		if ( ! Jetpack::is_user_connected( get_current_user_id() ) ) {
1089
			return;
1090
		}
1091
1092
		$user_data = $this->get_user_data( get_current_user_id() );
1093
		if ( ! $user_data ) {
1094
			return;
1095
		}
1096
1097
		setcookie(
1098
			'jetpack_sso_wpcom_name_' . COOKIEHASH,
1099
			$user_data->display_name,
1100
			time() + WEEK_IN_SECONDS,
1101
			COOKIEPATH,
1102
			COOKIE_DOMAIN
1103
		);
1104
1105
		setcookie(
1106
			'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
1107
			get_avatar_url(
1108
				$user_data->email,
1109
				array( 'size' => 72, 'default' => 'mystery' )
1110
			),
1111
			time() + WEEK_IN_SECONDS,
1112
			COOKIEPATH,
1113
			COOKIE_DOMAIN
1114
		);
1115
	}
1116
1117
	/**
1118
	 * Determines if a local user is connected to WordPress.com
1119
	 *
1120
	 * @since 2.8
1121
	 * @param integer $user_id - Local user id
1122
	 * @return boolean
1123
	 **/
1124
	public function is_user_connected( $user_id ) {
1125
		return $this->get_user_data( $user_id );
1126
	}
1127
1128
	/**
1129
	 * Retrieves a user's WordPress.com data
1130
	 *
1131
	 * @since 2.8
1132
	 * @param integer $user_id - Local user id
1133
	 * @return mixed null or stdClass
1134
	 **/
1135
	public function get_user_data( $user_id ) {
1136
		return get_user_meta( $user_id, 'wpcom_user_data', true );
1137
	}
1138
}
1139
1140
Jetpack_SSO::get_instance();
1141