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