]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/user.php
WordPress 3.6.1-scripts
[autoinstalls/wordpress.git] / wp-includes / user.php
1 <?php
2 /**
3  * WordPress User API
4  *
5  * @package WordPress
6  */
7
8 /**
9  * Authenticate user with remember capability.
10  *
11  * The credentials is an array that has 'user_login', 'user_password', and
12  * 'remember' indices. If the credentials is not given, then the log in form
13  * will be assumed and used if set.
14  *
15  * The various authentication cookies will be set by this function and will be
16  * set for a longer period depending on if the 'remember' credential is set to
17  * true.
18  *
19  * @since 2.5.0
20  *
21  * @param array $credentials Optional. User info in order to sign on.
22  * @param bool $secure_cookie Optional. Whether to use secure cookie.
23  * @return object Either WP_Error on failure, or WP_User on success.
24  */
25 function wp_signon( $credentials = '', $secure_cookie = '' ) {
26         if ( empty($credentials) ) {
27                 if ( ! empty($_POST['log']) )
28                         $credentials['user_login'] = $_POST['log'];
29                 if ( ! empty($_POST['pwd']) )
30                         $credentials['user_password'] = $_POST['pwd'];
31                 if ( ! empty($_POST['rememberme']) )
32                         $credentials['remember'] = $_POST['rememberme'];
33         }
34
35         if ( !empty($credentials['remember']) )
36                 $credentials['remember'] = true;
37         else
38                 $credentials['remember'] = false;
39
40         // TODO do we deprecate the wp_authentication action?
41         do_action_ref_array('wp_authenticate', array(&$credentials['user_login'], &$credentials['user_password']));
42
43         if ( '' === $secure_cookie )
44                 $secure_cookie = is_ssl();
45
46         $secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, $credentials);
47
48         global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
49         $auth_secure_cookie = $secure_cookie;
50
51         add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
52
53         $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
54
55         if ( is_wp_error($user) ) {
56                 if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
57                         $user = new WP_Error('', '');
58                 }
59
60                 return $user;
61         }
62
63         wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
64         do_action('wp_login', $user->user_login, $user);
65         return $user;
66 }
67
68 /**
69  * Authenticate the user using the username and password.
70  */
71 add_filter('authenticate', 'wp_authenticate_username_password', 20, 3);
72 function wp_authenticate_username_password($user, $username, $password) {
73         if ( is_a($user, 'WP_User') ) { return $user; }
74
75         if ( empty($username) || empty($password) ) {
76                 $error = new WP_Error();
77
78                 if ( empty($username) )
79                         $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
80
81                 if ( empty($password) )
82                         $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
83
84                 return $error;
85         }
86
87         $user = get_user_by('login', $username);
88
89         if ( !$user )
90                 return new WP_Error( 'invalid_username', sprintf( __( '<strong>ERROR</strong>: Invalid username. <a href="%s" title="Password Lost and Found">Lost your password</a>?' ), wp_lostpassword_url() ) );
91
92         if ( is_multisite() ) {
93                 // Is user marked as spam?
94                 if ( 1 == $user->spam )
95                         return new WP_Error( 'spammer_account', __( '<strong>ERROR</strong>: Your account has been marked as a spammer.' ) );
96
97                 // Is a user's blog marked as spam?
98                 if ( !is_super_admin( $user->ID ) && isset( $user->primary_blog ) ) {
99                         $details = get_blog_details( $user->primary_blog );
100                         if ( is_object( $details ) && $details->spam == 1 )
101                                 return new WP_Error( 'blog_suspended', __( 'Site Suspended.' ) );
102                 }
103         }
104
105         $user = apply_filters('wp_authenticate_user', $user, $password);
106         if ( is_wp_error($user) )
107                 return $user;
108
109         if ( !wp_check_password($password, $user->user_pass, $user->ID) )
110                 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" title="Password Lost and Found">Lost your password</a>?' ),
111                 $username, wp_lostpassword_url() ) );
112
113         return $user;
114 }
115
116 /**
117  * Authenticate the user using the WordPress auth cookie.
118  */
119 function wp_authenticate_cookie($user, $username, $password) {
120         if ( is_a($user, 'WP_User') ) { return $user; }
121
122         if ( empty($username) && empty($password) ) {
123                 $user_id = wp_validate_auth_cookie();
124                 if ( $user_id )
125                         return new WP_User($user_id);
126
127                 global $auth_secure_cookie;
128
129                 if ( $auth_secure_cookie )
130                         $auth_cookie = SECURE_AUTH_COOKIE;
131                 else
132                         $auth_cookie = AUTH_COOKIE;
133
134                 if ( !empty($_COOKIE[$auth_cookie]) )
135                         return new WP_Error('expired_session', __('Please log in again.'));
136
137                 // If the cookie is not set, be silent.
138         }
139
140         return $user;
141 }
142
143 /**
144  * Number of posts user has written.
145  *
146  * @since 3.0.0
147  * @uses $wpdb WordPress database object for queries.
148  *
149  * @param int $userid User ID.
150  * @return int Amount of posts user has written.
151  */
152 function count_user_posts($userid) {
153         global $wpdb;
154
155         $where = get_posts_by_author_sql('post', true, $userid);
156
157         $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
158
159         return apply_filters('get_usernumposts', $count, $userid);
160 }
161
162 /**
163  * Number of posts written by a list of users.
164  *
165  * @since 3.0.0
166  *
167  * @param array $users Array of user IDs.
168  * @param string $post_type Optional. Post type to check. Defaults to post.
169  * @param bool $public_only Optional. Only return counts for public posts.  Defaults to false.
170  * @return array Amount of posts each user has written.
171  */
172 function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
173         global $wpdb;
174
175         $count = array();
176         if ( empty( $users ) || ! is_array( $users ) )
177                 return $count;
178
179         $userlist = implode( ',', array_map( 'absint', $users ) );
180         $where = get_posts_by_author_sql( $post_type, true, null, $public_only );
181
182         $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
183         foreach ( $result as $row ) {
184                 $count[ $row[0] ] = $row[1];
185         }
186
187         foreach ( $users as $id ) {
188                 if ( ! isset( $count[ $id ] ) )
189                         $count[ $id ] = 0;
190         }
191
192         return $count;
193 }
194
195 //
196 // User option functions
197 //
198
199 /**
200  * Get the current user's ID
201  *
202  * @since MU
203  *
204  * @uses wp_get_current_user
205  *
206  * @return int The current user's ID
207  */
208 function get_current_user_id() {
209         $user = wp_get_current_user();
210         return ( isset( $user->ID ) ? (int) $user->ID : 0 );
211 }
212
213 /**
214  * Retrieve user option that can be either per Site or per Network.
215  *
216  * If the user ID is not given, then the current user will be used instead. If
217  * the user ID is given, then the user data will be retrieved. The filter for
218  * the result, will also pass the original option name and finally the user data
219  * object as the third parameter.
220  *
221  * The option will first check for the per site name and then the per Network name.
222  *
223  * @since 2.0.0
224  * @uses $wpdb WordPress database object for queries.
225  * @uses apply_filters() Calls 'get_user_option_$option' hook with result,
226  *              option parameter, and user data object.
227  *
228  * @param string $option User option name.
229  * @param int $user Optional. User ID.
230  * @param bool $deprecated Use get_option() to check for an option in the options table.
231  * @return mixed
232  */
233 function get_user_option( $option, $user = 0, $deprecated = '' ) {
234         global $wpdb;
235
236         if ( !empty( $deprecated ) )
237                 _deprecated_argument( __FUNCTION__, '3.0' );
238
239         if ( empty( $user ) )
240                 $user = get_current_user_id();
241
242         if ( ! $user = get_userdata( $user ) )
243                 return false;
244
245         if ( $user->has_prop( $wpdb->prefix . $option ) ) // Blog specific
246                 $result = $user->get( $wpdb->prefix . $option );
247         elseif ( $user->has_prop( $option ) ) // User specific and cross-blog
248                 $result = $user->get( $option );
249         else
250                 $result = false;
251
252         return apply_filters("get_user_option_{$option}", $result, $option, $user);
253 }
254
255 /**
256  * Update user option with global blog capability.
257  *
258  * User options are just like user metadata except that they have support for
259  * global blog options. If the 'global' parameter is false, which it is by default
260  * it will prepend the WordPress table prefix to the option name.
261  *
262  * Deletes the user option if $newvalue is empty.
263  *
264  * @since 2.0.0
265  * @uses $wpdb WordPress database object for queries
266  *
267  * @param int $user_id User ID
268  * @param string $option_name User option name.
269  * @param mixed $newvalue User option value.
270  * @param bool $global Optional. Whether option name is global or blog specific. Default false (blog specific).
271  * @return unknown
272  */
273 function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
274         global $wpdb;
275
276         if ( !$global )
277                 $option_name = $wpdb->prefix . $option_name;
278
279         return update_user_meta( $user_id, $option_name, $newvalue );
280 }
281
282 /**
283  * Delete user option with global blog capability.
284  *
285  * User options are just like user metadata except that they have support for
286  * global blog options. If the 'global' parameter is false, which it is by default
287  * it will prepend the WordPress table prefix to the option name.
288  *
289  * @since 3.0.0
290  * @uses $wpdb WordPress database object for queries
291  *
292  * @param int $user_id User ID
293  * @param string $option_name User option name.
294  * @param bool $global Optional. Whether option name is global or blog specific. Default false (blog specific).
295  * @return unknown
296  */
297 function delete_user_option( $user_id, $option_name, $global = false ) {
298         global $wpdb;
299
300         if ( !$global )
301                 $option_name = $wpdb->prefix . $option_name;
302         return delete_user_meta( $user_id, $option_name );
303 }
304
305 /**
306  * WordPress User Query class.
307  *
308  * @since 3.1.0
309  */
310 class WP_User_Query {
311
312         /**
313          * Query vars, after parsing
314          *
315          * @since 3.5.0
316          * @access public
317          * @var array
318          */
319         var $query_vars = array();
320
321         /**
322          * List of found user ids
323          *
324          * @since 3.1.0
325          * @access private
326          * @var array
327          */
328         var $results;
329
330         /**
331          * Total number of found users for the current query
332          *
333          * @since 3.1.0
334          * @access private
335          * @var int
336          */
337         var $total_users = 0;
338
339         // SQL clauses
340         var $query_fields;
341         var $query_from;
342         var $query_where;
343         var $query_orderby;
344         var $query_limit;
345
346         /**
347          * PHP5 constructor
348          *
349          * @since 3.1.0
350          *
351          * @param string|array $args The query variables
352          * @return WP_User_Query
353          */
354         function __construct( $query = null ) {
355                 if ( !empty( $query ) ) {
356                         $this->query_vars = wp_parse_args( $query, array(
357                                 'blog_id' => $GLOBALS['blog_id'],
358                                 'role' => '',
359                                 'meta_key' => '',
360                                 'meta_value' => '',
361                                 'meta_compare' => '',
362                                 'include' => array(),
363                                 'exclude' => array(),
364                                 'search' => '',
365                                 'search_columns' => array(),
366                                 'orderby' => 'login',
367                                 'order' => 'ASC',
368                                 'offset' => '',
369                                 'number' => '',
370                                 'count_total' => true,
371                                 'fields' => 'all',
372                                 'who' => ''
373                         ) );
374
375                         $this->prepare_query();
376                         $this->query();
377                 }
378         }
379
380         /**
381          * Prepare the query variables
382          *
383          * @since 3.1.0
384          * @access private
385          */
386         function prepare_query() {
387                 global $wpdb;
388
389                 $qv =& $this->query_vars;
390
391                 if ( is_array( $qv['fields'] ) ) {
392                         $qv['fields'] = array_unique( $qv['fields'] );
393
394                         $this->query_fields = array();
395                         foreach ( $qv['fields'] as $field ) {
396                                 $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
397                                 $this->query_fields[] = "$wpdb->users.$field";
398                         }
399                         $this->query_fields = implode( ',', $this->query_fields );
400                 } elseif ( 'all' == $qv['fields'] ) {
401                         $this->query_fields = "$wpdb->users.*";
402                 } else {
403                         $this->query_fields = "$wpdb->users.ID";
404                 }
405
406                 if ( $qv['count_total'] )
407                         $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
408
409                 $this->query_from = "FROM $wpdb->users";
410                 $this->query_where = "WHERE 1=1";
411
412                 // sorting
413                 if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) {
414                         $orderby = 'user_' . $qv['orderby'];
415                 } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) {
416                         $orderby = $qv['orderby'];
417                 } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) {
418                         $orderby = 'display_name';
419                 } elseif ( 'post_count' == $qv['orderby'] ) {
420                         // todo: avoid the JOIN
421                         $where = get_posts_by_author_sql('post');
422                         $this->query_from .= " LEFT OUTER JOIN (
423                                 SELECT post_author, COUNT(*) as post_count
424                                 FROM $wpdb->posts
425                                 $where
426                                 GROUP BY post_author
427                         ) p ON ({$wpdb->users}.ID = p.post_author)
428                         ";
429                         $orderby = 'post_count';
430                 } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
431                         $orderby = 'ID';
432                 } else {
433                         $orderby = 'user_login';
434                 }
435
436                 $qv['order'] = strtoupper( $qv['order'] );
437                 if ( 'ASC' == $qv['order'] )
438                         $order = 'ASC';
439                 else
440                         $order = 'DESC';
441                 $this->query_orderby = "ORDER BY $orderby $order";
442
443                 // limit
444                 if ( $qv['number'] ) {
445                         if ( $qv['offset'] )
446                                 $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
447                         else
448                                 $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
449                 }
450
451                 $search = trim( $qv['search'] );
452                 if ( $search ) {
453                         $leading_wild = ( ltrim($search, '*') != $search );
454                         $trailing_wild = ( rtrim($search, '*') != $search );
455                         if ( $leading_wild && $trailing_wild )
456                                 $wild = 'both';
457                         elseif ( $leading_wild )
458                                 $wild = 'leading';
459                         elseif ( $trailing_wild )
460                                 $wild = 'trailing';
461                         else
462                                 $wild = false;
463                         if ( $wild )
464                                 $search = trim($search, '*');
465
466                         $search_columns = array();
467                         if ( $qv['search_columns'] )
468                                 $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
469                         if ( ! $search_columns ) {
470                                 if ( false !== strpos( $search, '@') )
471                                         $search_columns = array('user_email');
472                                 elseif ( is_numeric($search) )
473                                         $search_columns = array('user_login', 'ID');
474                                 elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
475                                         $search_columns = array('user_url');
476                                 else
477                                         $search_columns = array('user_login', 'user_nicename');
478                         }
479
480                         $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
481
482                         $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
483                 }
484
485                 $blog_id = absint( $qv['blog_id'] );
486
487                 if ( 'authors' == $qv['who'] && $blog_id ) {
488                         $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
489                         $qv['meta_value'] = 0;
490                         $qv['meta_compare'] = '!=';
491                         $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
492                 }
493
494                 $role = trim( $qv['role'] );
495
496                 if ( $blog_id && ( $role || is_multisite() ) ) {
497                         $cap_meta_query = array();
498                         $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
499
500                         if ( $role ) {
501                                 $cap_meta_query['value'] = '"' . $role . '"';
502                                 $cap_meta_query['compare'] = 'like';
503                         }
504
505                         $qv['meta_query'][] = $cap_meta_query;
506                 }
507
508                 $meta_query = new WP_Meta_Query();
509                 $meta_query->parse_query_vars( $qv );
510
511                 if ( !empty( $meta_query->queries ) ) {
512                         $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
513                         $this->query_from .= $clauses['join'];
514                         $this->query_where .= $clauses['where'];
515
516                         if ( 'OR' == $meta_query->relation )
517                                 $this->query_fields = 'DISTINCT ' . $this->query_fields;
518                 }
519
520                 if ( !empty( $qv['include'] ) ) {
521                         $ids = implode( ',', wp_parse_id_list( $qv['include'] ) );
522                         $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
523                 } elseif ( !empty($qv['exclude']) ) {
524                         $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
525                         $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
526                 }
527
528                 do_action_ref_array( 'pre_user_query', array( &$this ) );
529         }
530
531         /**
532          * Execute the query, with the current variables
533          *
534          * @since 3.1.0
535          * @access private
536          */
537         function query() {
538                 global $wpdb;
539
540                 $qv =& $this->query_vars;
541
542                 if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
543                         $this->results = $wpdb->get_results("SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit");
544                 } else {
545                         $this->results = $wpdb->get_col("SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit");
546                 }
547
548                 if ( $qv['count_total'] )
549                         $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
550
551                 if ( !$this->results )
552                         return;
553
554                 if ( 'all_with_meta' == $qv['fields'] ) {
555                         cache_users( $this->results );
556
557                         $r = array();
558                         foreach ( $this->results as $userid )
559                                 $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
560
561                         $this->results = $r;
562                 } elseif ( 'all' == $qv['fields'] ) {
563                         foreach ( $this->results as $key => $user ) {
564                                 $this->results[ $key ] = new WP_User( $user );
565                         }
566                 }
567         }
568
569         /**
570          * Retrieve query variable.
571          *
572          * @since 3.5.0
573          * @access public
574          *
575          * @param string $query_var Query variable key.
576          * @return mixed
577          */
578         function get( $query_var ) {
579                 if ( isset( $this->query_vars[$query_var] ) )
580                         return $this->query_vars[$query_var];
581
582                 return null;
583         }
584
585         /**
586          * Set query variable.
587          *
588          * @since 3.5.0
589          * @access public
590          *
591          * @param string $query_var Query variable key.
592          * @param mixed $value Query variable value.
593          */
594         function set( $query_var, $value ) {
595                 $this->query_vars[$query_var] = $value;
596         }
597
598         /*
599          * Used internally to generate an SQL string for searching across multiple columns
600          *
601          * @access protected
602          * @since 3.1.0
603          *
604          * @param string $string
605          * @param array $cols
606          * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for
607          *  single site. Single site allows leading and trailing wildcards, Network Admin only trailing.
608          * @return string
609          */
610         function get_search_sql( $string, $cols, $wild = false ) {
611                 $string = esc_sql( $string );
612
613                 $searches = array();
614                 $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
615                 $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
616                 foreach ( $cols as $col ) {
617                         if ( 'ID' == $col )
618                                 $searches[] = "$col = '$string'";
619                         else
620                                 $searches[] = "$col LIKE '$leading_wild" . like_escape($string) . "$trailing_wild'";
621                 }
622
623                 return ' AND (' . implode(' OR ', $searches) . ')';
624         }
625
626         /**
627          * Return the list of users
628          *
629          * @since 3.1.0
630          * @access public
631          *
632          * @return array
633          */
634         function get_results() {
635                 return $this->results;
636         }
637
638         /**
639          * Return the total number of users for the current query
640          *
641          * @since 3.1.0
642          * @access public
643          *
644          * @return array
645          */
646         function get_total() {
647                 return $this->total_users;
648         }
649 }
650
651 /**
652  * Retrieve list of users matching criteria.
653  *
654  * @since 3.1.0
655  * @uses $wpdb
656  * @uses WP_User_Query See for default arguments and information.
657  *
658  * @param array $args Optional.
659  * @return array List of users.
660  */
661 function get_users( $args = array() ) {
662
663         $args = wp_parse_args( $args );
664         $args['count_total'] = false;
665
666         $user_search = new WP_User_Query($args);
667
668         return (array) $user_search->get_results();
669 }
670
671 /**
672  * Get the blogs a user belongs to.
673  *
674  * @since 3.0.0
675  *
676  * @param int $user_id User ID
677  * @param bool $all Whether to retrieve all blogs, or only blogs that are not marked as deleted, archived, or spam.
678  * @return array A list of the user's blogs. An empty array if the user doesn't exist or belongs to no blogs.
679  */
680 function get_blogs_of_user( $user_id, $all = false ) {
681         global $wpdb;
682
683         $user_id = (int) $user_id;
684
685         // Logged out users can't have blogs
686         if ( empty( $user_id ) )
687                 return array();
688
689         $keys = get_user_meta( $user_id );
690         if ( empty( $keys ) )
691                 return array();
692
693         if ( ! is_multisite() ) {
694                 $blog_id = get_current_blog_id();
695                 $blogs = array( $blog_id => new stdClass );
696                 $blogs[ $blog_id ]->userblog_id = $blog_id;
697                 $blogs[ $blog_id ]->blogname = get_option('blogname');
698                 $blogs[ $blog_id ]->domain = '';
699                 $blogs[ $blog_id ]->path = '';
700                 $blogs[ $blog_id ]->site_id = 1;
701                 $blogs[ $blog_id ]->siteurl = get_option('siteurl');
702                 $blogs[ $blog_id ]->archived = 0;
703                 $blogs[ $blog_id ]->spam = 0;
704                 $blogs[ $blog_id ]->deleted = 0;
705                 return $blogs;
706         }
707
708         $blogs = array();
709
710         if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
711                 $blog = get_blog_details( 1 );
712                 if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
713                         $blogs[ 1 ] = (object) array(
714                                 'userblog_id' => 1,
715                                 'blogname'    => $blog->blogname,
716                                 'domain'      => $blog->domain,
717                                 'path'        => $blog->path,
718                                 'site_id'     => $blog->site_id,
719                                 'siteurl'     => $blog->siteurl,
720                                 'archived'    => 0,
721                                 'spam'        => 0,
722                                 'deleted'     => 0
723                         );
724                 }
725                 unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
726         }
727
728         $keys = array_keys( $keys );
729
730         foreach ( $keys as $key ) {
731                 if ( 'capabilities' !== substr( $key, -12 ) )
732                         continue;
733                 if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) )
734                         continue;
735                 $blog_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
736                 if ( ! is_numeric( $blog_id ) )
737                         continue;
738
739                 $blog_id = (int) $blog_id;
740                 $blog = get_blog_details( $blog_id );
741                 if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
742                         $blogs[ $blog_id ] = (object) array(
743                                 'userblog_id' => $blog_id,
744                                 'blogname'    => $blog->blogname,
745                                 'domain'      => $blog->domain,
746                                 'path'        => $blog->path,
747                                 'site_id'     => $blog->site_id,
748                                 'siteurl'     => $blog->siteurl,
749                                 'archived'    => 0,
750                                 'spam'        => 0,
751                                 'deleted'     => 0
752                         );
753                 }
754         }
755
756         return apply_filters( 'get_blogs_of_user', $blogs, $user_id, $all );
757 }
758
759 /**
760  * Find out whether a user is a member of a given blog.
761  *
762  * @since MU 1.1
763  * @uses get_blogs_of_user()
764  *
765  * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
766  * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
767  * @return bool
768  */
769 function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
770         $user_id = (int) $user_id;
771         $blog_id = (int) $blog_id;
772
773         if ( empty( $user_id ) )
774                 $user_id = get_current_user_id();
775
776         if ( empty( $blog_id ) )
777                 $blog_id = get_current_blog_id();
778
779         $blogs = get_blogs_of_user( $user_id );
780         return array_key_exists( $blog_id, $blogs );
781 }
782
783 /**
784  * Add meta data field to a user.
785  *
786  * Post meta data is called "Custom Fields" on the Administration Screens.
787  *
788  * @since 3.0.0
789  * @uses add_metadata()
790  * @link http://codex.wordpress.org/Function_Reference/add_user_meta
791  *
792  * @param int $user_id Post ID.
793  * @param string $meta_key Metadata name.
794  * @param mixed $meta_value Metadata value.
795  * @param bool $unique Optional, default is false. Whether the same key should not be added.
796  * @return int|bool Meta ID on success, false on failure.
797  */
798 function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
799         return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
800 }
801
802 /**
803  * Remove metadata matching criteria from a user.
804  *
805  * You can match based on the key, or key and value. Removing based on key and
806  * value, will keep from removing duplicate metadata with the same key. It also
807  * allows removing all metadata matching key, if needed.
808  *
809  * @since 3.0.0
810  * @uses delete_metadata()
811  * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
812  *
813  * @param int $user_id user ID
814  * @param string $meta_key Metadata name.
815  * @param mixed $meta_value Optional. Metadata value.
816  * @return bool True on success, false on failure.
817  */
818 function delete_user_meta($user_id, $meta_key, $meta_value = '') {
819         return delete_metadata('user', $user_id, $meta_key, $meta_value);
820 }
821
822 /**
823  * Retrieve user meta field for a user.
824  *
825  * @since 3.0.0
826  * @uses get_metadata()
827  * @link http://codex.wordpress.org/Function_Reference/get_user_meta
828  *
829  * @param int $user_id Post ID.
830  * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
831  * @param bool $single Whether to return a single value.
832  * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
833  *  is true.
834  */
835 function get_user_meta($user_id, $key = '', $single = false) {
836         return get_metadata('user', $user_id, $key, $single);
837 }
838
839 /**
840  * Update user meta field based on user ID.
841  *
842  * Use the $prev_value parameter to differentiate between meta fields with the
843  * same key and user ID.
844  *
845  * If the meta field for the user does not exist, it will be added.
846  *
847  * @since 3.0.0
848  * @uses update_metadata
849  * @link http://codex.wordpress.org/Function_Reference/update_user_meta
850  *
851  * @param int $user_id Post ID.
852  * @param string $meta_key Metadata key.
853  * @param mixed $meta_value Metadata value.
854  * @param mixed $prev_value Optional. Previous value to check before removing.
855  * @return bool True on success, false on failure.
856  */
857 function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
858         return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
859 }
860
861 /**
862  * Count number of users who have each of the user roles.
863  *
864  * Assumes there are neither duplicated nor orphaned capabilities meta_values.
865  * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
866  * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
867  * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
868  *
869  * @since 3.0.0
870  * @param string $strategy 'time' or 'memory'
871  * @return array Includes a grand total and an array of counts indexed by role strings.
872  */
873 function count_users($strategy = 'time') {
874         global $wpdb, $wp_roles;
875
876         // Initialize
877         $id = get_current_blog_id();
878         $blog_prefix = $wpdb->get_blog_prefix($id);
879         $result = array();
880
881         if ( 'time' == $strategy ) {
882                 global $wp_roles;
883
884                 if ( ! isset( $wp_roles ) )
885                         $wp_roles = new WP_Roles();
886
887                 $avail_roles = $wp_roles->get_names();
888
889                 // Build a CPU-intensive query that will return concise information.
890                 $select_count = array();
891                 foreach ( $avail_roles as $this_role => $name ) {
892                         $select_count[] = "COUNT(NULLIF(`meta_value` LIKE '%\"" . like_escape( $this_role ) . "\"%', false))";
893                 }
894                 $select_count = implode(', ', $select_count);
895
896                 // Add the meta_value index to the selection list, then run the query.
897                 $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
898
899                 // Run the previous loop again to associate results with role names.
900                 $col = 0;
901                 $role_counts = array();
902                 foreach ( $avail_roles as $this_role => $name ) {
903                         $count = (int) $row[$col++];
904                         if ($count > 0) {
905                                 $role_counts[$this_role] = $count;
906                         }
907                 }
908
909                 // Get the meta_value index from the end of the result set.
910                 $total_users = (int) $row[$col];
911
912                 $result['total_users'] = $total_users;
913                 $result['avail_roles'] =& $role_counts;
914         } else {
915                 $avail_roles = array();
916
917                 $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
918
919                 foreach ( $users_of_blog as $caps_meta ) {
920                         $b_roles = maybe_unserialize($caps_meta);
921                         if ( ! is_array( $b_roles ) )
922                                 continue;
923                         foreach ( $b_roles as $b_role => $val ) {
924                                 if ( isset($avail_roles[$b_role]) ) {
925                                         $avail_roles[$b_role]++;
926                                 } else {
927                                         $avail_roles[$b_role] = 1;
928                                 }
929                         }
930                 }
931
932                 $result['total_users'] = count( $users_of_blog );
933                 $result['avail_roles'] =& $avail_roles;
934         }
935
936         return $result;
937 }
938
939 //
940 // Private helper functions
941 //
942
943 /**
944  * Set up global user vars.
945  *
946  * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
947  *
948  * @since 2.0.4
949  * @global string $userdata User description.
950  * @global string $user_login The user username for logging in
951  * @global int $user_level The level of the user
952  * @global int $user_ID The ID of the user
953  * @global string $user_email The email address of the user
954  * @global string $user_url The url in the user's profile
955  * @global string $user_identity The display name of the user
956  *
957  * @param int $for_user_id Optional. User ID to set up global data.
958  */
959 function setup_userdata($for_user_id = '') {
960         global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
961
962         if ( '' == $for_user_id )
963                 $for_user_id = get_current_user_id();
964         $user = get_userdata( $for_user_id );
965
966         if ( ! $user ) {
967                 $user_ID = 0;
968                 $user_level = 0;
969                 $userdata = null;
970                 $user_login = $user_email = $user_url = $user_identity = '';
971                 return;
972         }
973
974         $user_ID    = (int) $user->ID;
975         $user_level = (int) $user->user_level;
976         $userdata   = $user;
977         $user_login = $user->user_login;
978         $user_email = $user->user_email;
979         $user_url   = $user->user_url;
980         $user_identity = $user->display_name;
981 }
982
983 /**
984  * Create dropdown HTML content of users.
985  *
986  * The content can either be displayed, which it is by default or retrieved by
987  * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
988  * need to be used; all users will be displayed in that case. Only one can be
989  * used, either 'include' or 'exclude', but not both.
990  *
991  * The available arguments are as follows:
992  * <ol>
993  * <li>show_option_all - Text to show all and whether HTML option exists.</li>
994  * <li>show_option_none - Text for show none and whether HTML option exists.</li>
995  * <li>hide_if_only_one_author - Don't create the dropdown if there is only one user.</li>
996  * <li>orderby - SQL order by clause for what order the users appear. Default is 'display_name'.</li>
997  * <li>order - Default is 'ASC'. Can also be 'DESC'.</li>
998  * <li>include - User IDs to include.</li>
999  * <li>exclude - User IDs to exclude.</li>
1000  * <li>multi - Default is 'false'. Whether to skip the ID attribute on the 'select' element. A 'true' value is overridden when id argument is set.</li>
1001  * <li>show - Default is 'display_name'. User table column to display. If the selected item is empty then the user_login will be displayed in parentheses</li>
1002  * <li>echo - Default is '1'. Whether to display or retrieve content.</li>
1003  * <li>selected - Which User ID is selected.</li>
1004  * <li>include_selected - Always include the selected user ID in the dropdown. Default is false.</li>
1005  * <li>name - Default is 'user'. Name attribute of select element.</li>
1006  * <li>id - Default is the value of the 'name' parameter. ID attribute of select element.</li>
1007  * <li>class - Class attribute of select element.</li>
1008  * <li>blog_id - ID of blog (Multisite only). Defaults to ID of current blog.</li>
1009  * <li>who - Which users to query. Currently only 'authors' is supported. Default is all users.</li>
1010  * </ol>
1011  *
1012  * @since 2.3.0
1013  * @uses $wpdb WordPress database object for queries
1014  *
1015  * @param string|array $args Optional. Override defaults.
1016  * @return string|null Null on display. String of HTML content on retrieve.
1017  */
1018 function wp_dropdown_users( $args = '' ) {
1019         $defaults = array(
1020                 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '',
1021                 'orderby' => 'display_name', 'order' => 'ASC',
1022                 'include' => '', 'exclude' => '', 'multi' => 0,
1023                 'show' => 'display_name', 'echo' => 1,
1024                 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '',
1025                 'blog_id' => $GLOBALS['blog_id'], 'who' => '', 'include_selected' => false
1026         );
1027
1028         $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
1029
1030         $r = wp_parse_args( $args, $defaults );
1031         extract( $r, EXTR_SKIP );
1032
1033         $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who' ) );
1034         $query_args['fields'] = array( 'ID', 'user_login', $show );
1035         $users = get_users( $query_args );
1036
1037         $output = '';
1038         if ( !empty($users) && ( empty($hide_if_only_one_author) || count($users) > 1 ) ) {
1039                 $name = esc_attr( $name );
1040                 if ( $multi && ! $id )
1041                         $id = '';
1042                 else
1043                         $id = $id ? " id='" . esc_attr( $id ) . "'" : " id='$name'";
1044
1045                 $output = "<select name='{$name}'{$id} class='$class'>\n";
1046
1047                 if ( $show_option_all )
1048                         $output .= "\t<option value='0'>$show_option_all</option>\n";
1049
1050                 if ( $show_option_none ) {
1051                         $_selected = selected( -1, $selected, false );
1052                         $output .= "\t<option value='-1'$_selected>$show_option_none</option>\n";
1053                 }
1054
1055                 $found_selected = false;
1056                 foreach ( (array) $users as $user ) {
1057                         $user->ID = (int) $user->ID;
1058                         $_selected = selected( $user->ID, $selected, false );
1059                         if ( $_selected )
1060                                 $found_selected = true;
1061                         $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
1062                         $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n";
1063                 }
1064
1065                 if ( $include_selected && ! $found_selected && ( $selected > 0 ) ) {
1066                         $user = get_userdata( $selected );
1067                         $_selected = selected( $user->ID, $selected, false );
1068                         $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
1069                         $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n";
1070                 }
1071
1072                 $output .= "</select>";
1073         }
1074
1075         $output = apply_filters('wp_dropdown_users', $output);
1076
1077         if ( $echo )
1078                 echo $output;
1079
1080         return $output;
1081 }
1082
1083 /**
1084  * Sanitize user field based on context.
1085  *
1086  * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1087  * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1088  * when calling filters.
1089  *
1090  * @since 2.3.0
1091  * @uses apply_filters() Calls 'edit_$field' passing $value and $user_id if $context == 'edit'.
1092  *  $field is prefixed with 'user_' if it isn't already.
1093  * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db'. $field is prefixed with
1094  *  'user_' if it isn't already.
1095  * @uses apply_filters() Calls '$field' passing $value, $user_id and $context if $context == anything
1096  *  other than 'raw', 'edit' and 'db'. $field is prefixed with 'user_' if it isn't already.
1097  *
1098  * @param string $field The user Object field name.
1099  * @param mixed $value The user Object value.
1100  * @param int $user_id user ID.
1101  * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
1102  *               'attribute' and 'js'.
1103  * @return mixed Sanitized value.
1104  */
1105 function sanitize_user_field($field, $value, $user_id, $context) {
1106         $int_fields = array('ID');
1107         if ( in_array($field, $int_fields) )
1108                 $value = (int) $value;
1109
1110         if ( 'raw' == $context )
1111                 return $value;
1112
1113         if ( !is_string($value) && !is_numeric($value) )
1114                 return $value;
1115
1116         $prefixed = false !== strpos( $field, 'user_' );
1117
1118         if ( 'edit' == $context ) {
1119                 if ( $prefixed ) {
1120                         $value = apply_filters("edit_{$field}", $value, $user_id);
1121                 } else {
1122                         $value = apply_filters("edit_user_{$field}", $value, $user_id);
1123                 }
1124
1125                 if ( 'description' == $field )
1126                         $value = esc_html( $value ); // textarea_escaped?
1127                 else
1128                         $value = esc_attr($value);
1129         } else if ( 'db' == $context ) {
1130                 if ( $prefixed ) {
1131                         $value = apply_filters("pre_{$field}", $value);
1132                 } else {
1133                         $value = apply_filters("pre_user_{$field}", $value);
1134                 }
1135         } else {
1136                 // Use display filters by default.
1137                 if ( $prefixed )
1138                         $value = apply_filters($field, $value, $user_id, $context);
1139                 else
1140                         $value = apply_filters("user_{$field}", $value, $user_id, $context);
1141         }
1142
1143         if ( 'user_url' == $field )
1144                 $value = esc_url($value);
1145
1146         if ( 'attribute' == $context )
1147                 $value = esc_attr($value);
1148         else if ( 'js' == $context )
1149                 $value = esc_js($value);
1150
1151         return $value;
1152 }
1153
1154 /**
1155  * Update all user caches
1156  *
1157  * @since 3.0.0
1158  *
1159  * @param object $user User object to be cached
1160  */
1161 function update_user_caches($user) {
1162         wp_cache_add($user->ID, $user, 'users');
1163         wp_cache_add($user->user_login, $user->ID, 'userlogins');
1164         wp_cache_add($user->user_email, $user->ID, 'useremail');
1165         wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
1166 }
1167
1168 /**
1169  * Clean all user caches
1170  *
1171  * @since 3.0.0
1172  *
1173  * @param WP_User|int $user User object or ID to be cleaned from the cache
1174  */
1175 function clean_user_cache( $user ) {
1176         if ( is_numeric( $user ) )
1177                 $user = new WP_User( $user );
1178
1179         if ( ! $user->exists() )
1180                 return;
1181
1182         wp_cache_delete( $user->ID, 'users' );
1183         wp_cache_delete( $user->user_login, 'userlogins' );
1184         wp_cache_delete( $user->user_email, 'useremail' );
1185         wp_cache_delete( $user->user_nicename, 'userslugs' );
1186 }
1187
1188 /**
1189  * Checks whether the given username exists.
1190  *
1191  * @since 2.0.0
1192  *
1193  * @param string $username Username.
1194  * @return null|int The user's ID on success, and null on failure.
1195  */
1196 function username_exists( $username ) {
1197         if ( $user = get_user_by('login', $username ) ) {
1198                 return $user->ID;
1199         } else {
1200                 return null;
1201         }
1202 }
1203
1204 /**
1205  * Checks whether the given email exists.
1206  *
1207  * @since 2.1.0
1208  * @uses $wpdb
1209  *
1210  * @param string $email Email.
1211  * @return bool|int The user's ID on success, and false on failure.
1212  */
1213 function email_exists( $email ) {
1214         if ( $user = get_user_by('email', $email) )
1215                 return $user->ID;
1216
1217         return false;
1218 }
1219
1220 /**
1221  * Checks whether an username is valid.
1222  *
1223  * @since 2.0.1
1224  * @uses apply_filters() Calls 'validate_username' hook on $valid check and $username as parameters
1225  *
1226  * @param string $username Username.
1227  * @return bool Whether username given is valid
1228  */
1229 function validate_username( $username ) {
1230         $sanitized = sanitize_user( $username, true );
1231         $valid = ( $sanitized == $username );
1232         return apply_filters( 'validate_username', $valid, $username );
1233 }
1234
1235 /**
1236  * Insert an user into the database.
1237  *
1238  * Can update a current user or insert a new user based on whether the user's ID
1239  * is present.
1240  *
1241  * Can be used to update the user's info (see below), set the user's role, and
1242  * set the user's preference on whether they want the rich editor on.
1243  *
1244  * Most of the $userdata array fields have filters associated with the values.
1245  * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
1246  * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
1247  * by the field name. An example using 'description' would have the filter
1248  * called, 'pre_user_description' that can be hooked into.
1249  *
1250  * The $userdata array can contain the following fields:
1251  * 'ID' - An integer that will be used for updating an existing user.
1252  * 'user_pass' - A string that contains the plain text password for the user.
1253  * 'user_login' - A string that contains the user's username for logging in.
1254  * 'user_nicename' - A string that contains a URL-friendly name for the user.
1255  *              The default is the user's username.
1256  * 'user_url' - A string containing the user's URL for the user's web site.
1257  * 'user_email' - A string containing the user's email address.
1258  * 'display_name' - A string that will be shown on the site. Defaults to user's
1259  *              username. It is likely that you will want to change this, for appearance.
1260  * 'nickname' - The user's nickname, defaults to the user's username.
1261  * 'first_name' - The user's first name.
1262  * 'last_name' - The user's last name.
1263  * 'description' - A string containing content about the user.
1264  * 'rich_editing' - A string for whether to enable the rich editor. False
1265  *              if not empty.
1266  * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
1267  * 'role' - A string used to set the user's role.
1268  * 'jabber' - User's Jabber account.
1269  * 'aim' - User's AOL IM account.
1270  * 'yim' - User's Yahoo IM account.
1271  *
1272  * @since 2.0.0
1273  * @uses $wpdb WordPress database layer.
1274  * @uses apply_filters() Calls filters for most of the $userdata fields with the prefix 'pre_user'. See note above.
1275  * @uses do_action() Calls 'profile_update' hook when updating giving the user's ID
1276  * @uses do_action() Calls 'user_register' hook when creating a new user giving the user's ID
1277  *
1278  * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
1279  * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created.
1280  */
1281 function wp_insert_user( $userdata ) {
1282         global $wpdb;
1283
1284         if ( is_a( $userdata, 'stdClass' ) )
1285                 $userdata = get_object_vars( $userdata );
1286         elseif ( is_a( $userdata, 'WP_User' ) )
1287                 $userdata = $userdata->to_array();
1288
1289         extract( $userdata, EXTR_SKIP );
1290
1291         // Are we updating or creating?
1292         if ( !empty($ID) ) {
1293                 $ID = (int) $ID;
1294                 $update = true;
1295                 $old_user_data = WP_User::get_data_by( 'id', $ID );
1296         } else {
1297                 $update = false;
1298                 // Hash the password
1299                 $user_pass = wp_hash_password($user_pass);
1300         }
1301
1302         $user_login = sanitize_user($user_login, true);
1303         $user_login = apply_filters('pre_user_login', $user_login);
1304
1305         //Remove any non-printable chars from the login string to see if we have ended up with an empty username
1306         $user_login = trim($user_login);
1307
1308         if ( empty($user_login) )
1309                 return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
1310
1311         if ( !$update && username_exists( $user_login ) )
1312                 return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
1313
1314         if ( empty($user_nicename) )
1315                 $user_nicename = sanitize_title( $user_login );
1316         $user_nicename = apply_filters('pre_user_nicename', $user_nicename);
1317
1318         if ( empty($user_url) )
1319                 $user_url = '';
1320         $user_url = apply_filters('pre_user_url', $user_url);
1321
1322         if ( empty($user_email) )
1323                 $user_email = '';
1324         $user_email = apply_filters('pre_user_email', $user_email);
1325
1326         if ( !$update && ! defined( 'WP_IMPORTING' ) && email_exists($user_email) )
1327                 return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
1328
1329         if ( empty($nickname) )
1330                 $nickname = $user_login;
1331         $nickname = apply_filters('pre_user_nickname', $nickname);
1332
1333         if ( empty($first_name) )
1334                 $first_name = '';
1335         $first_name = apply_filters('pre_user_first_name', $first_name);
1336
1337         if ( empty($last_name) )
1338                 $last_name = '';
1339         $last_name = apply_filters('pre_user_last_name', $last_name);
1340
1341         if ( empty( $display_name ) ) {
1342                 if ( $update )
1343                         $display_name = $user_login;
1344                 elseif ( $first_name && $last_name )
1345                         /* translators: 1: first name, 2: last name */
1346                         $display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $first_name, $last_name );
1347                 elseif ( $first_name )
1348                         $display_name = $first_name;
1349                 elseif ( $last_name )
1350                         $display_name = $last_name;
1351                 else
1352                         $display_name = $user_login;
1353         }
1354         $display_name = apply_filters( 'pre_user_display_name', $display_name );
1355
1356         if ( empty($description) )
1357                 $description = '';
1358         $description = apply_filters('pre_user_description', $description);
1359
1360         if ( empty($rich_editing) )
1361                 $rich_editing = 'true';
1362
1363         if ( empty($comment_shortcuts) )
1364                 $comment_shortcuts = 'false';
1365
1366         if ( empty($admin_color) )
1367                 $admin_color = 'fresh';
1368         $admin_color = preg_replace('|[^a-z0-9 _.\-@]|i', '', $admin_color);
1369
1370         if ( empty($use_ssl) )
1371                 $use_ssl = 0;
1372
1373         if ( empty($user_registered) )
1374                 $user_registered = gmdate('Y-m-d H:i:s');
1375
1376         if ( empty($show_admin_bar_front) )
1377                 $show_admin_bar_front = 'true';
1378
1379         $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));
1380
1381         if ( $user_nicename_check ) {
1382                 $suffix = 2;
1383                 while ($user_nicename_check) {
1384                         $alt_user_nicename = $user_nicename . "-$suffix";
1385                         $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));
1386                         $suffix++;
1387                 }
1388                 $user_nicename = $alt_user_nicename;
1389         }
1390
1391         $data = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
1392         $data = wp_unslash( $data );
1393
1394         if ( $update ) {
1395                 $wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
1396                 $user_id = (int) $ID;
1397         } else {
1398                 $wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
1399                 $user_id = (int) $wpdb->insert_id;
1400         }
1401
1402         $user = new WP_User( $user_id );
1403
1404         foreach ( _get_additional_user_keys( $user ) as $key ) {
1405                 if ( isset( $$key ) )
1406                         update_user_meta( $user_id, $key, $$key );
1407         }
1408
1409         if ( isset($role) )
1410                 $user->set_role($role);
1411         elseif ( !$update )
1412                 $user->set_role(get_option('default_role'));
1413
1414         wp_cache_delete($user_id, 'users');
1415         wp_cache_delete($user_login, 'userlogins');
1416
1417         if ( $update )
1418                 do_action('profile_update', $user_id, $old_user_data);
1419         else
1420                 do_action('user_register', $user_id);
1421
1422         return $user_id;
1423 }
1424
1425 /**
1426  * Update an user in the database.
1427  *
1428  * It is possible to update a user's password by specifying the 'user_pass'
1429  * value in the $userdata parameter array.
1430  *
1431  * If current user's password is being updated, then the cookies will be
1432  * cleared.
1433  *
1434  * @since 2.0.0
1435  * @see wp_insert_user() For what fields can be set in $userdata
1436  * @uses wp_insert_user() Used to update existing user or add new one if user doesn't exist already
1437  *
1438  * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
1439  * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
1440  */
1441 function wp_update_user($userdata) {
1442         if ( is_a( $userdata, 'stdClass' ) )
1443                 $userdata = get_object_vars( $userdata );
1444         elseif ( is_a( $userdata, 'WP_User' ) )
1445                 $userdata = $userdata->to_array();
1446
1447         $ID = (int) $userdata['ID'];
1448
1449         // First, get all of the original fields
1450         $user_obj = get_userdata( $ID );
1451         if ( ! $user_obj )
1452                 return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
1453
1454         $user = $user_obj->to_array();
1455
1456         // Add additional custom fields
1457         foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
1458                 $user[ $key ] = get_user_meta( $ID, $key, true );
1459         }
1460
1461         // Escape data pulled from DB.
1462         $user = add_magic_quotes( $user );
1463
1464         // If password is changing, hash it now.
1465         if ( ! empty($userdata['user_pass']) ) {
1466                 $plaintext_pass = $userdata['user_pass'];
1467                 $userdata['user_pass'] = wp_hash_password($userdata['user_pass']);
1468         }
1469
1470         wp_cache_delete($user[ 'user_email' ], 'useremail');
1471
1472         // Merge old and new fields with new fields overwriting old ones.
1473         $userdata = array_merge($user, $userdata);
1474         $user_id = wp_insert_user($userdata);
1475
1476         // Update the cookies if the password changed.
1477         $current_user = wp_get_current_user();
1478         if ( $current_user->ID == $ID ) {
1479                 if ( isset($plaintext_pass) ) {
1480                         wp_clear_auth_cookie();
1481                         wp_set_auth_cookie($ID);
1482                 }
1483         }
1484
1485         return $user_id;
1486 }
1487
1488 /**
1489  * A simpler way of inserting an user into the database.
1490  *
1491  * Creates a new user with just the username, password, and email. For more
1492  * complex user creation use wp_insert_user() to specify more information.
1493  *
1494  * @since 2.0.0
1495  * @see wp_insert_user() More complete way to create a new user
1496  *
1497  * @param string $username The user's username.
1498  * @param string $password The user's password.
1499  * @param string $email The user's email (optional).
1500  * @return int The new user's ID.
1501  */
1502 function wp_create_user($username, $password, $email = '') {
1503         $user_login = wp_slash( $username );
1504         $user_email = wp_slash( $email    );
1505         $user_pass = $password;
1506
1507         $userdata = compact('user_login', 'user_email', 'user_pass');
1508         return wp_insert_user($userdata);
1509 }
1510
1511 /**
1512  * Return a list of meta keys that wp_insert_user() is supposed to set.
1513  *
1514  * @since 3.3.0
1515  * @access private
1516  *
1517  * @param object $user WP_User instance.
1518  * @return array
1519  */
1520 function _get_additional_user_keys( $user ) {
1521         $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front' );
1522         return array_merge( $keys, array_keys( _wp_get_user_contactmethods( $user ) ) );
1523 }
1524
1525 /**
1526  * Set up the contact methods.
1527  *
1528  * Default contact methods were removed in 3.6. A filter dictates contact methods.
1529  *
1530  * @since 2.9.0
1531  * @access private
1532  *
1533  * @param object $user User data object (optional).
1534  * @return array $user_contactmethods Array of contact methods and their labels.
1535  */
1536 function _wp_get_user_contactmethods( $user = null ) {
1537         $user_contactmethods = array();
1538         if ( get_site_option( 'initial_db_version' ) < 23588 ) {
1539                 $user_contactmethods = array(
1540                         'aim'    => __( 'AIM' ),
1541                         'yim'    => __( 'Yahoo IM' ),
1542                         'jabber' => __( 'Jabber / Google Talk' )
1543                 );
1544         }
1545         return apply_filters( 'user_contactmethods', $user_contactmethods, $user );
1546 }