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