9 * Authenticate user with remember capability.
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.
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
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.
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'];
35 if ( !empty($credentials['remember']) )
36 $credentials['remember'] = true;
38 $credentials['remember'] = false;
40 // TODO do we deprecate the wp_authentication action?
41 do_action_ref_array('wp_authenticate', array(&$credentials['user_login'], &$credentials['user_password']));
43 if ( '' === $secure_cookie )
44 $secure_cookie = is_ssl();
46 global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
47 $auth_secure_cookie = $secure_cookie;
49 add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
51 $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
53 if ( is_wp_error($user) ) {
54 if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
55 $user = new WP_Error('', '');
61 wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
62 do_action('wp_login', $credentials['user_login']);
68 * Authenticate the user using the username and password.
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; }
74 if ( empty($username) || empty($password) ) {
75 $error = new WP_Error();
77 if ( empty($username) )
78 $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
80 if ( empty($password) )
81 $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
86 $userdata = get_user_by('login', $username);
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')));
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.'));
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.'));
104 $userdata = apply_filters('wp_authenticate_user', $userdata, $password);
105 if ( is_wp_error($userdata) )
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')));
111 $user = new WP_User($userdata->ID);
116 * Authenticate the user using the WordPress auth cookie.
118 function wp_authenticate_cookie($user, $username, $password) {
119 if ( is_a($user, 'WP_User') ) { return $user; }
121 if ( empty($username) && empty($password) ) {
122 $user_id = wp_validate_auth_cookie();
124 return new WP_User($user_id);
126 global $auth_secure_cookie;
128 if ( $auth_secure_cookie )
129 $auth_cookie = SECURE_AUTH_COOKIE;
131 $auth_cookie = AUTH_COOKIE;
133 if ( !empty($_COOKIE[$auth_cookie]) )
134 return new WP_Error('expired_session', __('Please log in again.'));
136 // If the cookie is not set, be silent.
143 * Number of posts user has written.
146 * @uses $wpdb WordPress database object for queries.
148 * @param int $userid User ID.
149 * @return int Amount of posts user has written.
151 function count_user_posts($userid) {
154 $where = get_posts_by_author_sql('post', TRUE, $userid);
156 $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
158 return apply_filters('get_usernumposts', $count, $userid);
162 * Number of posts written by a list of users.
165 * @param array $userid User ID number list.
166 * @return array Amount of posts each user has written.
168 function count_many_users_posts($users) {
172 if ( ! is_array($users) || empty( $users ) )
175 $userlist = implode( ',', $users );
176 $where = get_posts_by_author_sql( 'post' );
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];
183 foreach ( $users as $id ) {
184 if ( ! isset( $count[ $id ] ) )
192 * Check that the user login name and password is correct.
195 * @todo xmlrpc only. Maybe move to xmlrpc.php.
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.
201 function user_pass_ok($user_login, $user_pass) {
202 $user = wp_authenticate($user_login, $user_pass);
203 if ( is_wp_error($user) )
210 // User option functions
214 * Get the current user's ID
218 * @uses wp_get_current_user
220 * @return int The current user's ID
222 function get_current_user_id() {
223 $user = wp_get_current_user();
224 return ( isset( $user->ID ) ? (int) $user->ID : 0 );
228 * Retrieve user option that can be either per Site or per Network.
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.
235 * The option will first check for the per site name and then the per Network name.
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.
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.
247 function get_user_option( $option, $user = 0, $deprecated = '' ) {
250 if ( !empty( $deprecated ) )
251 _deprecated_argument( __FUNCTION__, '3.0' );
253 if ( empty($user) ) {
254 $user = wp_get_current_user();
258 $user = get_userdata($user);
260 // Keys used as object vars cannot have dashes.
261 $key = str_replace('-', '', $option);
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};
270 return apply_filters("get_user_option_{$option}", $result, $option, $user);
274 * Update user option with global blog capability.
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.
280 * Deletes the user option if $newvalue is empty.
283 * @uses $wpdb WordPress database object for queries
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).
291 function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
295 $option_name = $wpdb->prefix . $option_name;
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 );
302 return update_user_meta( $user_id, $option_name, $newvalue );
306 * Delete user option with global blog capability.
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.
313 * @uses $wpdb WordPress database object for queries
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).
320 function delete_user_option( $user_id, $option_name, $global = false ) {
324 $option_name = $wpdb->prefix . $option_name;
325 return delete_user_meta( $user_id, $option_name );
329 * Get users for the blog.
331 * For setups that use the multi-blog feature. Can be used outside of the
332 * multi-blog feature.
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
338 * @param int $id Blog ID.
339 * @return array List of users that are part of that Blog ID
341 function get_users_of_blog( $id = '' ) {
342 global $wpdb, $blog_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" );
351 * Add meta data field to a user.
353 * Post meta data is called "Custom Fields" on the Administration Panels.
356 * @uses add_metadata()
357 * @link http://codex.wordpress.org/Function_Reference/add_user_meta
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.
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);
370 * Remove metadata matching criteria from a user.
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.
377 * @uses delete_metadata()
378 * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
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.
385 function delete_user_meta($user_id, $meta_key, $meta_value = '') {
386 return delete_metadata('user', $user_id, $meta_key, $meta_value);
390 * Retrieve user meta field for a user.
393 * @uses get_metadata()
394 * @link http://codex.wordpress.org/Function_Reference/get_user_meta
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
402 function get_user_meta($user_id, $key, $single = false) {
403 return get_metadata('user', $user_id, $key, $single);
407 * Update user meta field based on user ID.
409 * Use the $prev_value parameter to differentiate between meta fields with the
410 * same key and user ID.
412 * If the meta field for the user does not exist, it will be added.
415 * @uses update_metadata
416 * @link http://codex.wordpress.org/Function_Reference/update_user_meta
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.
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);
429 * Count number of users who have each of the user roles.
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.
437 * @param string $strategy 'time' or 'memory'
438 * @return array Includes a grand total and an array of counts indexed by role strings.
440 function count_users($strategy = 'time') {
441 global $wpdb, $blog_id, $wp_roles;
444 $id = (int) $blog_id;
445 $blog_prefix = $wpdb->get_blog_prefix($id);
448 if ( 'time' == $strategy ) {
451 if ( ! isset( $wp_roles ) )
452 $wp_roles = new WP_Roles();
454 $avail_roles = $wp_roles->get_names();
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))";
461 $select_count = implode(', ', $select_count);
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 );
466 // Run the previous loop again to associate results with role names.
468 $role_counts = array();
469 foreach ( $avail_roles as $this_role => $name ) {
470 $count = (int) $row[$col++];
472 $role_counts[$this_role] = $count;
476 // Get the meta_value index from the end of the result set.
477 $total_users = (int) $row[$col];
479 $result['total_users'] = $total_users;
480 $result['avail_roles'] =& $role_counts;
482 $avail_roles = array();
484 $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
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]++;
493 $avail_roles[$b_role] = 1;
499 $result['total_users'] = count( $users_of_blog );
500 $result['avail_roles'] =& $avail_roles;
507 // Private helper functions
511 * Set up global user vars.
513 * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
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
525 * @param int $for_user_id Optional. User ID to set up global data.
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;
530 if ( '' == $for_user_id )
531 $user = wp_get_current_user();
533 $user = new WP_User($for_user_id);
535 $userdata = $user->data;
536 $user_ID = (int) $user->ID;
537 $user_level = (int) isset($user->user_level) ? $user->user_level : 0;
539 if ( 0 == $user->ID ) {
540 $user_login = $user_email = $user_url = $user_pass_md5 = $user_identity = '';
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;
552 * Create dropdown HTML content of users.
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.
559 * The available arguments are as follows:
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.
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>
580 * @uses $wpdb WordPress database object for queries
582 * @param string|array $args Optional. Override defaults.
583 * @return string|null Null on display. String of HTML content on retrieve.
585 function wp_dropdown_users( $args = '' ) {
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'],
596 $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
598 $r = wp_parse_args( $args, $defaults );
599 extract( $r, EXTR_SKIP );
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'";
604 $query_where = array();
606 if ( is_array($include) )
607 $include = join(',', $include);
608 $include = preg_replace('/[^0-9,]/', '', $include); // (int)
610 $query_where[] = "ID IN ($include)";
612 if ( is_array($exclude) )
613 $exclude = join(',', $exclude);
614 $exclude = preg_replace('/[^0-9,]/', '', $exclude); // (int)
616 $query_where[] = "ID NOT IN ($exclude)";
619 $query .= " AND " . join(' AND', $query_where);
621 $query .= " ORDER BY $orderby $order";
623 $users = $wpdb->get_results( $query );
626 if ( !empty($users) ) {
627 $name = esc_attr( $name );
628 if ( $multi && ! $id )
631 $id = $id ? " id='" . esc_attr( $id ) . "'" : " id='$name'";
633 $output = "<select name='{$name}'{$id} class='$class'>\n";
635 if ( $show_option_all )
636 $output .= "\t<option value='0'>$show_option_all</option>\n";
638 if ( $show_option_none ) {
639 $_selected = selected( -1, $selected, false );
640 $output .= "\t<option value='-1'$_selected>$show_option_none</option>\n";
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";
650 $output .= "</select>";
653 $output = apply_filters('wp_dropdown_users', $output);
662 * Add user meta data as properties to given user object.
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.
671 * @uses $wpdb WordPress database object for queries
673 * @param object $user The user data object.
675 function _fill_user( &$user ) {
676 $metavalues = get_user_metavalues(array($user->ID));
677 _fill_single_user($user, $metavalues[$user->ID]);
681 * Perform the query to get the $metavalues array(s) needed by _fill_user and _fill_many_users
684 * @param array $ids User ID numbers list.
685 * @return array of arrays. The array is indexed by user_id, containing $metavalues object arrays.
687 function get_user_metavalues($ids) {
690 $clean = array_map('intval', $ids);
691 if ( 0 == count($clean) )
694 $list = implode(',', $clean);
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);
701 foreach($clean as $id) {
702 $objects[$id] = array();
704 foreach($metavalues as $meta_object) {
705 $objects[$meta_object->user_id][] = $meta_object;
712 * Unserialize user metadata, fill $user object, then cache everything.
715 * @param object $user The User object.
716 * @param array $metavalues An array of objects provided by get_user_metavalues()
718 function _fill_single_user( &$user, &$metavalues ) {
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;
728 $level = $wpdb->prefix . 'user_level';
729 if ( isset( $user->{$level} ) )
730 $user->user_level = $user->{$level};
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;
740 update_user_caches($user);
744 * Take an array of user objects, fill them with metas, and cache them.
747 * @param array $users User objects
749 function _fill_many_users( &$users ) {
751 foreach($users as $user_object) {
752 $ids[] = $user_object->ID;
755 $metas = get_user_metavalues($ids);
757 foreach($users as $user_object) {
758 if (isset($metas[$user_object->ID])) {
759 _fill_single_user($user_object, $metas[$user_object->ID]);
765 * Sanitize every user field.
767 * If the context is 'raw', then the user object or array will get minimal santization of the int fields.
770 * @uses sanitize_user_field() Used to sanitize the fields.
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)
776 function sanitize_user_object($user, $context = 'display') {
777 if ( is_object($user) ) {
778 if ( !isset($user->ID) )
780 if ( isset($user->data) )
781 $vars = get_object_vars( $user->data );
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);
788 $user->filter = $context;
790 if ( !isset($user['ID']) )
792 foreach ( array_keys($user) as $field )
793 $user[$field] = sanitize_user_field($field, $user[$field], $user['ID'], $context);
794 $user['filter'] = $context;
801 * Sanitize user field based on context.
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.
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_'.
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_'.
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_'.
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.
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;
832 if ( 'raw' == $context )
835 if ( !is_string($value) && !is_numeric($value) )
839 if ( false !== strpos($field, 'user_') ) {
841 $field_no_prefix = str_replace('user_', '', $field);
844 if ( 'edit' == $context ) {
846 $value = apply_filters("edit_$field", $value, $user_id);
848 $value = apply_filters("edit_user_$field", $value, $user_id);
851 if ( 'description' == $field )
852 $value = esc_html($value);
854 $value = esc_attr($value);
855 } else if ( 'db' == $context ) {
857 $value = apply_filters("pre_$field", $value);
859 $value = apply_filters("pre_user_$field", $value);
862 // Use display filters by default.
864 $value = apply_filters($field, $value, $user_id, $context);
866 $value = apply_filters("user_$field", $value, $user_id, $context);
869 if ( 'user_url' == $field )
870 $value = esc_url($value);
872 if ( 'attribute' == $context )
873 $value = esc_attr($value);
874 else if ( 'js' == $context )
875 $value = esc_js($value);
881 * Update all user caches
885 * @param object $user User object to be cached
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');
895 * Clean all user caches
899 * @param int $id User ID
901 function clean_user_cache($id) {
902 $user = new WP_User($id);
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');