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