Completed
Push — update/jetpack-sso-styles ( f1147c...bd7da8 )
by
unknown
108:12 queued 98:32
created

Jetpack_SSO::new_user_override()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
1
<?php
2
require_once( JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' );
3
4
/**
5
 * Module Name: Single Sign On
6
 * Module Description: Secure user authentication with WordPress.com.
7
 * Jumpstart Description: Lets you log in to all your Jetpack-enabled sites with one click using your WordPress.com account.
8
 * Sort Order: 30
9
 * Recommendation Order: 5
10
 * First Introduced: 2.6
11
 * Requires Connection: Yes
12
 * Auto Activate: No
13
 * Module Tags: Developers
14
 * Feature: Security, Jumpstart
15
 * Additional Search Queries: sso, single sign on, login, log in
16
 */
17
18
class Jetpack_SSO {
19
	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...
20
21
	private function __construct() {
22
23
		self::$instance = $this;
24
25
		add_action( 'admin_init',             array( $this, 'maybe_authorize_user_after_sso' ), 1 );
26
		add_action( 'admin_init',             array( $this, 'register_settings' ) );
27
		add_action( 'login_init',             array( $this, 'login_init' ) );
28
		add_action( 'delete_user',            array( $this, 'delete_connection_for_user' ) );
29
		add_filter( 'jetpack_xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
30
		add_action( 'init',                   array( $this, 'maybe_logout_user' ), 5 );
31
		add_action( 'jetpack_modules_loaded', array( $this, 'module_configure_button' ) );
32
		add_action( 'admin_enqueue_scripts',  array( $this, 'admin_enqueue_scripts' ) );
33
		add_action( 'login_form_logout',      array( $this, 'store_wpcom_profile_cookies_on_logout' ) );
34
		add_action( 'wp_login',               array( 'Jetpack_SSO', 'clear_wpcom_profile_cookies' ) );
35
		add_action( 'jetpack_unlinked_user',  array( $this, 'delete_connection_for_user') );
36
37
		// Adding this action so that on login_init, the action won't be sanitized out of the $action global.
38
		add_action( 'login_form_jetpack-sso', '__return_true' );
39
40
		if ( Jetpack_SSO_Helpers::should_hide_login_form() ) {
41
			/**
42
			 * Since the default authenticate filters fire at priority 20 for checking username and password,
43
			 * let's fire at priority 30. wp_authenticate_spam_check is fired at priority 99, but since we return a
44
			 * WP_Error in disable_default_login_form, then we won't trigger spam processing logic.
45
			 */
46
			add_filter( 'authenticate', array( $this, 'disable_default_login_form' ), 30 );
47
48
			/**
49
			 * Filter the display of the disclaimer message appearing when default WordPress login form is disabled.
50
			 *
51
			 * @module sso
52
			 *
53
			 * @since 2.8.0
54
			 *
55
			 * @param bool true Should the disclaimer be displayed. Default to true.
56
			 */
57
			$display_sso_disclaimer = apply_filters( 'jetpack_sso_display_disclaimer', true );
58
			if ( $display_sso_disclaimer ) {
59
				add_filter( 'login_message', array( $this, 'msg_login_by_jetpack' ) );
60
			}
61
		}
62
	}
63
64
	/**
65
	 * Returns the single instance of the Jetpack_SSO object
66
	 *
67
	 * @since 2.8
68
	 * @return Jetpack_SSO
69
	 **/
70
	public static function get_instance() {
71
		if ( ! is_null( self::$instance ) ) {
72
			return self::$instance;
73
		}
74
75
		return self::$instance = new Jetpack_SSO;
76
	}
77
78
	/**
79
	 * Add configure button and functionality to the module card on the Jetpack screen
80
	 **/
81
	public static function module_configure_button() {
82
		Jetpack::enable_module_configurable( __FILE__ );
83
		Jetpack::module_configuration_load( __FILE__, array( __CLASS__, 'module_configuration_load' ) );
84
		Jetpack::module_configuration_head( __FILE__, array( __CLASS__, 'module_configuration_head' ) );
85
		Jetpack::module_configuration_screen( __FILE__, array( __CLASS__, 'module_configuration_screen' ) );
86
	}
87
88
	public static function module_configuration_load() {}
89
90
	public static function module_configuration_head() {}
91
92
	public static function module_configuration_screen() {
93
		?>
94
		<form method="post" action="options.php">
95
			<?php settings_fields( 'jetpack-sso' ); ?>
96
			<?php do_settings_sections( 'jetpack-sso' ); ?>
97
			<?php submit_button(); ?>
98
		</form>
99
		<?php
100
	}
101
102
103
	/**
104
	 * When the default login form is hidden, this method is called on the 'authenticate' filter with a priority of 30.
105
	 * This method disables the ability to submit the default login form.
106
	 *
107
	 * @param $user
108
	 *
109
	 * @return WP_Error
110
	 */
111
	public function disable_default_login_form( $user ) {
112
		if ( is_wp_error( $user ) ) {
113
			return $user;
114
		}
115
116
		/**
117
		 * Since we're returning an error that will be shown as a red notice, let's remove the
118
		 * informational "blue" notice.
119
		 */
120
		remove_filter( 'login_message', array( $this, 'msg_login_by_jetpack' ) );
121
		return new WP_Error( 'jetpack_sso_required', $this->get_sso_required_message() );
122
	}
123
124
	/**
125
	 * If jetpack_force_logout == 1 in current user meta the user will be forced
126
	 * to logout and reauthenticate with the site.
127
	 **/
128
	public function maybe_logout_user() {
129
		global $current_user;
130
131
		if ( 1 == $current_user->jetpack_force_logout ) {
132
			delete_user_meta( $current_user->ID, 'jetpack_force_logout' );
133
			self::delete_connection_for_user( $current_user->ID );
134
			wp_logout();
135
			wp_safe_redirect( wp_login_url() );
136
			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...
137
		}
138
	}
139
140
141
	/**
142
	 * Adds additional methods the WordPress xmlrpc API for handling SSO specific features
143
	 *
144
	 * @param array $methods
145
	 * @return array
146
	 **/
147
	public function xmlrpc_methods( $methods ) {
148
		$methods['jetpack.userDisconnect'] = array( $this, 'xmlrpc_user_disconnect' );
149
		return $methods;
150
	}
151
152
	/**
153
	 * Marks a user's profile for disconnect from WordPress.com and forces a logout
154
	 * the next time the user visits the site.
155
	 **/
156
	public function xmlrpc_user_disconnect( $user_id ) {
157
		$user_query = new WP_User_Query(
158
			array(
159
				'meta_key' => 'wpcom_user_id',
160
				'meta_value' => $user_id,
161
			)
162
		);
163
		$user = $user_query->get_results();
164
		$user = $user[0];
165
166
		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...
167
			$user = wp_set_current_user( $user->ID );
168
			update_user_meta( $user->ID, 'jetpack_force_logout', '1' );
169
			self::delete_connection_for_user( $user->ID );
170
			return true;
171
		}
172
		return false;
173
	}
174
175
	/**
176
	 * Enqueues scripts and styles necessary for SSO login.
177
	 */
178
	public function login_enqueue_scripts() {
179
		global $action;
180
181
		if ( ! in_array( $action, array( 'jetpack-sso', 'login' ) ) ) {
182
			return;
183
		}
184
185
		if ( is_rtl() ) {
186
			wp_enqueue_style( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login-rtl.css', JETPACK__PLUGIN_FILE ), array( 'login', 'genericons' ), JETPACK__VERSION );
187
		} else {
188
			wp_enqueue_style( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login.css', JETPACK__PLUGIN_FILE ), array( 'login', 'genericons' ), JETPACK__VERSION );
189
		}
190
191
		wp_enqueue_script( 'jetpack-sso-login', plugins_url( 'modules/sso/jetpack-sso-login.js', JETPACK__PLUGIN_FILE ), array( 'jquery' ), JETPACK__VERSION );
192
	}
193
194
	/**
195
	 * Enqueue styles neceessary for Jetpack SSO on users' profiles
196
	 */
197
	public function admin_enqueue_scripts() {
198
		$screen = get_current_screen();
199
200
		if ( empty( $screen ) || ! in_array( $screen->base, array( 'edit-user', 'profile' ) ) ) {
201
			return;
202
		}
203
204
		wp_enqueue_style( 'jetpack-sso-profile', plugins_url( 'modules/sso/jetpack-sso-profile.css', JETPACK__PLUGIN_FILE ), array( 'genericons' ), JETPACK__VERSION );
205
	}
206
207
	/**
208
	 * Adds Jetpack SSO classes to login body
209
	 *
210
	 * @param  array $classes Array of classes to add to body tag
211
	 * @return array          Array of classes to add to body tag
212
	 */
213
	public function login_body_class( $classes ) {
214
		global $action;
215
216
		if ( ! in_array( $action, array( 'jetpack-sso', 'login' ) ) ) {
217
			return $classes;
218
		}
219
220
		// If jetpack-sso-default-form, show the default login form.
221
		if ( isset( $_GET['jetpack-sso-default-form'] ) && 1 == $_GET['jetpack-sso-default-form'] ) {
222
			return $classes;
223
		}
224
225
		$classes[] = 'jetpack-sso-body';
226
		return $classes;
227
	}
228
229
	/**
230
	 * Adds settings fields to Settings > General > Single Sign On that allows users to
231
	 * turn off the login form on wp-login.php
232
	 *
233
	 * @since 2.7
234
	 **/
235
	public function register_settings() {
236
237
		add_settings_section(
238
			'jetpack_sso_settings',
239
			__( 'Single Sign On' , 'jetpack' ),
240
			'__return_false',
241
			'jetpack-sso'
242
		);
243
244
		/*
245
		 * Settings > General > Single Sign On
246
		 * Require two step authentication
247
		 */
248
		register_setting(
249
			'jetpack-sso',
250
			'jetpack_sso_require_two_step',
251
			array( $this, 'validate_jetpack_sso_require_two_step' )
252
		);
253
254
		add_settings_field(
255
			'jetpack_sso_require_two_step',
256
			'', // __( 'Require Two-Step Authentication' , 'jetpack' ),
257
			array( $this, 'render_require_two_step' ),
258
			'jetpack-sso',
259
			'jetpack_sso_settings'
260
		);
261
262
		/*
263
		 * Settings > General > Single Sign On
264
		 */
265
		register_setting(
266
			'jetpack-sso',
267
			'jetpack_sso_match_by_email',
268
			array( $this, 'validate_jetpack_sso_match_by_email' )
269
		);
270
271
		add_settings_field(
272
			'jetpack_sso_match_by_email',
273
			'', // __( 'Match by Email' , 'jetpack' ),
274
			array( $this, 'render_match_by_email' ),
275
			'jetpack-sso',
276
			'jetpack_sso_settings'
277
		);
278
	}
279
280
	/**
281
	 * Builds the display for the checkbox allowing user to require two step
282
	 * auth be enabled on WordPress.com accounts before login. Displays in Settings > General
283
	 *
284
	 * @since 2.7
285
	 **/
286 View Code Duplication
	public function render_require_two_step() {
287
		/** This filter is documented in modules/sso.php */
288
		$require_two_step = Jetpack_SSO_Helpers::is_two_step_required();
289
		$disabled = $require_two_step ? ' disabled="disabled"' : '';
290
		echo '<label>';
291
		echo '<input type="checkbox" name="jetpack_sso_require_two_step" ' . checked( $require_two_step, true, false ) . "$disabled>";
292
		esc_html_e( 'Require Two-Step Authentication' , 'jetpack' );
293
		echo '</label>';
294
	}
295
296
	/**
297
	 * Validate the require  two step checkbox in Settings > General
298
	 *
299
	 * @since 2.7
300
	 * @return boolean
301
	 **/
302
	public function validate_jetpack_sso_require_two_step( $input ) {
303
		return ( ! empty( $input ) ) ? 1 : 0;
304
	}
305
306
	/**
307
	 * Builds the display for the checkbox allowing the user to allow matching logins by email
308
	 * Displays in Settings > General
309
	 *
310
	 * @since 2.9
311
	 **/
312 View Code Duplication
	public function render_match_by_email() {
313
		$match_by_email = 1 == $this->match_by_email();
0 ignored issues
show
Bug introduced by
The method match_by_email() does not exist on Jetpack_SSO. Did you maybe mean render_match_by_email()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
314
		$disabled = $match_by_email ? ' disabled="disabled"' : '';
315
		echo '<label>';
316
		echo '<input type="checkbox" name="jetpack_sso_match_by_email"' . checked( $match_by_email, true, false ) . "$disabled>";
317
		esc_html_e( 'Match by Email', 'jetpack' );
318
		echo '</label>';
319
	}
320
321
	/**
322
	 * Validate the match by email check in Settings > General
323
	 *
324
	 * @since 2.9
325
	 * @return boolean
326
	 **/
327
	public function validate_jetpack_sso_match_by_email( $input ) {
328
		return ( ! empty( $input ) ) ? 1 : 0;
329
	}
330
331
	/**
332
	 * Checks to determine if the user wants to login on wp-login
333
	 *
334
	 * This function mostly exists to cover the exceptions to login
335
	 * that may exist as other parameters to $_GET[action] as $_GET[action]
336
	 * does not have to exist. By default WordPress assumes login if an action
337
	 * is not set, however this may not be true, as in the case of logout
338
	 * where $_GET[loggedout] is instead set
339
	 *
340
	 * @return boolean
341
	 **/
342
	private function wants_to_login() {
343
		$wants_to_login = false;
344
345
		// Cover default WordPress behavior
346
		$action = isset( $_REQUEST['action'] ) ? $_REQUEST['action'] : 'login';
347
348
		// And now the exceptions
349
		$action = isset( $_GET['loggedout'] ) ? 'loggedout' : $action;
350
351
		if ( 'login' == $action ) {
352
			$wants_to_login = true;
353
		}
354
355
		return $wants_to_login;
356
	}
357
358
	function login_init() {
359
		global $action;
360
361
		/**
362
		 * If the user is attempting to logout AND the auto-forward to WordPress.com
363
		 * login is set then we need to ensure we do not auto-forward the user and get
364
		 * them stuck in an infinite logout loop.
365
		 */
366
		if ( isset( $_GET['loggedout'] ) && Jetpack_SSO_Helpers::bypass_login_forward_wpcom() ) {
367
			add_filter( 'jetpack_remove_login_form', '__return_true' );
368
		}
369
370
		/**
371
		 * Check to see if the site admin wants to automagically forward the user
372
		 * to the WordPress.com login page AND  that the request to wp-login.php
373
		 * is not something other than login (Like logout!)
374
		 */
375 View Code Duplication
		if (
376
			$this->wants_to_login()
377
			&& Jetpack_SSO_Helpers::bypass_login_forward_wpcom()
378
		) {
379
			add_filter( 'allowed_redirect_hosts', array( $this, 'allowed_redirect_hosts' ) );
380
			$this->maybe_save_cookie_redirect();
381
			$reauth = ! empty( $_GET['force_reauth'] );
382
			$sso_url = $this->get_sso_url_or_die( $reauth );
383
			JetpackTracking::record_user_event( 'sso_login_redirect_bypass_success' );
384
			wp_safe_redirect( $sso_url );
385
			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...
386
		}
387
388
		if ( 'login' === $action ) {
389
			$this->display_sso_login_form();
390
		} elseif ( 'jetpack-sso' === $action ) {
391
			if ( isset( $_GET['result'], $_GET['user_id'], $_GET['sso_nonce'] ) && 'success' == $_GET['result'] ) {
392
				$this->handle_login();
393
				$this->display_sso_login_form();
394
			} else {
395
				if ( Jetpack::check_identity_crisis() ) {
396
					JetpackTracking::record_user_event( 'sso_login_redirect_failed', array(
397
						'error_message' => 'identity_crisis'
398
					) );
399
					wp_die( __( "Error: This site's Jetpack connection is currently experiencing problems.", 'jetpack' ) );
400 View Code Duplication
				} else {
401
					$this->maybe_save_cookie_redirect();
402
					// Is it wiser to just use wp_redirect than do this runaround to wp_safe_redirect?
403
					add_filter( 'allowed_redirect_hosts', array( $this, 'allowed_redirect_hosts' ) );
404
					$reauth = ! empty( $_GET['force_reauth'] );
405
					$sso_url = $this->get_sso_url_or_die( $reauth );
406
					JetpackTracking::record_user_event( 'sso_login_redirect_success' );
407
					wp_safe_redirect( $sso_url );
408
					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...
409
				}
410
			}
411
		}
412
	}
413
414
	/**
415
	 * Ensures that we can get a nonce from WordPress.com via XML-RPC before setting
416
	 * up the hooks required to display the SSO form.
417
	 */
418
	public function display_sso_login_form() {
419
		$sso_nonce = self::request_initial_nonce();
420
		if ( is_wp_error( $sso_nonce ) ) {
421
			return;
422
		}
423
424
		add_action( 'login_form',            array( $this, 'login_form' ) );
425
		add_filter( 'login_body_class',      array( $this, 'login_body_class' ) );
426
		add_action( 'login_enqueue_scripts', array( $this, 'login_enqueue_scripts' ) );
427
	}
428
429
	/**
430
	 * Conditionally save the redirect_to url as a cookie.
431
	 */
432
	public static function maybe_save_cookie_redirect() {
433
		if ( headers_sent() ) {
434
			return new WP_Error( 'headers_sent', __( 'Cannot deal with cookie redirects, as headers are already sent.', 'jetpack' ) );
435
		}
436
437
		if ( ! empty( $_GET['redirect_to'] ) ) {
438
			// If we have something to redirect to
439
			$url = esc_url_raw( $_GET['redirect_to'] );
440
			setcookie( 'jetpack_sso_redirect_to', $url, time() + HOUR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, false, true );
441
442
		} elseif ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
443
			// Otherwise, if it's already set, purge it.
444
			setcookie( 'jetpack_sso_redirect_to', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
445
		}
446
447
		if ( ! empty( $_GET['rememberme'] ) ) {
448
			setcookie( 'jetpack_sso_remember_me', '1', time() + HOUR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, false, true );
449
		} elseif ( ! empty( $_COOKIE['jetpack_sso_remember_me'] ) ) {
450
			setcookie( 'jetpack_sso_remember_me', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
451
		}
452
	}
453
454
	/**
455
	 * Outputs the Jetpack SSO button and description as well as the toggle link
456
	 * for switching between Jetpack SSO and default login.
457
	 */
458
	function login_form() {
459
		$site_name = get_bloginfo( 'name' );
460
		if ( ! $site_name ) {
461
			$site_name = get_bloginfo( 'url' );
462
		}
463
464
		$display_name = ! empty( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] )
465
			? $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ]
466
			: false;
467
		$gravatar = ! empty( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] )
468
			? $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ]
469
			: false;
470
471
		?>
472
		<div id="jetpack-sso-wrap">
473
			<?php if ( $display_name && $gravatar ) : ?>
474
				<div id="jetpack-sso-wrap__user">
475
					<img width="72" height="72" src="<?php echo esc_html( $gravatar ); ?>" />
476
477
					<h2>
478
						<?php
479
							echo wp_kses(
480
								sprintf( __( 'Log in as <span>%s</span>', 'jetpack' ), esc_html( $display_name ) ),
481
								array( 'span' => true )
482
							);
483
						?>
484
					</h2>
485
				</div>
486
487
			<?php endif; ?>
488
489
490
			<div id="jetpack-sso-wrap__action">
491
				<?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...
492
493
				<?php if ( $display_name && $gravatar ) : ?>
494
					<a rel="nofollow" class="jetpack-sso-wrap__reauth" href="<?php echo esc_url( $this->build_sso_button_url( array( 'force_reauth' => '1' ) ) ); ?>">
495
						<?php esc_html_e( 'Log in as a different WordPress.com user', 'jetpack' ); ?>
496
					</a>
497
				<?php else : ?>
498
					<p>
499
						<?php
500
							echo esc_html(
501
								sprintf(
502
									__( 'You can now save time spent logging in by connecting your WordPress.com account to %s.', 'jetpack' ),
503
									esc_html( $site_name )
504
								)
505
							);
506
						?>
507
					</p>
508
				<?php endif; ?>
509
			</div>
510
511
			<?php if ( ! Jetpack_SSO_Helpers::should_hide_login_form() ) : ?>
512
				<div class="jetpack-sso-or">
513
					<span><?php esc_html_e( 'Or', 'jetpack' ); ?></span>
514
				</div>
515
516
				<a href="<?php echo add_query_arg( 'jetpack-sso-default-form', '1' ); ?>" class="jetpack-sso-toggle wpcom">
517
					<?php
518
						esc_html_e( 'Log in with username and password', 'jetpack' )
519
					?>
520
				</a>
521
522
				<a href="<?php echo add_query_arg( 'jetpack-sso-default-form', '0' ); ?>" class="jetpack-sso-toggle default">
523
					<?php
524
						esc_html_e( 'Log in with WordPress.com', 'jetpack' )
525
					?>
526
				</a>
527
			<?php endif; ?>
528
		</div>
529
		<?php
530
	}
531
532
	/**
533
	 * Clear the cookies that store the profile information for the last
534
	 * WPCOM user to connect.
535
	 */
536
	static function clear_wpcom_profile_cookies() {
537 View Code Duplication
		if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] ) ) {
538
			setcookie(
539
				'jetpack_sso_wpcom_name_' . COOKIEHASH,
540
				' ',
541
				time() - YEAR_IN_SECONDS,
542
				COOKIEPATH,
543
				COOKIE_DOMAIN
544
			);
545
		}
546
547 View Code Duplication
		if ( isset( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] ) ) {
548
			setcookie(
549
				'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
550
				' ',
551
				time() - YEAR_IN_SECONDS,
552
				COOKIEPATH,
553
				COOKIE_DOMAIN
554
			);
555
		}
556
	}
557
558
	static function delete_connection_for_user( $user_id ) {
559
		if ( ! $wpcom_user_id = get_user_meta( $user_id, 'wpcom_user_id', true ) ) {
560
			return;
561
		}
562
		Jetpack::load_xml_rpc_client();
563
		$xml = new Jetpack_IXR_Client( array(
564
			'wpcom_user_id' => $user_id,
565
		) );
566
		$xml->query( 'jetpack.sso.removeUser', $wpcom_user_id );
567
568
		if ( $xml->isError() ) {
569
			return false;
570
		}
571
572
		// Clean up local data stored for SSO
573
		delete_user_meta( $user_id, 'wpcom_user_id' );
574
		delete_user_meta( $user_id, 'wpcom_user_data'  );
575
		self::clear_wpcom_profile_cookies();
576
577
		return $xml->getResponse();
578
	}
579
580 View Code Duplication
	static function request_initial_nonce() {
581
		Jetpack::load_xml_rpc_client();
582
		$xml = new Jetpack_IXR_Client( array(
583
			'user_id' => get_current_user_id(),
584
		) );
585
		$xml->query( 'jetpack.sso.requestNonce' );
586
587
		if ( $xml->isError() ) {
588
			return new WP_Error( $xml->getErrorCode(), $xml->getErrorMessage() );
589
		}
590
591
		return $xml->getResponse();
592
	}
593
594
	/**
595
	 * The function that actually handles the login!
596
	 */
597
	function handle_login() {
598
		$wpcom_nonce   = sanitize_key( $_GET['sso_nonce'] );
599
		$wpcom_user_id = (int) $_GET['user_id'];
600
601
		Jetpack::load_xml_rpc_client();
602
		$xml = new Jetpack_IXR_Client( array(
603
			'user_id' => get_current_user_id(),
604
		) );
605
		$xml->query( 'jetpack.sso.validateResult', $wpcom_nonce, $wpcom_user_id );
606
607
		if ( $xml->isError() ) {
608
			$error_message = sanitize_text_field(
609
				sprintf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() )
610
			);
611
			JetpackTracking::record_user_event( 'sso_login_failed', array(
612
				'error_message' => $error_message
613
			) );
614
			wp_die( $error_message );
615
		}
616
617
		$user_data = $xml->getResponse();
618
619
		if ( empty( $user_data ) ) {
620
			JetpackTracking::record_user_event( 'sso_login_failed', array(
621
				'error_message' => 'invalid_response_data'
622
			) );
623
			wp_die( __( 'Error, invalid response data.', 'jetpack' ) );
624
		}
625
626
		$user_data = (object) $user_data;
627
		$user = null;
628
629
		/**
630
		 * Fires before Jetpack's SSO modifies the log in form.
631
		 *
632
		 * @module sso
633
		 *
634
		 * @since 2.6.0
635
		 *
636
		 * @param object $user_data User login information.
637
		 */
638
		do_action( 'jetpack_sso_pre_handle_login', $user_data );
639
640
		if ( Jetpack_SSO_Helpers::is_two_step_required() && 0 === (int) $user_data->two_step_enabled ) {
641
			$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...
642
643
			JetpackTracking::record_user_event( 'sso_login_failed', array(
644
				'error_message' => 'error_msg_enable_two_step'
645
			) );
646
			
647
			/** This filter is documented in core/src/wp-includes/pluggable.php */
648
			do_action( 'wp_login_failed', $user_data->login );
649
			add_filter( 'login_message', array( $this, 'error_msg_enable_two_step' ) );
650
			return;
651
		}
652
653
		$user_found_with = '';
654
		if ( empty( $user ) && isset( $user_data->external_user_id ) ) {
655
			$user_found_with = 'external_user_id';
656
			$user = get_user_by( 'id', intval( $user_data->external_user_id ) );
657
			if ( $user ) {
658
				update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
659
			}
660
		}
661
662
		// If we don't have one by wpcom_user_id, try by the email?
663
		if ( empty( $user ) && Jetpack_SSO_Helpers::match_by_email() ) {
664
			$user_found_with = 'match_by_email';
665
			$user = get_user_by( 'email', $user_data->email );
666
			if ( $user ) {
667
				update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
668
			}
669
		}
670
671
		// If we've still got nothing, create the user.
672
		if ( empty( $user ) && ( get_option( 'users_can_register' ) || Jetpack_SSO_Helpers::new_user_override() ) ) {
673
			// If not matching by email we still need to verify the email does not exist
674
			// or this blows up
675
			/**
676
			 * If match_by_email is true, we know the email doesn't exist, as it would have
677
			 * been found in the first pass.  If get_user_by( 'email' ) doesn't find the
678
			 * user, then we know that email is unused, so it's safe to add.
679
			 */
680
			if ( Jetpack_SSO_Helpers::match_by_email() || ! get_user_by( 'email', $user_data->email ) ) {
681
				$username = $user_data->login;
682
683
				if ( username_exists( $username ) ) {
684
					$username = $user_data->login . '_' . $user_data->ID;
685
				}
686
687
				$tries = 0;
688
				while ( username_exists( $username ) ) {
689
					$username = $user_data->login . '_' . $user_data->ID . '_' . mt_rand();
690
					if ( $tries++ >= 5 ) {
691
						JetpackTracking::record_user_event( 'sso_login_failed', array(
692
							'error_message' => 'could_not_create_username'
693
						) );
694
						wp_die( __( "Error: Couldn't create suitable username.", 'jetpack' ) );
695
					}
696
				}
697
698
				$user_found_with = Jetpack_SSO_Helpers::new_user_override()
699
					? 'user_created_new_user_override'
700
					: 'user_created_users_can_register';
701
702
				$password = wp_generate_password( 20 );
703
				$user_id  = wp_create_user( $username, $password, $user_data->email );
704
				$user     = get_userdata( $user_id );
705
706
				$user->display_name = $user_data->display_name;
707
				$user->first_name   = $user_data->first_name;
708
				$user->last_name    = $user_data->last_name;
709
				$user->url          = $user_data->url;
710
				$user->description  = $user_data->description;
711
				wp_update_user( $user );
712
713
				update_user_meta( $user->ID, 'wpcom_user_id', $user_data->ID );
714
			} else {
715
				JetpackTracking::record_user_event( 'sso_login_failed', array(
716
					'error_message' => 'error_msg_email_already_exists'
717
				) );
718
719
				$this->user_data = $user_data;
720
				add_action( 'login_message', array( $this, 'error_msg_email_already_exists' ) );
721
				return;
722
			}
723
		}
724
725
		/**
726
		 * Fires after we got login information from WordPress.com.
727
		 *
728
		 * @module sso
729
		 *
730
		 * @since 2.6.0
731
		 *
732
		 * @param array $user WordPress.com User information.
733
		 * @param object $user_data User Login information.
734
		 */
735
		do_action( 'jetpack_sso_handle_login', $user, $user_data );
736
737
		if ( $user ) {
738
			// Cache the user's details, so we can present it back to them on their user screen
739
			update_user_meta( $user->ID, 'wpcom_user_data', $user_data );
740
741
			$remember = false;
742 View Code Duplication
			if ( ! empty( $_COOKIE['jetpack_sso_remember_me'] ) ) {
743
				$remember = true;
744
				// And then purge it
745
				setcookie( 'jetpack_sso_remember_me', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
746
			}
747
			/**
748
			 * Filter the remember me value.
749
			 *
750
			 * @module sso
751
			 *
752
			 * @since 2.8.0
753
			 *
754
			 * @param bool $remember Is the remember me option checked?
755
			 */
756
			$remember = apply_filters( 'jetpack_remember_login', $remember );
757
			wp_set_auth_cookie( $user->ID, $remember );
758
759
			/** This filter is documented in core/src/wp-includes/user.php */
760
			do_action( 'wp_login', $user->user_login, $user );
761
762
			wp_set_current_user( $user->ID );
763
764
			$_request_redirect_to = isset( $_REQUEST['redirect_to'] ) ? esc_url_raw( $_REQUEST['redirect_to'] ) : '';
765
			$redirect_to = user_can( $user, 'edit_posts' ) ? admin_url() : self::profile_page_url();
766
767
			// If we have a saved redirect to request in a cookie
768 View Code Duplication
			if ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
769
				// Set that as the requested redirect to
770
				$redirect_to = $_request_redirect_to = esc_url_raw( $_COOKIE['jetpack_sso_redirect_to'] );
771
				// And then purge it
772
				setcookie( 'jetpack_sso_redirect_to', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
773
			}
774
775
			$is_user_connected = Jetpack::is_user_connected( $user->ID );
776
			JetpackTracking::record_user_event( 'sso_user_logged_in', array(
777
				'user_found_with' => $user_found_with,
778
				'user_connected'  => (bool) $is_user_connected,
779
				'user_role'       => Jetpack::init()->translate_current_user_to_role()
780
			) );
781
782
			if ( ! $is_user_connected ) {
783
				$calypso_env = ! empty( $_GET['calypso_env'] )
784
					? sanitize_key( $_GET['calypso_env'] )
785
					: '';
786
787
				wp_safe_redirect(
788
					add_query_arg(
789
						array(
790
							'redirect_to'               => $redirect_to,
791
							'request_redirect_to'       => $_request_redirect_to,
792
							'calypso_env'               => $calypso_env,
793
							'jetpack-sso-auth-redirect' => '1',
794
						),
795
						admin_url()
796
					)
797
				);
798
				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...
799
			}
800
801
			wp_safe_redirect(
802
				/** This filter is documented in core/src/wp-login.php */
803
				apply_filters( 'login_redirect', $redirect_to, $_request_redirect_to, $user )
804
			);
805
			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...
806
		}
807
808
		JetpackTracking::record_user_event( 'sso_login_failed', array(
809
			'error_message' => 'cant_find_user'
810
		) );
811
812
		$this->user_data = $user_data;
813
		/** This filter is documented in core/src/wp-includes/pluggable.php */
814
		do_action( 'wp_login_failed', $user_data->login );
815
		add_filter( 'login_message', array( $this, 'cant_find_user' ) );
816
	}
817
818
	static function profile_page_url() {
819
		return admin_url( 'profile.php' );
820
	}
821
822
	function allowed_redirect_hosts( $hosts ) {
823
		if ( empty( $hosts ) ) {
824
			$hosts = array();
825
		}
826
		$hosts[] = 'wordpress.com';
827
		$hosts[] = 'jetpack.wordpress.com';
828
829
		return array_unique( $hosts );
830
	}
831
832
	/**
833
	 * Builds the "Login to WordPress.com" button that is displayed on the login page as well as user profile page.
834
	 *
835
	 * @param  array   $args       An array of arguments to add to the SSO URL.
836
	 * @param  boolean $is_primary Should the button have the `button-primary` class?
837
	 * @return string              Returns the HTML markup for the button.
838
	 */
839
	function build_sso_button( $args = array(), $is_primary = false ) {
840
		$url = $this->build_sso_button_url( $args );
841
		$classes = $is_primary
842
			? 'jetpack-sso button button-primary'
843
			: 'jetpack-sso button';
844
845
		return sprintf(
846
			'<a rel="nofollow" href="%1$s" class="%2$s"><span>%3$s %4$s</span></a>',
847
			esc_url( $url ),
848
			$classes,
849
			'<span class="genericon genericon-wordpress"></span>',
850
			esc_html__( 'Log in with WordPress.com', 'jetpack' )
851
		);
852
	}
853
854
	/**
855
	 * Builds a URL with `jetpack-sso` action and option args which is used to setup SSO.
856
	 *
857
	 * @param  array  $args An array of arguments to add to the SSO URL.
858
	 * @return string       The URL used for SSO.
859
	 */
860
	function build_sso_button_url( $args = array() ) {
861
		$defaults = array(
862
			'action'  => 'jetpack-sso',
863
		);
864
865
		$args = wp_parse_args( $args, $defaults );
866
867
		if ( ! empty( $_GET['redirect_to'] ) ) {
868
			$args['redirect_to'] = esc_url_raw( $_GET['redirect_to'] );
869
		}
870
871
		return add_query_arg( $args, wp_login_url() );
872
	}
873
874
	/**
875
	 * Retrieves a WordPress.com SSO URL with appropriate query parameters or dies.
876
	 *
877
	 * @param  boolean  $reauth  Should the user be forced to reauthenticate on WordPress.com?
878
	 * @param  array    $args    Optional query parameters.
879
	 * @return string            The WordPress.com SSO URL.
880
	 */
881
	function get_sso_url_or_die( $reauth = false, $args = array() ) {
882
		if ( empty( $reauth ) ) {
883
			$sso_redirect = $this->build_sso_url( $args );
884
		} else {
885
			self::clear_wpcom_profile_cookies();
886
			$sso_redirect = $this->build_reauth_and_sso_url( $args );
887
		}
888
889
		// If there was an error retrieving the SSO URL, then error.
890
		if ( is_wp_error( $sso_redirect ) ) {
891
			$error_message = sanitize_text_field(
892
				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...
893
			);
894
			JetpackTracking::record_user_event( 'sso_login_redirect_failed', array(
895
				'error_message' => $error_message
896
			) );
897
			wp_die( $error_message );
898
		}
899
900
		return $sso_redirect;
901
	}
902
903
	/**
904
	 * Build WordPress.com SSO URL with appropriate query parameters.
905
	 *
906
	 * @param  array  $args Optional query parameters.
907
	 * @return string       WordPress.com SSO URL
908
	 */
909
	function build_sso_url( $args = array() ) {
910
		$sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
911
		$defaults = array(
912
			'action'    => 'jetpack-sso',
913
			'site_id'   => Jetpack_Options::get_option( 'id' ),
914
			'sso_nonce' => $sso_nonce,
915
		);
916
917
		$args = wp_parse_args( $args, $defaults );
918
919
		if ( is_wp_error( $args['sso_nonce'] ) ) {
920
			return $args['sso_nonce'];
921
		}
922
923
		return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
924
	}
925
926
	/**
927
	 * Build WordPress.com SSO URL with appropriate query parameters,
928
	 * including the parameters necessary to force the user to reauthenticate
929
	 * on WordPress.com.
930
	 *
931
	 * @param  array  $args Optional query parameters.
932
	 * @return string       WordPress.com SSO URL
933
	 */
934
	function build_reauth_and_sso_url( $args = array() ) {
935
		$sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
936
		$redirect = $this->build_sso_url( array( 'force_auth' => '1', 'sso_nonce' => $sso_nonce ) );
937
938
		if ( is_wp_error( $redirect ) ) {
939
			return $redirect;
940
		}
941
942
		$defaults = array(
943
			'action'      => 'jetpack-sso',
944
			'site_id'     => Jetpack_Options::get_option( 'id' ),
945
			'sso_nonce'   => $sso_nonce,
946
			'reauth'      => '1',
947
			'redirect_to' => urlencode( $redirect ),
948
		);
949
950
		$args = wp_parse_args( $args, $defaults );
951
952
		if ( is_wp_error( $args['sso_nonce'] ) ) {
953
			return $args['sso_nonce'];
954
		}
955
956
		return add_query_arg( $args, 'https://wordpress.com/wp-login.php' );
957
	}
958
959
	/**
960
	 * Determines local user associated with a given WordPress.com user ID.
961
	 *
962
	 * @since 2.6.0
963
	 *
964
	 * @param int $wpcom_user_id User ID from WordPress.com
965
	 * @return object Local user object if found, null if not.
966
	 */
967
	static function get_user_by_wpcom_id( $wpcom_user_id ) {
968
		$user_query = new WP_User_Query( array(
969
			'meta_key'   => 'wpcom_user_id',
970
			'meta_value' => intval( $wpcom_user_id ),
971
			'number'     => 1,
972
		) );
973
974
		$users = $user_query->get_results();
975
		return $users ? array_shift( $users ) : null;
976
	}
977
978
	/**
979
	 * Error message displayed on the login form when two step is required and
980
	 * the user's account on WordPress.com does not have two step enabled.
981
	 *
982
	 * @since 2.7
983
	 * @param string $message
984
	 * @return string
985
	 **/
986
	public function error_msg_enable_two_step( $message ) {
987
		$error = sprintf(
988
			wp_kses(
989
				__(
990
					'Two-Step Authentication is required to access this site. Please visit your <a href="%1$s" target="_blank">Security Settings</a> to configure <a href="%2$S" target="_blank">Two-step Authentication</a> for your account.',
991
					'jetpack'
992
				),
993
				array(  'a' => array( 'href' => array() ) )
994
			),
995
			'https://wordpress.com/me/security/two-step',
996
			'https://support.wordpress.com/security/two-step-authentication/'
997
		);
998
999
		$message .= sprintf( '<p class="message" id="login_error">%s</p>', $error );
1000
1001
		return $message;
1002
	}
1003
1004
	/**
1005
	 * Error message displayed when the user tries to SSO, but match by email
1006
	 * is off and they already have an account with their email address on
1007
	 * this site.
1008
	 *
1009
	 * @param string $message
1010
	 * @return string
1011
	 */
1012
	public function error_msg_email_already_exists( $message ) {
1013
		$error = sprintf(
1014
			wp_kses(
1015
				__(
1016
					'You already have an account on this site. Please <a href="%1$s">sign in</a> with your username and password and then connect to WordPress.com.',
1017
					'jetpack'
1018
				),
1019
				array(  'a' => array( 'href' => array() ) )
1020
			),
1021
			esc_url_raw( add_query_arg( 'jetpack-sso-default-form', '1', wp_login_url() ) )
1022
		);
1023
1024
		$message .= sprintf( '<p class="message" id="login_error">%s</p>', $error );
1025
1026
		return $message;
1027
	}
1028
1029
	/**
1030
	 * Builds the translation ready string that is to be used when the site hides the default login form.
1031
	 *
1032
	 * @since 4.1.0
1033
	 * 
1034
	 * @return string
1035
	 */
1036
	public function get_sso_required_message() {
1037
		$msg = esc_html__( 'A WordPress.com account is required to access this site. Click the button below to sign in or create a free WordPress.com account.', 'jetpack' );
1038
1039
		/**
1040
		 * Filter the message displayed when the default WordPress login form is disabled.
1041
		 *
1042
		 * @module sso
1043
		 *
1044
		 * @since 2.8.0
1045
		 *
1046
		 * @param string $msg Disclaimer when default WordPress login form is disabled.
1047
		 */
1048
		return apply_filters( 'jetpack_sso_disclaimer_message', $msg );
1049
	}
1050
1051
	/**
1052
	 * Message displayed when the site admin has disabled the default WordPress
1053
	 * login form in Settings > General > Single Sign On
1054
	 *
1055
	 * @since 2.7
1056
	 * @param string $message
1057
	 * 
1058
	 * @return string
1059
	 **/
1060
	public function msg_login_by_jetpack( $message ) {
1061
		$msg = $this->get_sso_required_message();
1062
1063
		if ( empty( $msg ) ) {
1064
			return $message;
1065
		}
1066
1067
		$message .= sprintf( '<p class="message">%s</p>', $msg );
1068
		return $message;
1069
	}
1070
1071
	/**
1072
	 * Message displayed when the user can not be found after approving the SSO process on WordPress.com
1073
	 *
1074
	 * @param string $message
1075
	 * @return string
1076
	 */
1077
	function cant_find_user( $message ) {
1078
		$error = esc_html__(
1079
			"We couldn't find your account. If you already have an account, make sure you have connected to WordPress.com.",
1080
			'jetpack'
1081
		);
1082
		$message .= sprintf( '<p class="message" id="login_error">%s</p>', $error );
1083
1084
		return $message;
1085
	}
1086
1087
	/**
1088
	 * When jetpack-sso-auth-redirect query parameter is set, will redirect user to
1089
	 * WordPress.com authorization flow.
1090
	 *
1091
	 * We redirect here instead of in handle_login() because Jetpack::init()->build_connect_url
1092
	 * calls menu_page_url() which doesn't work properly until admin menus are registered.
1093
	 */
1094
	function maybe_authorize_user_after_sso() {
1095
		if ( empty( $_GET['jetpack-sso-auth-redirect'] ) ) {
1096
			return;
1097
		}
1098
1099
		$redirect_to = ! empty( $_GET['redirect_to'] ) ? esc_url_raw( $_GET['redirect_to'] ) : admin_url();
1100
		$request_redirect_to = ! empty( $_GET['request_redirect_to'] ) ? esc_url_raw( $_GET['request_redirect_to'] ) : $redirect_to;
1101
1102
		/** This filter is documented in core/src/wp-login.php */
1103
		$redirect_after_auth = apply_filters( 'login_redirect', $redirect_to, $request_redirect_to, wp_get_current_user() );
1104
1105
		/**
1106
		 * Since we are passing this redirect to WordPress.com and therefore can not use wp_safe_redirect(),
1107
		 * let's sanitize it here to make sure it's safe. If the redirect is not safe, then use admin_url().
1108
		 */
1109
		$redirect_after_auth = wp_sanitize_redirect( $redirect_after_auth );
1110
		$redirect_after_auth = wp_validate_redirect( $redirect_after_auth, admin_url() );
1111
1112
		/**
1113
		 * Return the raw connect URL with our redirect and attribute connection to SSO.
1114
		 */
1115
		$connect_url = Jetpack::init()->build_connect_url( true, $redirect_after_auth, 'sso' );
1116
1117
		add_filter( 'allowed_redirect_hosts', array( $this, 'allowed_redirect_hosts' ) );
1118
		wp_safe_redirect( $connect_url );
1119
		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...
1120
	}
1121
1122
	/**
1123
	 * Cache user's display name and Gravatar so it can be displayed on the login screen. These cookies are
1124
	 * stored when the user logs out, and then deleted when the user logs in.
1125
	 */
1126
	function store_wpcom_profile_cookies_on_logout() {
1127
		if ( ! Jetpack::is_user_connected( get_current_user_id() ) ) {
1128
			return;
1129
		}
1130
1131
		$user_data = $this->get_user_data( get_current_user_id() );
1132
		if ( ! $user_data ) {
1133
			return;
1134
		}
1135
1136
		setcookie(
1137
			'jetpack_sso_wpcom_name_' . COOKIEHASH,
1138
			$user_data->display_name,
1139
			time() + WEEK_IN_SECONDS,
1140
			COOKIEPATH,
1141
			COOKIE_DOMAIN
1142
		);
1143
1144
		setcookie(
1145
			'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
1146
			get_avatar_url(
1147
				$user_data->email,
1148
				array( 'size' => 72, 'default' => 'mystery' )
1149
			),
1150
			time() + WEEK_IN_SECONDS,
1151
			COOKIEPATH,
1152
			COOKIE_DOMAIN
1153
		);
1154
	}
1155
1156
	/**
1157
	 * Determines if a local user is connected to WordPress.com
1158
	 *
1159
	 * @since 2.8
1160
	 * @param integer $user_id - Local user id
1161
	 * @return boolean
1162
	 **/
1163
	public function is_user_connected( $user_id ) {
1164
		return $this->get_user_data( $user_id );
1165
	}
1166
1167
	/**
1168
	 * Retrieves a user's WordPress.com data
1169
	 *
1170
	 * @since 2.8
1171
	 * @param integer $user_id - Local user id
1172
	 * @return mixed null or stdClass
1173
	 **/
1174
	public function get_user_data( $user_id ) {
1175
		return get_user_meta( $user_id, 'wpcom_user_data', true );
1176
	}
1177
}
1178
1179
Jetpack_SSO::get_instance();
1180