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 $secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, $credentials);
48 global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
49 $auth_secure_cookie = $secure_cookie;
51 add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
53 $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
55 if ( is_wp_error($user) ) {
56 if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
57 $user = new WP_Error('', '');
63 wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
64 do_action('wp_login', $credentials['user_login']);
70 * Authenticate the user using the username and password.
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; }
76 if ( empty($username) || empty($password) ) {
77 $error = new WP_Error();
79 if ( empty($username) )
80 $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
82 if ( empty($password) )
83 $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
88 $userdata = get_user_by('login', $username);
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')));
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.'));
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.'));
106 $userdata = apply_filters('wp_authenticate_user', $userdata, $password);
107 if ( is_wp_error($userdata) )
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' ) ) );
114 $user = new WP_User($userdata->ID);
119 * Authenticate the user using the WordPress auth cookie.
121 function wp_authenticate_cookie($user, $username, $password) {
122 if ( is_a($user, 'WP_User') ) { return $user; }
124 if ( empty($username) && empty($password) ) {
125 $user_id = wp_validate_auth_cookie();
127 return new WP_User($user_id);
129 global $auth_secure_cookie;
131 if ( $auth_secure_cookie )
132 $auth_cookie = SECURE_AUTH_COOKIE;
134 $auth_cookie = AUTH_COOKIE;
136 if ( !empty($_COOKIE[$auth_cookie]) )
137 return new WP_Error('expired_session', __('Please log in again.'));
139 // If the cookie is not set, be silent.
146 * Number of posts user has written.
149 * @uses $wpdb WordPress database object for queries.
151 * @param int $userid User ID.
152 * @return int Amount of posts user has written.
154 function count_user_posts($userid) {
157 $where = get_posts_by_author_sql('post', TRUE, $userid);
159 $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
161 return apply_filters('get_usernumposts', $count, $userid);
165 * Number of posts written by a list of users.
168 * @param array $users User ID number list.
169 * @return array Amount of posts each user has written.
171 function count_many_users_posts($users) {
175 if ( ! is_array($users) || empty( $users ) )
178 $userlist = implode( ',', $users );
179 $where = get_posts_by_author_sql( 'post' );
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];
186 foreach ( $users as $id ) {
187 if ( ! isset( $count[ $id ] ) )
195 * Check that the user login name and password is correct.
198 * @todo xmlrpc only. Maybe move to xmlrpc.php.
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.
204 function user_pass_ok($user_login, $user_pass) {
205 $user = wp_authenticate($user_login, $user_pass);
206 if ( is_wp_error($user) )
213 // User option functions
217 * Get the current user's ID
221 * @uses wp_get_current_user
223 * @return int The current user's ID
225 function get_current_user_id() {
226 $user = wp_get_current_user();
227 return ( isset( $user->ID ) ? (int) $user->ID : 0 );
231 * Retrieve user option that can be either per Site or per Network.
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.
238 * The option will first check for the per site name and then the per Network name.
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.
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.
250 function get_user_option( $option, $user = 0, $deprecated = '' ) {
253 if ( !empty( $deprecated ) )
254 _deprecated_argument( __FUNCTION__, '3.0' );
256 if ( empty($user) ) {
257 $user = wp_get_current_user();
261 $user = get_userdata($user);
263 // Keys used as object vars cannot have dashes.
264 $key = str_replace('-', '', $option);
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};
273 return apply_filters("get_user_option_{$option}", $result, $option, $user);
277 * Update user option with global blog capability.
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.
283 * Deletes the user option if $newvalue is empty.
286 * @uses $wpdb WordPress database object for queries
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).
294 function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
298 $option_name = $wpdb->prefix . $option_name;
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 );
305 return update_user_meta( $user_id, $option_name, $newvalue );
309 * Delete user option with global blog capability.
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.
316 * @uses $wpdb WordPress database object for queries
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).
323 function delete_user_option( $user_id, $option_name, $global = false ) {
327 $option_name = $wpdb->prefix . $option_name;
328 return delete_user_meta( $user_id, $option_name );
332 * WordPress User Query class.
336 class WP_User_Query {
339 * List of found user ids
348 * Total number of found users for the current query
354 var $total_users = 0;
366 function WP_User_Query( $query = null ) {
367 $this->__construct( $query );
375 * @param string|array $args The query variables
376 * @return WP_User_Query
378 function __construct( $query = null ) {
379 if ( !empty( $query ) ) {
380 $this->query_vars = wp_parse_args( $query, array(
381 'blog_id' => $GLOBALS['blog_id'],
385 'meta_compare' => '',
386 'include' => array(),
387 'exclude' => array(),
389 'orderby' => 'login',
391 'offset' => '', 'number' => '',
392 'count_total' => true,
397 $this->prepare_query();
403 * Prepare the query variables
408 function prepare_query() {
411 $qv = &$this->query_vars;
413 if ( is_array( $qv['fields'] ) ) {
414 $qv['fields'] = array_unique( $qv['fields'] );
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.*";
423 $this->query_fields = "$wpdb->users.ID";
426 $this->query_from = "FROM $wpdb->users";
427 $this->query_where = "WHERE 1=1";
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
444 ) p ON ({$wpdb->users}.ID = p.post_author)
446 $orderby = 'post_count';
447 } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
450 $orderby = 'user_login';
453 $qv['order'] = strtoupper( $qv['order'] );
454 if ( 'ASC' == $qv['order'] )
458 $this->query_orderby = "ORDER BY $orderby $order";
461 if ( $qv['number'] ) {
463 $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
465 $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
468 $search = trim( $qv['search'] );
470 $leading_wild = ( ltrim($search, '*') != $search );
471 $trailing_wild = ( rtrim($search, '*') != $search );
472 if ( $leading_wild && $trailing_wild )
474 elseif ( $leading_wild )
476 elseif ( $trailing_wild )
481 $search = trim($search, '*');
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');
490 $search_columns = array('user_login', 'user_nicename');
492 $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
495 $blog_id = absint( $qv['blog_id'] );
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
504 _parse_meta_query( $qv );
506 $role = trim( $qv['role'] );
508 if ( $blog_id && ( $role || is_multisite() ) ) {
509 $cap_meta_query = array();
510 $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
513 $cap_meta_query['value'] = '"' . $role . '"';
514 $cap_meta_query['compare'] = 'like';
517 $qv['meta_query'][] = $cap_meta_query;
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'];
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)";
534 do_action_ref_array( 'pre_user_query', array( &$this ) );
538 * Execute the query, with the current variables
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");
549 $this->results = $wpdb->get_col("SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit");
552 if ( $this->query_vars['count_total'] )
553 $this->total_users = $wpdb->get_var("SELECT COUNT(*) $this->query_from $this->query_where");
555 if ( !$this->results )
558 if ( 'all_with_meta' == $this->query_vars['fields'] ) {
559 cache_users( $this->results );
562 foreach ( $this->results as $userid )
563 $r[ $userid ] = new WP_User( $userid, '', $this->query_vars['blog_id'] );
570 * Used internally to generate an SQL string for searching across multiple columns
575 * @param string $string
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.
581 function get_search_sql( $string, $cols, $wild = false ) {
582 $string = esc_sql( $string );
585 $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
586 $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
587 foreach ( $cols as $col ) {
589 $searches[] = "$col = '$string'";
591 $searches[] = "$col LIKE '$leading_wild" . like_escape($string) . "$trailing_wild'";
594 return ' AND (' . implode(' OR ', $searches) . ')';
598 * Return the list of users
605 function get_results() {
606 return $this->results;
610 * Return the total number of users for the current query
617 function get_total() {
618 return $this->total_users;
623 * Retrieve list of users matching criteria.
627 * @uses WP_User_Query See for default arguments and information.
629 * @param array $args Optional.
630 * @return array List of users.
632 function get_users( $args = array() ) {
634 $args = wp_parse_args( $args );
635 $args['count_total'] = false;
637 $user_search = new WP_User_Query($args);
639 return (array) $user_search->get_results();
643 * Get the blogs a user belongs to.
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.
651 function get_blogs_of_user( $id, $all = false ) {
654 if ( !is_multisite() ) {
655 $blog_id = get_current_blog_id();
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');
666 $blogs = wp_cache_get( 'blogs_of_user-' . $id, 'users' );
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 );
675 wp_cache_set( 'blogs_of_user-' . $id, $blogs, 'users' );
679 if ( false === $blogs ) {
680 $user = get_userdata( (int) $id );
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 )
689 if ( substr($key, -12, 12) != 'capabilities' )
691 if ( preg_match( '/^' . $wpdb->base_prefix . '((\d+)_)?capabilities$/', $key, $match ) ) {
692 if ( count( $match ) > 2 )
693 $blogs[] = (int) $match[ 2 ];
698 wp_cache_set( 'blogs_of_user-' . $id, $blogs, 'users' );
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;
714 return apply_filters( 'get_blogs_of_user', $blog_deets, $id, $all );
718 * Checks if the current user belong to a given blog.
722 * @param int $blog_id Blog ID
723 * @return bool True if the current users belong to $blog_id, false if not.
725 function is_blog_user( $blog_id = 0 ) {
728 $current_user = wp_get_current_user();
730 $blog_id = $wpdb->blogid;
732 $cap_key = $wpdb->base_prefix . $blog_id . '_capabilities';
734 if ( is_array($current_user->$cap_key) && in_array(1, $current_user->$cap_key) )
741 * Add meta data field to a user.
743 * Post meta data is called "Custom Fields" on the Administration Panels.
746 * @uses add_metadata()
747 * @link http://codex.wordpress.org/Function_Reference/add_user_meta
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.
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);
760 * Remove metadata matching criteria from a user.
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.
767 * @uses delete_metadata()
768 * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
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.
775 function delete_user_meta($user_id, $meta_key, $meta_value = '') {
776 return delete_metadata('user', $user_id, $meta_key, $meta_value);
780 * Retrieve user meta field for a user.
783 * @uses get_metadata()
784 * @link http://codex.wordpress.org/Function_Reference/get_user_meta
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
792 function get_user_meta($user_id, $key, $single = false) {
793 return get_metadata('user', $user_id, $key, $single);
797 * Update user meta field based on user ID.
799 * Use the $prev_value parameter to differentiate between meta fields with the
800 * same key and user ID.
802 * If the meta field for the user does not exist, it will be added.
805 * @uses update_metadata
806 * @link http://codex.wordpress.org/Function_Reference/update_user_meta
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.
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);
819 * Count number of users who have each of the user roles.
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.
827 * @param string $strategy 'time' or 'memory'
828 * @return array Includes a grand total and an array of counts indexed by role strings.
830 function count_users($strategy = 'time') {
831 global $wpdb, $wp_roles;
834 $id = get_current_blog_id();
835 $blog_prefix = $wpdb->get_blog_prefix($id);
838 if ( 'time' == $strategy ) {
841 if ( ! isset( $wp_roles ) )
842 $wp_roles = new WP_Roles();
844 $avail_roles = $wp_roles->get_names();
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))";
851 $select_count = implode(', ', $select_count);
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 );
856 // Run the previous loop again to associate results with role names.
858 $role_counts = array();
859 foreach ( $avail_roles as $this_role => $name ) {
860 $count = (int) $row[$col++];
862 $role_counts[$this_role] = $count;
866 // Get the meta_value index from the end of the result set.
867 $total_users = (int) $row[$col];
869 $result['total_users'] = $total_users;
870 $result['avail_roles'] =& $role_counts;
872 $avail_roles = array();
874 $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
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]++;
883 $avail_roles[$b_role] = 1;
889 $result['total_users'] = count( $users_of_blog );
890 $result['avail_roles'] =& $avail_roles;
897 // Private helper functions
901 * Set up global user vars.
903 * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
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
915 * @param int $for_user_id Optional. User ID to set up global data.
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;
920 if ( '' == $for_user_id )
921 $user = wp_get_current_user();
923 $user = new WP_User($for_user_id);
925 $userdata = $user->data;
926 $user_ID = (int) $user->ID;
927 $user_level = (int) isset($user->user_level) ? $user->user_level : 0;
929 if ( 0 == $user->ID ) {
930 $user_login = $user_email = $user_url = $user_pass_md5 = $user_identity = '';
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;
942 * Create dropdown HTML content of users.
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.
949 * The available arguments are as follows:
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>
971 * @uses $wpdb WordPress database object for queries
973 * @param string|array $args Optional. Override defaults.
974 * @return string|null Null on display. String of HTML content on retrieve.
976 function wp_dropdown_users( $args = '' ) {
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
986 $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
988 $r = wp_parse_args( $args, $defaults );
989 extract( $r, EXTR_SKIP );
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 );
996 if ( !empty($users) && ( empty($hide_if_only_one_author) || count($users) > 1 ) ) {
997 $name = esc_attr( $name );
998 if ( $multi && ! $id )
1001 $id = $id ? " id='" . esc_attr( $id ) . "'" : " id='$name'";
1003 $output = "<select name='{$name}'{$id} class='$class'>\n";
1005 if ( $show_option_all )
1006 $output .= "\t<option value='0'>$show_option_all</option>\n";
1008 if ( $show_option_none ) {
1009 $_selected = selected( -1, $selected, false );
1010 $output .= "\t<option value='-1'$_selected>$show_option_none</option>\n";
1013 $found_selected = false;
1014 foreach ( (array) $users as $user ) {
1015 $user->ID = (int) $user->ID;
1016 $_selected = selected( $user->ID, $selected, false );
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";
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";
1030 $output .= "</select>";
1033 $output = apply_filters('wp_dropdown_users', $output);
1042 * Add user meta data as properties to given user object.
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.
1051 * @uses $wpdb WordPress database object for queries
1053 * @param object $user The user data object.
1055 function _fill_user( &$user ) {
1056 $metavalues = get_user_metavalues(array($user->ID));
1057 _fill_single_user($user, $metavalues[$user->ID]);
1061 * Perform the query to get the $metavalues array(s) needed by _fill_user and _fill_many_users
1064 * @param array $ids User ID numbers list.
1065 * @return array of arrays. The array is indexed by user_id, containing $metavalues object arrays.
1067 function get_user_metavalues($ids) {
1070 $ids = array_map('intval', $ids);
1071 foreach ( $ids as $id )
1072 $objects[$id] = array();
1074 $metas = update_meta_cache('user', $ids);
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);
1088 * Unserialize user metadata, fill $user object, then cache everything.
1091 * @param object $user The User object.
1092 * @param array $metavalues An array of objects provided by get_user_metavalues()
1094 function _fill_single_user( &$user, &$metavalues ) {
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;
1104 $level = $wpdb->prefix . 'user_level';
1105 if ( isset( $user->{$level} ) )
1106 $user->user_level = $user->{$level};
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;
1116 update_user_caches($user);
1120 * Take an array of user objects, fill them with metas, and cache them.
1123 * @param array $users User objects
1125 function _fill_many_users( &$users ) {
1127 foreach( $users as $user_object ) {
1128 $ids[] = $user_object->ID;
1131 $metas = get_user_metavalues($ids);
1133 foreach ( $users as $user_object ) {
1134 if ( isset($metas[$user_object->ID]) ) {
1135 _fill_single_user($user_object, $metas[$user_object->ID]);
1141 * Sanitize every user field.
1143 * If the context is 'raw', then the user object or array will get minimal santization of the int fields.
1146 * @uses sanitize_user_field() Used to sanitize the fields.
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)
1152 function sanitize_user_object($user, $context = 'display') {
1153 if ( is_object($user) ) {
1154 if ( !isset($user->ID) )
1156 if ( isset($user->data) )
1157 $vars = get_object_vars( $user->data );
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);
1164 $user->filter = $context;
1166 if ( !isset($user['ID']) )
1168 foreach ( array_keys($user) as $field )
1169 $user[$field] = sanitize_user_field($field, $user[$field], $user['ID'], $context);
1170 $user['filter'] = $context;
1177 * Sanitize user field based on context.
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.
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_'.
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_'.
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_'.
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.
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;
1208 if ( 'raw' == $context )
1211 if ( !is_string($value) && !is_numeric($value) )
1215 if ( false !== strpos($field, 'user_') ) {
1217 $field_no_prefix = str_replace('user_', '', $field);
1220 if ( 'edit' == $context ) {
1222 $value = apply_filters("edit_{$field}", $value, $user_id);
1224 $value = apply_filters("edit_user_{$field}", $value, $user_id);
1227 if ( 'description' == $field )
1228 $value = esc_html( $value ); // textarea_escaped?
1230 $value = esc_attr($value);
1231 } else if ( 'db' == $context ) {
1233 $value = apply_filters("pre_{$field}", $value);
1235 $value = apply_filters("pre_user_{$field}", $value);
1238 // Use display filters by default.
1240 $value = apply_filters($field, $value, $user_id, $context);
1242 $value = apply_filters("user_{$field}", $value, $user_id, $context);
1245 if ( 'user_url' == $field )
1246 $value = esc_url($value);
1248 if ( 'attribute' == $context )
1249 $value = esc_attr($value);
1250 else if ( 'js' == $context )
1251 $value = esc_js($value);
1257 * Update all user caches
1261 * @param object $user User object to be cached
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');
1271 * Clean all user caches
1275 * @param int $id User ID
1277 function clean_user_cache($id) {
1278 $user = new WP_User($id);
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');
1288 * Checks whether the given username exists.
1292 * @param string $username Username.
1293 * @return null|int The user's ID on success, and null on failure.
1295 function username_exists( $username ) {
1296 if ( $user = get_userdatabylogin( $username ) ) {
1304 * Checks whether the given email exists.
1309 * @param string $email Email.
1310 * @return bool|int The user's ID on success, and false on failure.
1312 function email_exists( $email ) {
1313 if ( $user = get_user_by_email($email) )
1320 * Checks whether an username is valid.
1323 * @uses apply_filters() Calls 'validate_username' hook on $valid check and $username as parameters
1325 * @param string $username Username.
1326 * @return bool Whether username given is valid
1328 function validate_username( $username ) {
1329 $sanitized = sanitize_user( $username, true );
1330 $valid = ( $sanitized == $username );
1331 return apply_filters( 'validate_username', $valid, $username );
1335 * Insert an user into the database.
1337 * Can update a current user or insert a new user based on whether the user's ID
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.
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.
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
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.
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
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.
1382 function wp_insert_user($userdata) {
1385 extract($userdata, EXTR_SKIP);
1387 // Are we updating or creating?
1388 if ( !empty($ID) ) {
1391 $old_user_data = get_userdata($ID);
1394 // Hash the password
1395 $user_pass = wp_hash_password($user_pass);
1398 $user_login = sanitize_user($user_login, true);
1399 $user_login = apply_filters('pre_user_login', $user_login);
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);
1404 if ( empty($user_login) )
1405 return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
1407 if ( !$update && username_exists( $user_login ) )
1408 return new WP_Error('existing_user_login', __('This username is already registered.') );
1410 if ( empty($user_nicename) )
1411 $user_nicename = sanitize_title( $user_login );
1412 $user_nicename = apply_filters('pre_user_nicename', $user_nicename);
1414 if ( empty($user_url) )
1416 $user_url = apply_filters('pre_user_url', $user_url);
1418 if ( empty($user_email) )
1420 $user_email = apply_filters('pre_user_email', $user_email);
1422 if ( !$update && ! defined( 'WP_IMPORTING' ) && email_exists($user_email) )
1423 return new WP_Error('existing_user_email', __('This email address is already registered.') );
1425 if ( empty($display_name) )
1426 $display_name = $user_login;
1427 $display_name = apply_filters('pre_user_display_name', $display_name);
1429 if ( empty($nickname) )
1430 $nickname = $user_login;
1431 $nickname = apply_filters('pre_user_nickname', $nickname);
1433 if ( empty($first_name) )
1435 $first_name = apply_filters('pre_user_first_name', $first_name);
1437 if ( empty($last_name) )
1439 $last_name = apply_filters('pre_user_last_name', $last_name);
1441 if ( empty($description) )
1443 $description = apply_filters('pre_user_description', $description);
1445 if ( empty($rich_editing) )
1446 $rich_editing = 'true';
1448 if ( empty($comment_shortcuts) )
1449 $comment_shortcuts = 'false';
1451 if ( empty($admin_color) )
1452 $admin_color = 'fresh';
1453 $admin_color = preg_replace('|[^a-z0-9 _.\-@]|i', '', $admin_color);
1455 if ( empty($use_ssl) )
1458 if ( empty($user_registered) )
1459 $user_registered = gmdate('Y-m-d H:i:s');
1461 if ( empty($show_admin_bar_front) )
1462 $show_admin_bar_front = 'true';
1464 if ( empty($show_admin_bar_admin) )
1465 $show_admin_bar_admin = is_multisite() ? 'true' : 'false';
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));
1469 if ( $user_nicename_check ) {
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));
1476 $user_nicename = $alt_user_nicename;
1479 $data = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
1480 $data = stripslashes_deep( $data );
1483 $wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
1484 $user_id = (int) $ID;
1486 $wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
1487 $user_id = (int) $wpdb->insert_id;
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 );
1501 $user = new WP_User($user_id);
1503 foreach ( _wp_get_user_contactmethods( $user ) as $method => $name ) {
1504 if ( empty($$method) )
1507 update_user_meta( $user_id, $method, $$method );
1511 $user->set_role($role);
1513 $user->set_role(get_option('default_role'));
1515 wp_cache_delete($user_id, 'users');
1516 wp_cache_delete($user_login, 'userlogins');
1519 do_action('profile_update', $user_id, $old_user_data);
1521 do_action('user_register', $user_id);
1527 * Update an user in the database.
1529 * It is possible to update a user's password by specifying the 'user_pass'
1530 * value in the $userdata parameter array.
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.
1535 * If current user's password is being updated, then the cookies will be
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
1542 * @param array $userdata An array of user data.
1543 * @return int The updated user's ID.
1545 function wp_update_user($userdata) {
1546 $ID = (int) $userdata['ID'];
1548 // First, get all of the original fields
1549 $user = get_userdata($ID);
1551 // Escape data pulled from DB.
1552 $user = add_magic_quotes(get_object_vars($user));
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']);
1560 wp_cache_delete($user[ 'user_email' ], 'useremail');
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);
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);
1579 * A simpler way of inserting an user into the database.
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.
1585 * @see wp_insert_user() More complete way to create a new user
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.
1592 function wp_create_user($username, $password, $email = '') {
1593 $user_login = esc_sql( $username );
1594 $user_email = esc_sql( $email );
1595 $user_pass = $password;
1597 $userdata = compact('user_login', 'user_email', 'user_pass');
1598 return wp_insert_user($userdata);
1603 * Set up the default contact methods
1608 * @param object $user User data object (optional)
1609 * @return array $user_contactmethods Array of contact methods and their labels.
1611 function _wp_get_user_contactmethods( $user = null ) {
1612 $user_contactmethods = array(
1614 'yim' => __('Yahoo IM'),
1615 'jabber' => __('Jabber / Google Talk')
1617 return apply_filters( 'user_contactmethods', $user_contactmethods, $user );