Completed
Push — add/password-strength-checker ( 70f27e...f0b1af )
by
unknown
263:21 queued 256:27
created

Jetpack_Sync_Module_Users::authenticate_handler()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 4
nop 3
dl 0
loc 32
rs 9.0968
c 0
b 0
f 0
1
<?php
2
3
class Jetpack_Sync_Module_Users extends Jetpack_Sync_Module {
4
	const MAX_INITIAL_SYNC_USERS = 100;
5
6
	protected $flags = array();
7
8
	function name() {
9
		return 'users';
10
	}
11
12
	// this is here to support the backfill API
13
	public function get_object_by_id( $object_type, $id ) {
14
		if ( $object_type === 'user' && $user = get_user_by( 'id', intval( $id ) ) ) {
15
			return $this->sanitize_user_and_expand( $user );
16
		}
17
18
		return false;
19
	}
20
21
	public function init_listeners( $callable ) {
22
23
		// users
24
		add_action( 'user_register', array( $this, 'user_register_handler' ) );
25
		add_action( 'profile_update', array( $this, 'save_user_handler' ), 10, 2 );
26
27
		add_action( 'add_user_to_blog', array( $this, 'add_user_to_blog_handler' ) );
28
		add_action( 'jetpack_sync_add_user', $callable, 10, 2 );
29
		add_action( 'jetpack_sync_add_user', array( $this, 'clear_flags' ), 11 );
30
31
		add_action( 'jetpack_sync_register_user', $callable, 10, 2 );
32
		add_action( 'jetpack_sync_register_user', array( $this, 'clear_flags' ), 11 );
33
34
		add_action( 'jetpack_sync_save_user', $callable, 10, 2 );
35
		add_action( 'jetpack_sync_save_user', array( $this, 'clear_flags' ), 11 );
36
37
		add_action( 'jetpack_sync_user_locale', $callable, 10, 2 );
38
		add_action( 'jetpack_sync_user_locale_delete', $callable, 10, 1 );
39
40
		add_action( 'deleted_user', array( $this, 'deleted_user_handler' ), 10, 2 );
41
		add_action( 'jetpack_deleted_user', $callable, 10, 3 );
42
		add_action( 'remove_user_from_blog', array( $this, 'remove_user_from_blog_handler' ), 10, 2 );
43
		add_action( 'jetpack_removed_user_from_blog', $callable, 10, 2 );
44
45
		// user roles
46
		add_action( 'add_user_role', array( $this, 'save_user_role_handler' ), 10, 2 );
47
		add_action( 'set_user_role', array( $this, 'save_user_role_handler' ), 10, 3 );
48
		add_action( 'remove_user_role', array( $this, 'save_user_role_handler' ), 10, 2 );
49
50
		// user capabilities
51
		add_action( 'added_user_meta', array( $this, 'maybe_save_user_meta' ), 10, 4 );
52
		add_action( 'updated_user_meta', array( $this, 'maybe_save_user_meta' ), 10, 4 );
53
		add_action( 'deleted_user_meta', array( $this, 'maybe_save_user_meta' ), 10, 4 );
54
55
		// user authentication
56
		add_filter( 'authenticate', array( $this, 'authenticate_handler' ), 1000, 3 );
57
		add_action( 'wp_login', array( $this, 'wp_login_handler' ), 10, 2 );
58
59
		add_action( 'jetpack_wp_login', $callable, 10, 3 );
60
		add_action( 'jetpack_wp_login', array( $this, 'clear_flags' ), 11 );
61
62
		add_action( 'wp_logout', $callable, 10, 0 );
63
		add_action( 'wp_masterbar_logout', $callable, 10, 0 );
64
65
		// Add on init
66
		add_filter( 'jetpack_sync_before_enqueue_jetpack_sync_add_user', array( $this, 'expand_action' ) );
67
		add_filter( 'jetpack_sync_before_enqueue_jetpack_sync_register_user', array( $this, 'expand_action' ) );
68
		add_filter( 'jetpack_sync_before_enqueue_jetpack_sync_save_user', array( $this, 'expand_action' ) );
69
	}
70
71
	public function init_full_sync_listeners( $callable ) {
72
		add_action( 'jetpack_full_sync_users', $callable );
73
	}
74
75
	public function init_before_send() {
76
77
		add_filter( 'jetpack_sync_before_send_jetpack_wp_login', array( $this, 'expand_login_username' ), 10, 1 );
78
		add_filter( 'jetpack_sync_before_send_wp_logout', array( $this, 'expand_logout_username' ), 10, 2 );
79
80
		// full sync
81
		add_filter( 'jetpack_sync_before_send_jetpack_full_sync_users', array( $this, 'expand_users' ) );
82
	}
83
84
	private function get_user( $user ) {
85
		if ( is_numeric( $user ) ) {
86
			$user = get_user_by( 'id', $user );
87
		}
88
		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...
89
			return $user;
90
		}
91
		return null;
92
	}
93
94
	public function sanitize_user( $user ) {
95
		$user = $this->get_user( $user );
96
		// this create a new user object and stops the passing of the object by reference.
97
		$user = unserialize( serialize( $user ) );
98
99
		if ( is_object( $user ) && is_object( $user->data ) ) {
100
			unset( $user->data->user_pass );
101
		}
102
		return $user;
103
	}
104
105
	public function expand_user( $user ) {
106
		if ( ! is_object( $user ) ) {
107
			return null;
108
		}
109
		$user->allowed_mime_types = get_allowed_mime_types( $user );
110
		$user->allcaps            = $this->get_real_user_capabilities( $user );
111
112
		// Only set the user locale if it is different from the site local
113
		if ( get_locale() !== get_user_locale( $user->ID ) ) {
114
			$user->locale = get_user_locale( $user->ID );
115
		}
116
117
		return $user;
118
	}
119
120
	public function get_real_user_capabilities( $user ) {
121
		$user_capabilities = array();
122
		if ( is_wp_error( $user ) ) {
123
			return $user_capabilities;
124
		}
125
		foreach ( Jetpack_Sync_Defaults::get_capabilities_whitelist() as $capability ) {
126
			if ( $user_has_capabilities = user_can( $user, $capability ) ) {
0 ignored issues
show
Unused Code introduced by
$user_has_capabilities is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
127
				$user_capabilities[ $capability ] = true;
128
			}
129
		}
130
		return $user_capabilities;
131
	}
132
133
	public function sanitize_user_and_expand( $user ) {
134
		$user = $this->get_user( $user );
135
		$user = $this->expand_user( $user );
136
		return $this->sanitize_user( $user );
137
	}
138
139
	public function expand_action( $args ) {
140
		// the first argument is always the user
141
		list( $user ) = $args;
142
		if ( $user ) {
143
			$args[0] = $this->sanitize_user_and_expand( $user );
144
			return $args;
145
		}
146
147
		return false;
148
	}
149
    
150
	public function expand_login_username( $args ) {
151
		list( $login, $user, $flags ) = $args;
152
		$user                         = $this->sanitize_user( $user );
153
154
		return array( $login, $user, $flags );
155
	}
156
157
	public function expand_logout_username( $args, $user_id ) {
158
		$user = get_userdata( $user_id );
159
		$user = $this->sanitize_user( $user );
160
161
		$login = '';
162
		if ( is_object( $user ) && is_object( $user->data ) ) {
163
			$login = $user->data->user_login;
164
		}
165
		// if we don't have a user here lets not send anything.
166
		if ( empty( $login ) ) {
167
			return false;
168
		}
169
170
		return array( $login, $user );
171
	}
172
173
    /**
174
     * Additional processing is needed for wp_login so we introduce this wrapper
175
     * handler.
176
     *
177
     * @param String  $user_login the user login.
178
     * @param WP_User $user       the user object.
179
     */
180
     function wp_login_handler( $user_login, $user ) {
181
		/**
182
		 * Fires when a user is logged into a site.
183
		 *
184
		 * @since 7.2.0
185
		 *
186
		 * @param Numeric $user_id The user ID.
187
         * @param Array   $params  Additional event parameters.
188
		 */
189
        do_action( 'jetpack_wp_login', $user->ID, $user, $this->get_flags( $user->ID ) );
190
	}
191
192
	/**
193
	 * A hook for the authenticate event that checks the password strength.
194
	 *
195
	 * @param WP_Error|WP_User $user     the user object, or an error.
196
	 * @param String           $username the username.
197
	 * @param Sting            $password the password used to authenticate.
198
	 * @return WP_Error|WP_User the same object that was passed into the function.
199
	 */
200
	public function authenticate_handler( $user, $username, $password ) {
201
		jetpack_require_lib( 'class.jetpack-password-checker' );
202
203
        // In case of cookie authentication we don't do anything here.
204
        if ( empty( $password ) ) {
205
            return $user;
206
        }
207
208
		// We are only interested in successful authentication events.
209
		if ( is_wp_error( $user ) || ! ( $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...
210
			return $user;
211
		}
212
213
		$password_checker = new Jetpack_Password_Checker( $user->ID );
214
215
		$test_results = $password_checker->test( $password, true );
216
217
		// If the password passes tests, we don't do anything.
218
		if ( empty( $test_results['test_results']['failed'] ) ) {
219
			return $user;
220
		}
221
222
        $this->add_flags(
223
            $user->ID,
224
            array(
225
                'warning'          => 'The password failed at least one strength test.',
226
                'failures'         => $test_results['test_results']['failed'],
227
            )
228
        );
229
230
		return $user;
231
	}
232
233
	public function deleted_user_handler( $deleted_user_id, $reassigned_user_id = '' ) {
234
		$is_multisite = is_multisite();
235
		/**
236
		 * Fires when a user is deleted on a site
237
		 *
238
		 * @since 5.4.0
239
		 *
240
		 * @param int $deleted_user_id - ID of the deleted user
241
		 * @param int $reassigned_user_id - ID of the user the deleted user's posts is reassigned to (if any)
242
		 * @param bool $is_multisite - Whether this site is a multisite installation
243
		 */
244
		do_action( 'jetpack_deleted_user', $deleted_user_id, $reassigned_user_id, $is_multisite );
245
	}
246
247 View Code Duplication
	function user_register_handler( $user_id, $old_user_data = null ) {
248
		// ensure we only sync users who are members of the current blog
249
		if ( ! is_user_member_of_blog( $user_id, get_current_blog_id() ) ) {
250
			return;
251
		}
252
253
		if ( Jetpack_Constants::is_true( 'JETPACK_INVITE_ACCEPTED' ) ) {
254
			$this->add_flags( $user_id, array( 'invitation_accepted' => true ) );
255
		}
256
		/**
257
		 * Fires when a new user is registered on a site
258
		 *
259
		 * @since 4.9.0
260
		 *
261
		 * @param object The WP_User object
262
		 */
263
		do_action( 'jetpack_sync_register_user', $user_id, $this->get_flags( $user_id ) );
264
265
	}
266
267 View Code Duplication
	function add_user_to_blog_handler( $user_id, $old_user_data = null ) {
268
		// ensure we only sync users who are members of the current blog
269
		if ( ! is_user_member_of_blog( $user_id, get_current_blog_id() ) ) {
270
			return;
271
		}
272
273
		if ( Jetpack_Constants::is_true( 'JETPACK_INVITE_ACCEPTED' ) ) {
274
			$this->add_flags( $user_id, array( 'invitation_accepted' => true ) );
275
		}
276
		/**
277
		 * Fires when a user is added on a site
278
		 *
279
		 * @since 4.9.0
280
		 *
281
		 * @param object The WP_User object
282
		 */
283
		do_action( 'jetpack_sync_add_user', $user_id, $this->get_flags( $user_id ) );
284
	}
285
286
	function save_user_handler( $user_id, $old_user_data = null ) {
287
		// ensure we only sync users who are members of the current blog
288
		if ( ! is_user_member_of_blog( $user_id, get_current_blog_id() ) ) {
289
			return;
290
		}
291
292
		$user = get_user_by( 'id', $user_id );
293
294
		// Older versions of WP don't pass the old_user_data in ->data
295
		if ( isset( $old_user_data->data ) ) {
296
			$old_user = $old_user_data->data;
297
		} else {
298
			$old_user = $old_user_data;
299
		}
300
301
		if ( $old_user !== null && $user->user_pass !== $old_user->user_pass ) {
302
			$this->flags[ $user_id ]['password_changed'] = true;
303
		}
304
		if ( $old_user !== null && $user->data->user_email !== $old_user->user_email ) {
305
			// The '_new_email' user meta is deleted right after the call to wp_update_user
306
			// that got us to this point so if it's still set then this was a user confirming
307
			// their new email address
308
			if ( 1 === intval( get_user_meta( $user->ID, '_new_email', true ) ) ) {
309
				$this->flags[ $user_id ]['email_changed'] = true;
310
			}
311
		}
312
313
		/**
314
		 * Fires when the client needs to sync an updated user
315
		 *
316
		 * @since 4.2.0
317
		 *
318
		 * @param object The WP_User object
319
		 * @param array state - New since 5.8.0
320
		 */
321
		do_action( 'jetpack_sync_save_user', $user_id, $this->get_flags( $user_id ) );
322
	}
323
324
	function save_user_role_handler( $user_id, $role, $old_roles = null ) {
325
		$this->add_flags(
326
			$user_id,
327
			array(
328
				'role_changed'  => true,
329
				'previous_role' => $old_roles,
330
			)
331
		);
332
333
		// The jetpack_sync_register_user payload is identical to jetpack_sync_save_user, don't send both
334
		if ( $this->is_create_user() || $this->is_add_user_to_blog() ) {
335
			return;
336
		}
337
		/**
338
		 * This action is documented already in this file
339
		 */
340
		do_action( 'jetpack_sync_save_user', $user_id, $this->get_flags( $user_id ) );
341
	}
342
343
	function get_flags( $user_id ) {
344
		if ( isset( $this->flags[ $user_id ] ) ) {
345
			return $this->flags[ $user_id ];
346
		}
347
		return array();
348
	}
349
350
	function clear_flags( $user_id ) {
351
		if ( isset( $this->flags[ $user_id ] ) ) {
352
			unset( $this->flags[ $user_id ] );
353
		}
354
	}
355
356
	function add_flags( $user_id, $flags ) {
357
		$this->flags[ $user_id ] = wp_parse_args( $flags, $this->get_flags( $user_id ) );
358
	}
359
360
	function maybe_save_user_meta( $meta_id, $user_id, $meta_key, $value ) {
361
		if ( $meta_key === 'locale' ) {
362
			$this->add_flags( $user_id, array( 'locale_changed' => true ) );
363
		}
364
365
		$user = get_user_by( 'id', $user_id );
366
		if ( isset( $user->cap_key ) && $meta_key === $user->cap_key ) {
367
			$this->add_flags( $user_id, array( 'capabilities_changed' => true ) );
368
		}
369
370
		if ( $this->is_create_user() || $this->is_add_user_to_blog() || $this->is_delete_user() ) {
371
			return;
372
		}
373
374
		if ( isset( $this->flags[ $user_id ] ) ) {
375
			/**
376
			 * This action is documented already in this file
377
			 */
378
			do_action( 'jetpack_sync_save_user', $user_id, $this->get_flags( $user_id ) );
379
		}
380
	}
381
382
	public function enqueue_full_sync_actions( $config, $max_items_to_enqueue, $state ) {
383
		global $wpdb;
384
385
		return $this->enqueue_all_ids_as_action( 'jetpack_full_sync_users', $wpdb->usermeta, 'user_id', $this->get_where_sql( $config ), $max_items_to_enqueue, $state );
386
	}
387
388
	public function estimate_full_sync_actions( $config ) {
389
		global $wpdb;
390
391
		$query = "SELECT count(*) FROM $wpdb->usermeta";
392
393
		if ( $where_sql = $this->get_where_sql( $config ) ) {
394
			$query .= ' WHERE ' . $where_sql;
395
		}
396
397
		$count = $wpdb->get_var( $query );
398
399
		return (int) ceil( $count / self::ARRAY_CHUNK_SIZE );
400
	}
401
402 View Code Duplication
	private function get_where_sql( $config ) {
403
		global $wpdb;
404
405
		$query = "meta_key = '{$wpdb->prefix}capabilities'";
406
407
		// config is a list of user IDs to sync
408
		if ( is_array( $config ) ) {
409
			$query .= ' AND user_id IN (' . implode( ',', array_map( 'intval', $config ) ) . ')';
410
		}
411
412
		return $query;
413
	}
414
415
	function get_full_sync_actions() {
416
		return array( 'jetpack_full_sync_users' );
417
	}
418
419
	function get_initial_sync_user_config() {
420
		global $wpdb;
421
422
		$user_ids = $wpdb->get_col( "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}user_level' AND meta_value > 0 LIMIT " . ( self::MAX_INITIAL_SYNC_USERS + 1 ) );
423
424
		if ( count( $user_ids ) <= self::MAX_INITIAL_SYNC_USERS ) {
425
			return $user_ids;
426
		} else {
427
			return false;
428
		}
429
	}
430
431
	public function expand_users( $args ) {
432
		$user_ids = $args[0];
433
434
		return array_map( array( $this, 'sanitize_user_and_expand' ), get_users( array( 'include' => $user_ids ) ) );
435
	}
436
437
	public function remove_user_from_blog_handler( $user_id, $blog_id ) {
438
		// User is removed on add, see https://github.com/WordPress/WordPress/blob/0401cee8b36df3def8e807dd766adc02b359dfaf/wp-includes/ms-functions.php#L2114
439
		if ( $this->is_add_new_user_to_blog() ) {
440
			return;
441
		}
442
443
		$reassigned_user_id = $this->get_reassigned_network_user_id();
444
445
		// Note that we are in the context of the blog the user is removed from, see https://github.com/WordPress/WordPress/blob/473e1ba73bc5c18c72d7f288447503713d518790/wp-includes/ms-functions.php#L233
446
		/**
447
		 * Fires when a user is removed from a blog on a multisite installation
448
		 *
449
		 * @since 5.4.0
450
		 *
451
		 * @param int $user_id - ID of the removed user
452
		 * @param int $reassigned_user_id - ID of the user the removed user's posts is reassigned to (if any)
453
		 */
454
		do_action( 'jetpack_removed_user_from_blog', $user_id, $reassigned_user_id );
455
	}
456
457
	protected function is_add_new_user_to_blog() {
458
		return Jetpack::is_function_in_backtrace( 'add_new_user_to_blog' );
459
	}
460
461
	protected function is_add_user_to_blog() {
462
		return Jetpack::is_function_in_backtrace( 'add_user_to_blog' );
463
	}
464
465
	protected function is_delete_user() {
466
		return Jetpack::is_function_in_backtrace( array( 'wp_delete_user', 'remove_user_from_blog' ) );
467
	}
468
469
	protected function is_create_user() {
470
		$functions = array(
471
			'add_new_user_to_blog', // Used to suppress jetpack_sync_save_user in save_user_cap_handler when user registered on multi site
472
			'wp_create_user', // Used to suppress jetpack_sync_save_user in save_user_role_handler when user registered on multi site
473
			'wp_insert_user', // Used to suppress jetpack_sync_save_user in save_user_cap_handler and save_user_role_handler when user registered on single site
474
		);
475
476
		return Jetpack::is_function_in_backtrace( $functions );
477
	}
478
479
	protected function get_reassigned_network_user_id() {
480
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.PHP.NewFunctionParameters.debug_backtrace_optionsFound
481
		foreach ( $backtrace as $call ) {
482
			if (
483
				'remove_user_from_blog' === $call['function'] &&
484
				3 === count( $call['args'] )
485
			) {
486
				return $call['args'][2];
487
			}
488
		}
489
490
		return false;
491
	}
492
}
493