]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/user.php
Wordpress 3.0.2
[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         global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
47         $auth_secure_cookie = $secure_cookie;
48
49         add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
50
51         $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
52
53         if ( is_wp_error($user) ) {
54                 if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
55                         $user = new WP_Error('', '');
56                 }
57
58                 return $user;
59         }
60
61         wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
62         do_action('wp_login', $credentials['user_login']);
63         return $user;
64 }
65
66
67 /**
68  * Authenticate the user using the username and password.
69  */
70 add_filter('authenticate', 'wp_authenticate_username_password', 20, 3);
71 function wp_authenticate_username_password($user, $username, $password) {
72         if ( is_a($user, 'WP_User') ) { return $user; }
73
74         if ( empty($username) || empty($password) ) {
75                 $error = new WP_Error();
76
77                 if ( empty($username) )
78                         $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
79
80                 if ( empty($password) )
81                         $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
82
83                 return $error;
84         }
85
86         $userdata = get_user_by('login', $username);
87
88         if ( !$userdata )
89                 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')));
90
91         if ( is_multisite() ) {
92                 // Is user marked as spam?
93                 if ( 1 == $userdata->spam)
94                         return new WP_Error('invalid_username', __('<strong>ERROR</strong>: Your account has been marked as a spammer.'));
95
96                 // Is a user's blog marked as spam?
97                 if ( !is_super_admin( $userdata->ID ) && isset($userdata->primary_blog) ) {
98                         $details = get_blog_details( $userdata->primary_blog );
99                         if ( is_object( $details ) && $details->spam == 1 )
100                                 return new WP_Error('blog_suspended', __('Site Suspended.'));
101                 }
102         }
103
104         $userdata = apply_filters('wp_authenticate_user', $userdata, $password);
105         if ( is_wp_error($userdata) )
106                 return $userdata;
107
108         if ( !wp_check_password($password, $userdata->user_pass, $userdata->ID) )
109                 return new WP_Error('incorrect_password', sprintf(__('<strong>ERROR</strong>: Incorrect password. <a href="%s" title="Password Lost and Found">Lost your password</a>?'), site_url('wp-login.php?action=lostpassword', 'login')));
110
111         $user =  new WP_User($userdata->ID);
112         return $user;
113 }
114
115 /**
116  * Authenticate the user using the WordPress auth cookie.
117  */
118 function wp_authenticate_cookie($user, $username, $password) {
119         if ( is_a($user, 'WP_User') ) { return $user; }
120
121         if ( empty($username) && empty($password) ) {
122                 $user_id = wp_validate_auth_cookie();
123                 if ( $user_id )
124                         return new WP_User($user_id);
125
126                 global $auth_secure_cookie;
127
128                 if ( $auth_secure_cookie )
129                         $auth_cookie = SECURE_AUTH_COOKIE;
130                 else
131                         $auth_cookie = AUTH_COOKIE;
132
133                 if ( !empty($_COOKIE[$auth_cookie]) )
134                         return new WP_Error('expired_session', __('Please log in again.'));
135
136                 // If the cookie is not set, be silent.
137         }
138
139         return $user;
140 }
141
142 /**
143  * Number of posts user has written.
144  *
145  * @since 3.0.0
146  * @uses $wpdb WordPress database object for queries.
147  *
148  * @param int $userid User ID.
149  * @return int Amount of posts user has written.
150  */
151 function count_user_posts($userid) {
152         global $wpdb;
153
154         $where = get_posts_by_author_sql('post', TRUE, $userid);
155
156         $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
157
158         return apply_filters('get_usernumposts', $count, $userid);
159 }
160
161 /**
162  * Number of posts written by a list of users.
163  *
164  * @since 3.0.0
165  * @param array $userid User ID number list.
166  * @return array Amount of posts each user has written.
167  */
168 function count_many_users_posts($users) {
169         global $wpdb;
170
171         $count = array();
172         if ( ! is_array($users) || empty( $users ) )
173                 return $count;
174
175         $userlist = implode( ',', $users );
176         $where = get_posts_by_author_sql( 'post' );
177
178         $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
179         foreach ( $result as $row ) {
180                 $count[ $row[0] ] = $row[1];
181         }
182
183         foreach ( $users as $id ) {
184                 if ( ! isset( $count[ $id ] ) )
185                         $count[ $id ] = 0;
186         }
187
188         return $count;
189 }
190
191 /**
192  * Check that the user login name and password is correct.
193  *
194  * @since 0.71
195  * @todo xmlrpc only. Maybe move to xmlrpc.php.
196  *
197  * @param string $user_login User name.
198  * @param string $user_pass User password.
199  * @return bool False if does not authenticate, true if username and password authenticates.
200  */
201 function user_pass_ok($user_login, $user_pass) {
202         $user = wp_authenticate($user_login, $user_pass);
203         if ( is_wp_error($user) )
204                 return false;
205
206         return true;
207 }
208
209 //
210 // User option functions
211 //
212
213 /**
214  * Get the current user's ID
215  *
216  * @since MU
217  *
218  * @uses wp_get_current_user
219  *
220  * @return int The current user's ID
221  */
222 function get_current_user_id() {
223         $user = wp_get_current_user();
224         return ( isset( $user->ID ) ? (int) $user->ID : 0 );
225 }
226
227 /**
228  * Retrieve user option that can be either per Site or per Network.
229  *
230  * If the user ID is not given, then the current user will be used instead. If
231  * the user ID is given, then the user data will be retrieved. The filter for
232  * the result, will also pass the original option name and finally the user data
233  * object as the third parameter.
234  *
235  * The option will first check for the per site name and then the per Network name.
236  *
237  * @since 2.0.0
238  * @uses $wpdb WordPress database object for queries.
239  * @uses apply_filters() Calls 'get_user_option_$option' hook with result,
240  *              option parameter, and user data object.
241  *
242  * @param string $option User option name.
243  * @param int $user Optional. User ID.
244  * @param bool $deprecated Use get_option() to check for an option in the options table.
245  * @return mixed
246  */
247 function get_user_option( $option, $user = 0, $deprecated = '' ) {
248         global $wpdb;
249
250         if ( !empty( $deprecated ) )
251                 _deprecated_argument( __FUNCTION__, '3.0' );
252
253         if ( empty($user) ) {
254                 $user = wp_get_current_user();
255                 $user = $user->ID;
256         }
257
258         $user = get_userdata($user);
259
260         // Keys used as object vars cannot have dashes.
261         $key = str_replace('-', '', $option);
262
263         if ( isset( $user->{$wpdb->prefix . $key} ) ) // Blog specific
264                 $result = $user->{$wpdb->prefix . $key};
265         elseif ( isset( $user->{$key} ) ) // User specific and cross-blog
266                 $result = $user->{$key};
267         else
268                 $result = false;
269
270         return apply_filters("get_user_option_{$option}", $result, $option, $user);
271 }
272
273 /**
274  * Update user option with global blog capability.
275  *
276  * User options are just like user metadata except that they have support for
277  * global blog options. If the 'global' parameter is false, which it is by default
278  * it will prepend the WordPress table prefix to the option name.
279  *
280  * Deletes the user option if $newvalue is empty.
281  *
282  * @since 2.0.0
283  * @uses $wpdb WordPress database object for queries
284  *
285  * @param int $user_id User ID
286  * @param string $option_name User option name.
287  * @param mixed $newvalue User option value.
288  * @param bool $global Optional. Whether option name is global or blog specific. Default false (blog specific).
289  * @return unknown
290  */
291 function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
292         global $wpdb;
293
294         if ( !$global )
295                 $option_name = $wpdb->prefix . $option_name;
296
297         // For backward compatibility. See differences between update_user_meta() and deprecated update_usermeta().
298         // http://core.trac.wordpress.org/ticket/13088
299         if ( is_null( $newvalue ) || is_scalar( $newvalue ) && empty( $newvalue ) )
300                 return delete_user_meta( $user_id, $option_name );
301
302         return update_user_meta( $user_id, $option_name, $newvalue );
303 }
304
305 /**
306  * Delete user option with global blog capability.
307  *
308  * User options are just like user metadata except that they have support for
309  * global blog options. If the 'global' parameter is false, which it is by default
310  * it will prepend the WordPress table prefix to the option name.
311  *
312  * @since 3.0.0
313  * @uses $wpdb WordPress database object for queries
314  *
315  * @param int $user_id User ID
316  * @param string $option_name User option name.
317  * @param bool $global Optional. Whether option name is global or blog specific. Default false (blog specific).
318  * @return unknown
319  */
320 function delete_user_option( $user_id, $option_name, $global = false ) {
321         global $wpdb;
322
323         if ( !$global )
324                 $option_name = $wpdb->prefix . $option_name;
325         return delete_user_meta( $user_id, $option_name );
326 }
327
328 /**
329  * Get users for the blog.
330  *
331  * For setups that use the multi-blog feature. Can be used outside of the
332  * multi-blog feature.
333  *
334  * @since 2.2.0
335  * @uses $wpdb WordPress database object for queries
336  * @uses $blog_id The Blog id of the blog for those that use more than one blog
337  *
338  * @param int $id Blog ID.
339  * @return array List of users that are part of that Blog ID
340  */
341 function get_users_of_blog( $id = '' ) {
342         global $wpdb, $blog_id;
343         if ( empty($id) )
344                 $id = (int) $blog_id;
345         $blog_prefix = $wpdb->get_blog_prefix($id);
346         $users = $wpdb->get_results( "SELECT user_id, user_id AS ID, user_login, display_name, user_email, meta_value FROM $wpdb->users, $wpdb->usermeta WHERE {$wpdb->users}.ID = {$wpdb->usermeta}.user_id AND meta_key = '{$blog_prefix}capabilities' ORDER BY {$wpdb->usermeta}.user_id" );
347         return $users;
348 }
349
350 /**
351  * Add meta data field to a user.
352  *
353  * Post meta data is called "Custom Fields" on the Administration Panels.
354  *
355  * @since 3.0.0
356  * @uses add_metadata()
357  * @link http://codex.wordpress.org/Function_Reference/add_user_meta
358  *
359  * @param int $user_id Post ID.
360  * @param string $key Metadata name.
361  * @param mixed $value Metadata value.
362  * @param bool $unique Optional, default is false. Whether the same key should not be added.
363  * @return bool False for failure. True for success.
364  */
365 function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
366         return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
367 }
368
369 /**
370  * Remove metadata matching criteria from a user.
371  *
372  * You can match based on the key, or key and value. Removing based on key and
373  * value, will keep from removing duplicate metadata with the same key. It also
374  * allows removing all metadata matching key, if needed.
375  *
376  * @since 3.0.0
377  * @uses delete_metadata()
378  * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
379  *
380  * @param int $user_id user ID
381  * @param string $meta_key Metadata name.
382  * @param mixed $meta_value Optional. Metadata value.
383  * @return bool False for failure. True for success.
384  */
385 function delete_user_meta($user_id, $meta_key, $meta_value = '') {
386         return delete_metadata('user', $user_id, $meta_key, $meta_value);
387 }
388
389 /**
390  * Retrieve user meta field for a user.
391  *
392  * @since 3.0.0
393  * @uses get_metadata()
394  * @link http://codex.wordpress.org/Function_Reference/get_user_meta
395  *
396  * @param int $user_id Post ID.
397  * @param string $key The meta key to retrieve.
398  * @param bool $single Whether to return a single value.
399  * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
400  *  is true.
401  */
402 function get_user_meta($user_id, $key, $single = false) {
403         return get_metadata('user', $user_id, $key, $single);
404 }
405
406 /**
407  * Update user meta field based on user ID.
408  *
409  * Use the $prev_value parameter to differentiate between meta fields with the
410  * same key and user ID.
411  *
412  * If the meta field for the user does not exist, it will be added.
413  *
414  * @since 3.0.0
415  * @uses update_metadata
416  * @link http://codex.wordpress.org/Function_Reference/update_user_meta
417  *
418  * @param int $user_id Post ID.
419  * @param string $key Metadata key.
420  * @param mixed $value Metadata value.
421  * @param mixed $prev_value Optional. Previous value to check before removing.
422  * @return bool False on failure, true if success.
423  */
424 function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
425         return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
426 }
427
428 /**
429  * Count number of users who have each of the user roles.
430  *
431  * Assumes there are neither duplicated nor orphaned capabilities meta_values.
432  * Assumes role names are unique phrases.  Same assumption made by WP_User_Search::prepare_query()
433  * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
434  * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
435  *
436  * @since 3.0.0
437  * @param string $strategy 'time' or 'memory'
438  * @return array Includes a grand total and an array of counts indexed by role strings.
439  */
440 function count_users($strategy = 'time') {
441         global $wpdb, $blog_id, $wp_roles;
442
443         // Initialize
444         $id = (int) $blog_id;
445         $blog_prefix = $wpdb->get_blog_prefix($id);
446         $result = array();
447
448         if ( 'time' == $strategy ) {
449                 global $wp_roles;
450
451                 if ( ! isset( $wp_roles ) )
452                         $wp_roles = new WP_Roles();
453
454                 $avail_roles = $wp_roles->get_names();
455
456                 // Build a CPU-intensive query that will return concise information.
457                 $select_count = array();
458                 foreach ( $avail_roles as $this_role => $name ) {
459                         $select_count[] = "COUNT(NULLIF(`meta_value` LIKE '%" . like_escape($this_role) . "%', FALSE))";
460                 }
461                 $select_count = implode(', ', $select_count);
462
463                 // Add the meta_value index to the selection list, then run the query.
464                 $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
465
466                 // Run the previous loop again to associate results with role names.
467                 $col = 0;
468                 $role_counts = array();
469                 foreach ( $avail_roles as $this_role => $name ) {
470                         $count = (int) $row[$col++];
471                         if ($count > 0) {
472                                 $role_counts[$this_role] = $count;
473                         }
474                 }
475
476                 // Get the meta_value index from the end of the result set.
477                 $total_users = (int) $row[$col];
478
479                 $result['total_users'] = $total_users;
480                 $result['avail_roles'] =& $role_counts;
481         } else {
482                 $avail_roles = array();
483
484                 $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
485
486                 foreach ( $users_of_blog as $caps_meta ) {
487                         $b_roles = unserialize($caps_meta);
488                         if ( is_array($b_roles) ) {
489                                 foreach ( $b_roles as $b_role => $val ) {
490                                         if ( isset($avail_roles[$b_role]) ) {
491                                                 $avail_roles[$b_role]++;
492                                         } else {
493                                                 $avail_roles[$b_role] = 1;
494                                         }
495                                 }
496                         }
497                 }
498
499                 $result['total_users'] = count( $users_of_blog );
500                 $result['avail_roles'] =& $avail_roles;
501         }
502
503         return $result;
504 }
505
506 //
507 // Private helper functions
508 //
509
510 /**
511  * Set up global user vars.
512  *
513  * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
514  *
515  * @since 2.0.4
516  * @global string $userdata User description.
517  * @global string $user_login The user username for logging in
518  * @global int $user_level The level of the user
519  * @global int $user_ID The ID of the user
520  * @global string $user_email The email address of the user
521  * @global string $user_url The url in the user's profile
522  * @global string $user_pass_md5 MD5 of the user's password
523  * @global string $user_identity The display name of the user
524  *
525  * @param int $for_user_id Optional. User ID to set up global data.
526  */
527 function setup_userdata($for_user_id = '') {
528         global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_pass_md5, $user_identity;
529
530         if ( '' == $for_user_id )
531                 $user = wp_get_current_user();
532         else
533                 $user = new WP_User($for_user_id);
534
535         $userdata   = $user->data;
536         $user_ID    = (int) $user->ID;
537         $user_level = (int) isset($user->user_level) ? $user->user_level : 0;
538
539         if ( 0 == $user->ID ) {
540                 $user_login = $user_email = $user_url = $user_pass_md5 = $user_identity = '';
541                 return;
542         }
543
544         $user_login     = $user->user_login;
545         $user_email     = $user->user_email;
546         $user_url       = $user->user_url;
547         $user_pass_md5  = md5($user->user_pass);
548         $user_identity  = $user->display_name;
549 }
550
551 /**
552  * Create dropdown HTML content of users.
553  *
554  * The content can either be displayed, which it is by default or retrieved by
555  * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
556  * need to be used; all users will be displayed in that case. Only one can be
557  * used, either 'include' or 'exclude', but not both.
558  *
559  * The available arguments are as follows:
560  * <ol>
561  * <li>show_option_all - Text to show all and whether HTML option exists.</li>
562  * <li>show_option_none - Text for show none and whether HTML option exists.
563  *     </li>
564  * <li>orderby - SQL order by clause for what order the users appear. Default is
565  * 'display_name'.</li>
566  * <li>order - Default is 'ASC'. Can also be 'DESC'.</li>
567  * <li>include - User IDs to include.</li>
568  * <li>exclude - User IDs to exclude.</li>
569  * <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>
570  * <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 parentesis</li>
571  * <li>echo - Default is '1'. Whether to display or retrieve content.</li>
572  * <li>selected - Which User ID is selected.</li>
573  * <li>name - Default is 'user'. Name attribute of select element.</li>
574  * <li>id - Default is the value of the 'name' parameter. ID attribute of select element.</li>
575  * <li>class - Class attribute of select element.</li>
576  * <li>blog_id - ID of blog (Multisite only). Defaults to ID of current blog.</li>
577  * </ol>
578  *
579  * @since 2.3.0
580  * @uses $wpdb WordPress database object for queries
581  *
582  * @param string|array $args Optional. Override defaults.
583  * @return string|null Null on display. String of HTML content on retrieve.
584  */
585 function wp_dropdown_users( $args = '' ) {
586         global $wpdb;
587         $defaults = array(
588                 'show_option_all' => '', 'show_option_none' => '',
589                 'orderby' => 'display_name', 'order' => 'ASC',
590                 'include' => '', 'exclude' => '', 'multi' => 0,
591                 'show' => 'display_name', 'echo' => 1,
592                 'selected' => 0, 'name' => 'user', 'class' => '', 'blog_id' => $GLOBALS['blog_id'],
593                 'id' => '',
594         );
595
596         $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
597
598         $r = wp_parse_args( $args, $defaults );
599         extract( $r, EXTR_SKIP );
600
601         $blog_prefix = $wpdb->get_blog_prefix( $blog_id );
602         $query = "SELECT {$wpdb->users}.* FROM $wpdb->users, $wpdb->usermeta WHERE {$wpdb->users}.ID = {$wpdb->usermeta}.user_id AND meta_key = '{$blog_prefix}capabilities'";
603
604         $query_where = array();
605
606         if ( is_array($include) )
607                 $include = join(',', $include);
608         $include = preg_replace('/[^0-9,]/', '', $include); // (int)
609         if ( $include )
610                 $query_where[] = "ID IN ($include)";
611
612         if ( is_array($exclude) )
613                 $exclude = join(',', $exclude);
614         $exclude = preg_replace('/[^0-9,]/', '', $exclude); // (int)
615         if ( $exclude )
616                 $query_where[] = "ID NOT IN ($exclude)";
617
618         if ( $query_where )
619                 $query .= " AND " . join(' AND', $query_where);
620
621         $query .= " ORDER BY $orderby $order";
622
623         $users = $wpdb->get_results( $query );
624
625         $output = '';
626         if ( !empty($users) ) {
627                 $name = esc_attr( $name );
628                 if ( $multi && ! $id )
629                         $id = '';
630                 else
631                         $id = $id ? " id='" . esc_attr( $id ) . "'" : " id='$name'";
632
633                 $output = "<select name='{$name}'{$id} class='$class'>\n";
634
635                 if ( $show_option_all )
636                         $output .= "\t<option value='0'>$show_option_all</option>\n";
637
638                 if ( $show_option_none ) {
639                         $_selected = selected( -1, $selected, false );
640                         $output .= "\t<option value='-1'$_selected>$show_option_none</option>\n";
641                 }
642
643                 foreach ( (array) $users as $user ) {
644                         $user->ID = (int) $user->ID;
645                         $_selected = selected( $user->ID, $selected, false );
646                         $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
647                         $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n";
648                 }
649
650                 $output .= "</select>";
651         }
652
653         $output = apply_filters('wp_dropdown_users', $output);
654
655         if ( $echo )
656                 echo $output;
657
658         return $output;
659 }
660
661 /**
662  * Add user meta data as properties to given user object.
663  *
664  * The finished user data is cached, but the cache is not used to fill in the
665  * user data for the given object. Once the function has been used, the cache
666  * should be used to retrieve user data. The intention is if the current data
667  * had been cached already, there would be no need to call this function.
668  *
669  * @access private
670  * @since 2.5.0
671  * @uses $wpdb WordPress database object for queries
672  *
673  * @param object $user The user data object.
674  */
675 function _fill_user( &$user ) {
676         $metavalues = get_user_metavalues(array($user->ID));
677         _fill_single_user($user, $metavalues[$user->ID]);
678 }
679
680 /**
681  * Perform the query to get the $metavalues array(s) needed by _fill_user and _fill_many_users
682  *
683  * @since 3.0.0
684  * @param array $ids User ID numbers list.
685  * @return array of arrays. The array is indexed by user_id, containing $metavalues object arrays.
686  */
687 function get_user_metavalues($ids) {
688         global $wpdb;
689
690         $clean = array_map('intval', $ids);
691         if ( 0 == count($clean) )
692                 return $objects;
693
694         $list = implode(',', $clean);
695
696         $show = $wpdb->hide_errors();
697         $metavalues = $wpdb->get_results("SELECT user_id, meta_key, meta_value FROM $wpdb->usermeta WHERE user_id IN ($list)");
698         $wpdb->show_errors($show);
699
700         $objects = array();
701         foreach($clean as $id) {
702                 $objects[$id] = array();
703         }
704         foreach($metavalues as $meta_object) {
705                 $objects[$meta_object->user_id][] = $meta_object;
706         }
707
708         return $objects;
709 }
710
711 /**
712  * Unserialize user metadata, fill $user object, then cache everything.
713  *
714  * @since 3.0.0
715  * @param object $user The User object.
716  * @param array $metavalues An array of objects provided by get_user_metavalues()
717  */
718 function _fill_single_user( &$user, &$metavalues ) {
719         global $wpdb;
720
721         foreach ( $metavalues as $meta ) {
722                 $value = maybe_unserialize($meta->meta_value);
723                 // Keys used as object vars cannot have dashes.
724                 $key = str_replace('-', '', $meta->meta_key);
725                 $user->{$key} = $value;
726         }
727
728         $level = $wpdb->prefix . 'user_level';
729         if ( isset( $user->{$level} ) )
730                 $user->user_level = $user->{$level};
731
732         // For backwards compat.
733         if ( isset($user->first_name) )
734                 $user->user_firstname = $user->first_name;
735         if ( isset($user->last_name) )
736                 $user->user_lastname = $user->last_name;
737         if ( isset($user->description) )
738                 $user->user_description = $user->description;
739
740         update_user_caches($user);
741 }
742
743 /**
744  * Take an array of user objects, fill them with metas, and cache them.
745  *
746  * @since 3.0.0
747  * @param array $users User objects
748  */
749 function _fill_many_users( &$users ) {
750         $ids = array();
751         foreach($users as $user_object) {
752                 $ids[] = $user_object->ID;
753         }
754
755     $metas = get_user_metavalues($ids);
756
757         foreach($users as $user_object) {
758                 if (isset($metas[$user_object->ID])) {
759                 _fill_single_user($user_object, $metas[$user_object->ID]);
760                 }
761         }
762 }
763
764 /**
765  * Sanitize every user field.
766  *
767  * If the context is 'raw', then the user object or array will get minimal santization of the int fields.
768  *
769  * @since 2.3.0
770  * @uses sanitize_user_field() Used to sanitize the fields.
771  *
772  * @param object|array $user The User Object or Array
773  * @param string $context Optional, default is 'display'. How to sanitize user fields.
774  * @return object|array The now sanitized User Object or Array (will be the same type as $user)
775  */
776 function sanitize_user_object($user, $context = 'display') {
777         if ( is_object($user) ) {
778                 if ( !isset($user->ID) )
779                         $user->ID = 0;
780                 if ( isset($user->data) )
781                         $vars = get_object_vars( $user->data );
782                 else
783                         $vars = get_object_vars($user);
784                 foreach ( array_keys($vars) as $field ) {
785                         if ( is_string($user->$field) || is_numeric($user->$field) )
786                                 $user->$field = sanitize_user_field($field, $user->$field, $user->ID, $context);
787                 }
788                 $user->filter = $context;
789         } else {
790                 if ( !isset($user['ID']) )
791                         $user['ID'] = 0;
792                 foreach ( array_keys($user) as $field )
793                         $user[$field] = sanitize_user_field($field, $user[$field], $user['ID'], $context);
794                 $user['filter'] = $context;
795         }
796
797         return $user;
798 }
799
800 /**
801  * Sanitize user field based on context.
802  *
803  * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
804  * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
805  * when calling filters.
806  *
807  * @since 2.3.0
808  * @uses apply_filters() Calls 'edit_$field' and '${field_no_prefix}_edit_pre' passing $value and
809  *  $user_id if $context == 'edit' and field name prefix == 'user_'.
810  *
811  * @uses apply_filters() Calls 'edit_user_$field' passing $value and $user_id if $context == 'db'.
812  * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'user_'.
813  * @uses apply_filters() Calls '${field}_pre' passing $value if $context == 'db' and field name prefix != 'user_'.
814  *
815  * @uses apply_filters() Calls '$field' passing $value, $user_id and $context if $context == anything
816  *  other than 'raw', 'edit' and 'db' and field name prefix == 'user_'.
817  * @uses apply_filters() Calls 'user_$field' passing $value if $context == anything other than 'raw',
818  *  'edit' and 'db' and field name prefix != 'user_'.
819  *
820  * @param string $field The user Object field name.
821  * @param mixed $value The user Object value.
822  * @param int $user_id user ID.
823  * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
824  *               'attribute' and 'js'.
825  * @return mixed Sanitized value.
826  */
827 function sanitize_user_field($field, $value, $user_id, $context) {
828         $int_fields = array('ID');
829         if ( in_array($field, $int_fields) )
830                 $value = (int) $value;
831
832         if ( 'raw' == $context )
833                 return $value;
834
835         if ( !is_string($value) && !is_numeric($value) )
836                 return $value;
837
838         $prefixed = false;
839         if ( false !== strpos($field, 'user_') ) {
840                 $prefixed = true;
841                 $field_no_prefix = str_replace('user_', '', $field);
842         }
843
844         if ( 'edit' == $context ) {
845                 if ( $prefixed ) {
846                         $value = apply_filters("edit_$field", $value, $user_id);
847                 } else {
848                         $value = apply_filters("edit_user_$field", $value, $user_id);
849                 }
850
851                 if ( 'description' == $field )
852                         $value = esc_html($value);
853                 else
854                         $value = esc_attr($value);
855         } else if ( 'db' == $context ) {
856                 if ( $prefixed ) {
857                         $value = apply_filters("pre_$field", $value);
858                 } else {
859                         $value = apply_filters("pre_user_$field", $value);
860                 }
861         } else {
862                 // Use display filters by default.
863                 if ( $prefixed )
864                         $value = apply_filters($field, $value, $user_id, $context);
865                 else
866                         $value = apply_filters("user_$field", $value, $user_id, $context);
867         }
868
869         if ( 'user_url' == $field )
870                 $value = esc_url($value);
871
872         if ( 'attribute' == $context )
873                 $value = esc_attr($value);
874         else if ( 'js' == $context )
875                 $value = esc_js($value);
876
877         return $value;
878 }
879
880 /**
881  * Update all user caches
882  *
883  * @since 3.0.0
884  *
885  * @param object $user User object to be cached
886  */
887 function update_user_caches(&$user) {
888         wp_cache_add($user->ID, $user, 'users');
889         wp_cache_add($user->user_login, $user->ID, 'userlogins');
890         wp_cache_add($user->user_email, $user->ID, 'useremail');
891         wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
892 }
893
894 /**
895  * Clean all user caches
896  *
897  * @since 3.0.0
898  *
899  * @param int $id User ID
900  */
901 function clean_user_cache($id) {
902         $user = new WP_User($id);
903
904         wp_cache_delete($id, 'users');
905         wp_cache_delete($user->user_login, 'userlogins');
906         wp_cache_delete($user->user_email, 'useremail');
907         wp_cache_delete($user->user_nicename, 'userslugs');
908 }
909
910 ?>