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 $user_ids Array of user IDs.
169 * @param string|array $post_type Optional. Post type to check. Defaults to post.
170 * @return array Amount of posts each user has written.
172 function count_many_users_posts($users, $post_type = 'post' ) {
176 if ( empty( $users ) || ! is_array( $users ) )
179 $userlist = implode( ',', array_map( 'absint', $users ) );
180 $where = get_posts_by_author_sql( $post_type );
182 $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
183 foreach ( $result as $row ) {
184 $count[ $row[0] ] = $row[1];
187 foreach ( $users as $id ) {
188 if ( ! isset( $count[ $id ] ) )
196 * Check that the user login name and password is correct.
199 * @todo xmlrpc only. Maybe move to xmlrpc.php.
201 * @param string $user_login User name.
202 * @param string $user_pass User password.
203 * @return bool False if does not authenticate, true if username and password authenticates.
205 function user_pass_ok($user_login, $user_pass) {
206 $user = wp_authenticate($user_login, $user_pass);
207 if ( is_wp_error($user) )
214 // User option functions
218 * Get the current user's ID
222 * @uses wp_get_current_user
224 * @return int The current user's ID
226 function get_current_user_id() {
227 $user = wp_get_current_user();
228 return ( isset( $user->ID ) ? (int) $user->ID : 0 );
232 * Retrieve user option that can be either per Site or per Network.
234 * If the user ID is not given, then the current user will be used instead. If
235 * the user ID is given, then the user data will be retrieved. The filter for
236 * the result, will also pass the original option name and finally the user data
237 * object as the third parameter.
239 * The option will first check for the per site name and then the per Network name.
242 * @uses $wpdb WordPress database object for queries.
243 * @uses apply_filters() Calls 'get_user_option_$option' hook with result,
244 * option parameter, and user data object.
246 * @param string $option User option name.
247 * @param int $user Optional. User ID.
248 * @param bool $deprecated Use get_option() to check for an option in the options table.
251 function get_user_option( $option, $user = 0, $deprecated = '' ) {
254 if ( !empty( $deprecated ) )
255 _deprecated_argument( __FUNCTION__, '3.0' );
257 if ( empty($user) ) {
258 $user = wp_get_current_user();
262 $user = get_userdata($user);
264 // Keys used as object vars cannot have dashes.
265 $key = str_replace('-', '', $option);
267 if ( isset( $user->{$wpdb->prefix . $key} ) ) // Blog specific
268 $result = $user->{$wpdb->prefix . $key};
269 elseif ( isset( $user->{$key} ) ) // User specific and cross-blog
270 $result = $user->{$key};
274 return apply_filters("get_user_option_{$option}", $result, $option, $user);
278 * Update user option with global blog capability.
280 * User options are just like user metadata except that they have support for
281 * global blog options. If the 'global' parameter is false, which it is by default
282 * it will prepend the WordPress table prefix to the option name.
284 * Deletes the user option if $newvalue is empty.
287 * @uses $wpdb WordPress database object for queries
289 * @param int $user_id User ID
290 * @param string $option_name User option name.
291 * @param mixed $newvalue User option value.
292 * @param bool $global Optional. Whether option name is global or blog specific. Default false (blog specific).
295 function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
299 $option_name = $wpdb->prefix . $option_name;
301 // For backward compatibility. See differences between update_user_meta() and deprecated update_usermeta().
302 // http://core.trac.wordpress.org/ticket/13088
303 if ( is_null( $newvalue ) || is_scalar( $newvalue ) && empty( $newvalue ) )
304 return delete_user_meta( $user_id, $option_name );
306 return update_user_meta( $user_id, $option_name, $newvalue );
310 * Delete user option with global blog capability.
312 * User options are just like user metadata except that they have support for
313 * global blog options. If the 'global' parameter is false, which it is by default
314 * it will prepend the WordPress table prefix to the option name.
317 * @uses $wpdb WordPress database object for queries
319 * @param int $user_id User ID
320 * @param string $option_name User option name.
321 * @param bool $global Optional. Whether option name is global or blog specific. Default false (blog specific).
324 function delete_user_option( $user_id, $option_name, $global = false ) {
328 $option_name = $wpdb->prefix . $option_name;
329 return delete_user_meta( $user_id, $option_name );
333 * WordPress User Query class.
337 class WP_User_Query {
340 * List of found user ids
349 * Total number of found users for the current query
355 var $total_users = 0;
370 * @param string|array $args The query variables
371 * @return WP_User_Query
373 function __construct( $query = null ) {
374 if ( !empty( $query ) ) {
375 $this->query_vars = wp_parse_args( $query, array(
376 'blog_id' => $GLOBALS['blog_id'],
380 'meta_compare' => '',
381 'include' => array(),
382 'exclude' => array(),
384 'orderby' => 'login',
388 'count_total' => true,
393 $this->prepare_query();
399 * Prepare the query variables
404 function prepare_query() {
407 $qv = &$this->query_vars;
409 if ( is_array( $qv['fields'] ) ) {
410 $qv['fields'] = array_unique( $qv['fields'] );
412 $this->query_fields = array();
413 foreach ( $qv['fields'] as $field )
414 $this->query_fields[] = $wpdb->users . '.' . esc_sql( $field );
415 $this->query_fields = implode( ',', $this->query_fields );
416 } elseif ( 'all' == $qv['fields'] ) {
417 $this->query_fields = "$wpdb->users.*";
419 $this->query_fields = "$wpdb->users.ID";
422 if ( $this->query_vars['count_total'] )
423 $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
425 $this->query_from = "FROM $wpdb->users";
426 $this->query_where = "WHERE 1=1";
429 if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) {
430 $orderby = 'user_' . $qv['orderby'];
431 } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) {
432 $orderby = $qv['orderby'];
433 } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) {
434 $orderby = 'display_name';
435 } elseif ( 'post_count' == $qv['orderby'] ) {
436 // todo: avoid the JOIN
437 $where = get_posts_by_author_sql('post');
438 $this->query_from .= " LEFT OUTER JOIN (
439 SELECT post_author, COUNT(*) as post_count
443 ) p ON ({$wpdb->users}.ID = p.post_author)
445 $orderby = 'post_count';
446 } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
449 $orderby = 'user_login';
452 $qv['order'] = strtoupper( $qv['order'] );
453 if ( 'ASC' == $qv['order'] )
457 $this->query_orderby = "ORDER BY $orderby $order";
460 if ( $qv['number'] ) {
462 $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
464 $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
467 $search = trim( $qv['search'] );
469 $leading_wild = ( ltrim($search, '*') != $search );
470 $trailing_wild = ( rtrim($search, '*') != $search );
471 if ( $leading_wild && $trailing_wild )
473 elseif ( $leading_wild )
475 elseif ( $trailing_wild )
480 $search = trim($search, '*');
482 if ( false !== strpos( $search, '@') )
483 $search_columns = array('user_email');
484 elseif ( is_numeric($search) )
485 $search_columns = array('user_login', 'ID');
486 elseif ( preg_match('|^https?://|', $search) )
487 $search_columns = array('user_url');
489 $search_columns = array('user_login', 'user_nicename');
491 $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
494 $blog_id = absint( $qv['blog_id'] );
496 if ( 'authors' == $qv['who'] && $blog_id ) {
497 $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
498 $qv['meta_value'] = 0;
499 $qv['meta_compare'] = '!=';
500 $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
503 $role = trim( $qv['role'] );
505 if ( $blog_id && ( $role || is_multisite() ) ) {
506 $cap_meta_query = array();
507 $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
510 $cap_meta_query['value'] = '"' . $role . '"';
511 $cap_meta_query['compare'] = 'like';
514 $qv['meta_query'][] = $cap_meta_query;
517 $meta_query = new WP_Meta_Query();
518 $meta_query->parse_query_vars( $qv );
520 if ( !empty( $meta_query->queries ) ) {
521 $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
522 $this->query_from .= $clauses['join'];
523 $this->query_where .= $clauses['where'];
525 if ( 'OR' == $meta_query->relation )
526 $this->query_fields = 'DISTINCT ' . $this->query_fields;
529 if ( !empty( $qv['include'] ) ) {
530 $ids = implode( ',', wp_parse_id_list( $qv['include'] ) );
531 $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
532 } elseif ( !empty($qv['exclude']) ) {
533 $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
534 $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
537 do_action_ref_array( 'pre_user_query', array( &$this ) );
541 * Execute the query, with the current variables
549 if ( is_array( $this->query_vars['fields'] ) || 'all' == $this->query_vars['fields'] ) {
550 $this->results = $wpdb->get_results("SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit");
552 $this->results = $wpdb->get_col("SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit");
555 if ( $this->query_vars['count_total'] )
556 $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
558 if ( !$this->results )
561 if ( 'all_with_meta' == $this->query_vars['fields'] ) {
562 cache_users( $this->results );
565 foreach ( $this->results as $userid )
566 $r[ $userid ] = new WP_User( $userid, '', $this->query_vars['blog_id'] );
573 * Used internally to generate an SQL string for searching across multiple columns
578 * @param string $string
580 * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for
581 * single site. Single site allows leading and trailing wildcards, Network Admin only trailing.
584 function get_search_sql( $string, $cols, $wild = false ) {
585 $string = esc_sql( $string );
588 $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
589 $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
590 foreach ( $cols as $col ) {
592 $searches[] = "$col = '$string'";
594 $searches[] = "$col LIKE '$leading_wild" . like_escape($string) . "$trailing_wild'";
597 return ' AND (' . implode(' OR ', $searches) . ')';
601 * Return the list of users
608 function get_results() {
609 return $this->results;
613 * Return the total number of users for the current query
620 function get_total() {
621 return $this->total_users;
626 * Retrieve list of users matching criteria.
630 * @uses WP_User_Query See for default arguments and information.
632 * @param array $args Optional.
633 * @return array List of users.
635 function get_users( $args = array() ) {
637 $args = wp_parse_args( $args );
638 $args['count_total'] = false;
640 $user_search = new WP_User_Query($args);
642 return (array) $user_search->get_results();
646 * Get the blogs a user belongs to.
650 * @param int $id User Id
651 * @param bool $all Whether to retrieve all blogs or only blogs that are not marked as deleted, archived, or spam.
652 * @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.
654 function get_blogs_of_user( $id, $all = false ) {
657 if ( !is_multisite() ) {
658 $blog_id = get_current_blog_id();
660 $blogs[ $blog_id ]->userblog_id = $blog_id;
661 $blogs[ $blog_id ]->blogname = get_option('blogname');
662 $blogs[ $blog_id ]->domain = '';
663 $blogs[ $blog_id ]->path = '';
664 $blogs[ $blog_id ]->site_id = 1;
665 $blogs[ $blog_id ]->siteurl = get_option('siteurl');
669 $blogs = wp_cache_get( 'blogs_of_user-' . $id, 'users' );
671 // Try priming the new cache from the old cache
672 if ( false === $blogs ) {
673 $cache_suffix = $all ? '_all' : '_short';
674 $blogs = wp_cache_get( 'blogs_of_user_' . $id . $cache_suffix, 'users' );
675 if ( is_array( $blogs ) ) {
676 $blogs = array_keys( $blogs );
678 wp_cache_set( 'blogs_of_user-' . $id, $blogs, 'users' );
682 if ( false === $blogs ) {
683 $user = get_userdata( (int) $id );
687 $blogs = $match = array();
688 $prefix_length = strlen($wpdb->base_prefix);
689 foreach ( (array) $user as $key => $value ) {
690 if ( $prefix_length && substr($key, 0, $prefix_length) != $wpdb->base_prefix )
692 if ( substr($key, -12, 12) != 'capabilities' )
694 if ( preg_match( '/^' . $wpdb->base_prefix . '((\d+)_)?capabilities$/', $key, $match ) ) {
695 if ( count( $match ) > 2 )
696 $blogs[] = (int) $match[ 2 ];
701 wp_cache_set( 'blogs_of_user-' . $id, $blogs, 'users' );
704 $blog_deets = array();
705 foreach ( (array) $blogs as $blog_id ) {
706 $blog = get_blog_details( $blog_id );
707 if ( $blog && isset( $blog->domain ) && ( $all == true || $all == false && ( $blog->archived == 0 && $blog->spam == 0 && $blog->deleted == 0 ) ) ) {
708 $blog_deets[ $blog_id ]->userblog_id = $blog_id;
709 $blog_deets[ $blog_id ]->blogname = $blog->blogname;
710 $blog_deets[ $blog_id ]->domain = $blog->domain;
711 $blog_deets[ $blog_id ]->path = $blog->path;
712 $blog_deets[ $blog_id ]->site_id = $blog->site_id;
713 $blog_deets[ $blog_id ]->siteurl = $blog->siteurl;
717 return apply_filters( 'get_blogs_of_user', $blog_deets, $id, $all );
721 * Checks if the current user belong to a given blog.
725 * @param int $blog_id Blog ID
726 * @return bool True if the current users belong to $blog_id, false if not.
728 function is_blog_user( $blog_id = 0 ) {
731 $current_user = wp_get_current_user();
733 $blog_id = $wpdb->blogid;
735 $cap_key = $wpdb->base_prefix . $blog_id . '_capabilities';
737 if ( is_array($current_user->$cap_key) && in_array(1, $current_user->$cap_key) )
744 * Add meta data field to a user.
746 * Post meta data is called "Custom Fields" on the Administration Screens.
749 * @uses add_metadata()
750 * @link http://codex.wordpress.org/Function_Reference/add_user_meta
752 * @param int $user_id Post ID.
753 * @param string $meta_key Metadata name.
754 * @param mixed $meta_value Metadata value.
755 * @param bool $unique Optional, default is false. Whether the same key should not be added.
756 * @return bool False for failure. True for success.
758 function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
759 return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
763 * Remove metadata matching criteria from a user.
765 * You can match based on the key, or key and value. Removing based on key and
766 * value, will keep from removing duplicate metadata with the same key. It also
767 * allows removing all metadata matching key, if needed.
770 * @uses delete_metadata()
771 * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
773 * @param int $user_id user ID
774 * @param string $meta_key Metadata name.
775 * @param mixed $meta_value Optional. Metadata value.
776 * @return bool False for failure. True for success.
778 function delete_user_meta($user_id, $meta_key, $meta_value = '') {
779 return delete_metadata('user', $user_id, $meta_key, $meta_value);
783 * Retrieve user meta field for a user.
786 * @uses get_metadata()
787 * @link http://codex.wordpress.org/Function_Reference/get_user_meta
789 * @param int $user_id Post ID.
790 * @param string $key The meta key to retrieve.
791 * @param bool $single Whether to return a single value.
792 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
795 function get_user_meta($user_id, $key, $single = false) {
796 return get_metadata('user', $user_id, $key, $single);
800 * Update user meta field based on user ID.
802 * Use the $prev_value parameter to differentiate between meta fields with the
803 * same key and user ID.
805 * If the meta field for the user does not exist, it will be added.
808 * @uses update_metadata
809 * @link http://codex.wordpress.org/Function_Reference/update_user_meta
811 * @param int $user_id Post ID.
812 * @param string $meta_key Metadata key.
813 * @param mixed $meta_value Metadata value.
814 * @param mixed $prev_value Optional. Previous value to check before removing.
815 * @return bool False on failure, true if success.
817 function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
818 return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
822 * Count number of users who have each of the user roles.
824 * Assumes there are neither duplicated nor orphaned capabilities meta_values.
825 * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
826 * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
827 * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
830 * @param string $strategy 'time' or 'memory'
831 * @return array Includes a grand total and an array of counts indexed by role strings.
833 function count_users($strategy = 'time') {
834 global $wpdb, $wp_roles;
837 $id = get_current_blog_id();
838 $blog_prefix = $wpdb->get_blog_prefix($id);
841 if ( 'time' == $strategy ) {
844 if ( ! isset( $wp_roles ) )
845 $wp_roles = new WP_Roles();
847 $avail_roles = $wp_roles->get_names();
849 // Build a CPU-intensive query that will return concise information.
850 $select_count = array();
851 foreach ( $avail_roles as $this_role => $name ) {
852 $select_count[] = "COUNT(NULLIF(`meta_value` LIKE '%" . like_escape($this_role) . "%', FALSE))";
854 $select_count = implode(', ', $select_count);
856 // Add the meta_value index to the selection list, then run the query.
857 $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
859 // Run the previous loop again to associate results with role names.
861 $role_counts = array();
862 foreach ( $avail_roles as $this_role => $name ) {
863 $count = (int) $row[$col++];
865 $role_counts[$this_role] = $count;
869 // Get the meta_value index from the end of the result set.
870 $total_users = (int) $row[$col];
872 $result['total_users'] = $total_users;
873 $result['avail_roles'] =& $role_counts;
875 $avail_roles = array();
877 $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
879 foreach ( $users_of_blog as $caps_meta ) {
880 $b_roles = unserialize($caps_meta);
881 if ( is_array($b_roles) ) {
882 foreach ( $b_roles as $b_role => $val ) {
883 if ( isset($avail_roles[$b_role]) ) {
884 $avail_roles[$b_role]++;
886 $avail_roles[$b_role] = 1;
892 $result['total_users'] = count( $users_of_blog );
893 $result['avail_roles'] =& $avail_roles;
900 // Private helper functions
904 * Set up global user vars.
906 * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
909 * @global string $userdata User description.
910 * @global string $user_login The user username for logging in
911 * @global int $user_level The level of the user
912 * @global int $user_ID The ID of the user
913 * @global string $user_email The email address of the user
914 * @global string $user_url The url in the user's profile
915 * @global string $user_pass_md5 MD5 of the user's password
916 * @global string $user_identity The display name of the user
918 * @param int $for_user_id Optional. User ID to set up global data.
920 function setup_userdata($for_user_id = '') {
921 global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_pass_md5, $user_identity;
923 if ( '' == $for_user_id )
924 $user = wp_get_current_user();
926 $user = new WP_User($for_user_id);
928 $userdata = $user->data;
929 $user_ID = (int) $user->ID;
930 $user_level = (int) isset($user->user_level) ? $user->user_level : 0;
932 if ( 0 == $user->ID ) {
933 $user_login = $user_email = $user_url = $user_pass_md5 = $user_identity = '';
937 $user_login = $user->user_login;
938 $user_email = $user->user_email;
939 $user_url = $user->user_url;
940 $user_pass_md5 = md5($user->user_pass);
941 $user_identity = $user->display_name;
945 * Create dropdown HTML content of users.
947 * The content can either be displayed, which it is by default or retrieved by
948 * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
949 * need to be used; all users will be displayed in that case. Only one can be
950 * used, either 'include' or 'exclude', but not both.
952 * The available arguments are as follows:
954 * <li>show_option_all - Text to show all and whether HTML option exists.</li>
955 * <li>show_option_none - Text for show none and whether HTML option exists.</li>
956 * <li>hide_if_only_one_author - Don't create the dropdown if there is only one user.</li>
957 * <li>orderby - SQL order by clause for what order the users appear. Default is 'display_name'.</li>
958 * <li>order - Default is 'ASC'. Can also be 'DESC'.</li>
959 * <li>include - User IDs to include.</li>
960 * <li>exclude - User IDs to exclude.</li>
961 * <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>
962 * <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>
963 * <li>echo - Default is '1'. Whether to display or retrieve content.</li>
964 * <li>selected - Which User ID is selected.</li>
965 * <li>include_selected - Always include the selected user ID in the dropdown. Default is false.</li>
966 * <li>name - Default is 'user'. Name attribute of select element.</li>
967 * <li>id - Default is the value of the 'name' parameter. ID attribute of select element.</li>
968 * <li>class - Class attribute of select element.</li>
969 * <li>blog_id - ID of blog (Multisite only). Defaults to ID of current blog.</li>
970 * <li>who - Which users to query. Currently only 'authors' is supported. Default is all users.</li>
974 * @uses $wpdb WordPress database object for queries
976 * @param string|array $args Optional. Override defaults.
977 * @return string|null Null on display. String of HTML content on retrieve.
979 function wp_dropdown_users( $args = '' ) {
981 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '',
982 'orderby' => 'display_name', 'order' => 'ASC',
983 'include' => '', 'exclude' => '', 'multi' => 0,
984 'show' => 'display_name', 'echo' => 1,
985 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '',
986 'blog_id' => $GLOBALS['blog_id'], 'who' => '', 'include_selected' => false
989 $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
991 $r = wp_parse_args( $args, $defaults );
992 extract( $r, EXTR_SKIP );
994 $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who' ) );
995 $query_args['fields'] = array( 'ID', $show );
996 $users = get_users( $query_args );
999 if ( !empty($users) && ( empty($hide_if_only_one_author) || count($users) > 1 ) ) {
1000 $name = esc_attr( $name );
1001 if ( $multi && ! $id )
1004 $id = $id ? " id='" . esc_attr( $id ) . "'" : " id='$name'";
1006 $output = "<select name='{$name}'{$id} class='$class'>\n";
1008 if ( $show_option_all )
1009 $output .= "\t<option value='0'>$show_option_all</option>\n";
1011 if ( $show_option_none ) {
1012 $_selected = selected( -1, $selected, false );
1013 $output .= "\t<option value='-1'$_selected>$show_option_none</option>\n";
1016 $found_selected = false;
1017 foreach ( (array) $users as $user ) {
1018 $user->ID = (int) $user->ID;
1019 $_selected = selected( $user->ID, $selected, false );
1021 $found_selected = true;
1022 $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
1023 $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n";
1026 if ( $include_selected && ! $found_selected && ( $selected > 0 ) ) {
1027 $user = get_userdata( $selected );
1028 $_selected = selected( $user->ID, $selected, false );
1029 $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
1030 $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n";
1033 $output .= "</select>";
1036 $output = apply_filters('wp_dropdown_users', $output);
1045 * Add user meta data as properties to given user object.
1047 * The finished user data is cached, but the cache is not used to fill in the
1048 * user data for the given object. Once the function has been used, the cache
1049 * should be used to retrieve user data. The intention is if the current data
1050 * had been cached already, there would be no need to call this function.
1054 * @uses $wpdb WordPress database object for queries
1056 * @param object $user The user data object.
1058 function _fill_user( &$user ) {
1059 $metavalues = get_user_metavalues(array($user->ID));
1060 _fill_single_user($user, $metavalues[$user->ID]);
1064 * Perform the query to get the $metavalues array(s) needed by _fill_user and _fill_many_users
1067 * @param array $ids User ID numbers list.
1068 * @return array of arrays. The array is indexed by user_id, containing $metavalues object arrays.
1070 function get_user_metavalues($ids) {
1073 $ids = array_map('intval', $ids);
1074 foreach ( $ids as $id )
1075 $objects[$id] = array();
1077 $metas = update_meta_cache('user', $ids);
1079 foreach ( $metas as $id => $meta ) {
1080 foreach ( $meta as $key => $metavalues ) {
1081 foreach ( $metavalues as $value ) {
1082 $objects[$id][] = (object)array( 'user_id' => $id, 'meta_key' => $key, 'meta_value' => $value);
1091 * Unserialize user metadata, fill $user object, then cache everything.
1094 * @param object $user The User object.
1095 * @param array $metavalues An array of objects provided by get_user_metavalues()
1097 function _fill_single_user( &$user, &$metavalues ) {
1100 foreach ( $metavalues as $meta ) {
1101 $value = maybe_unserialize($meta->meta_value);
1102 // Keys used as object vars cannot have dashes.
1103 $key = str_replace('-', '', $meta->meta_key);
1104 $user->{$key} = $value;
1107 $level = $wpdb->prefix . 'user_level';
1108 if ( isset( $user->{$level} ) )
1109 $user->user_level = $user->{$level};
1111 // For backwards compat.
1112 if ( isset($user->first_name) )
1113 $user->user_firstname = $user->first_name;
1114 if ( isset($user->last_name) )
1115 $user->user_lastname = $user->last_name;
1116 if ( isset($user->description) )
1117 $user->user_description = $user->description;
1119 update_user_caches($user);
1123 * Take an array of user objects, fill them with metas, and cache them.
1126 * @param array $users User objects
1128 function _fill_many_users( &$users ) {
1130 foreach( $users as $user_object ) {
1131 $ids[] = $user_object->ID;
1134 $metas = get_user_metavalues($ids);
1136 foreach ( $users as $user_object ) {
1137 if ( isset($metas[$user_object->ID]) ) {
1138 _fill_single_user($user_object, $metas[$user_object->ID]);
1144 * Sanitize every user field.
1146 * If the context is 'raw', then the user object or array will get minimal santization of the int fields.
1149 * @uses sanitize_user_field() Used to sanitize the fields.
1151 * @param object|array $user The User Object or Array
1152 * @param string $context Optional, default is 'display'. How to sanitize user fields.
1153 * @return object|array The now sanitized User Object or Array (will be the same type as $user)
1155 function sanitize_user_object($user, $context = 'display') {
1156 if ( is_object($user) ) {
1157 if ( !isset($user->ID) )
1159 if ( isset($user->data) )
1160 $vars = get_object_vars( $user->data );
1162 $vars = get_object_vars($user);
1163 foreach ( array_keys($vars) as $field ) {
1164 if ( is_string($user->$field) || is_numeric($user->$field) )
1165 $user->$field = sanitize_user_field($field, $user->$field, $user->ID, $context);
1167 $user->filter = $context;
1169 if ( !isset($user['ID']) )
1171 foreach ( array_keys($user) as $field )
1172 $user[$field] = sanitize_user_field($field, $user[$field], $user['ID'], $context);
1173 $user['filter'] = $context;
1180 * Sanitize user field based on context.
1182 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1183 * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1184 * when calling filters.
1187 * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and
1188 * $user_id if $context == 'edit' and field name prefix == 'user_'.
1190 * @uses apply_filters() Calls 'edit_user_$field' passing $value and $user_id if $context == 'db'.
1191 * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'user_'.
1192 * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'user_'.
1194 * @uses apply_filters() Calls '$field' passing $value, $user_id and $context if $context == anything
1195 * other than 'raw', 'edit' and 'db' and field name prefix == 'user_'.
1196 * @uses apply_filters() Calls 'user_$field' passing $value if $context == anything other than 'raw',
1197 * 'edit' and 'db' and field name prefix != 'user_'.
1199 * @param string $field The user Object field name.
1200 * @param mixed $value The user Object value.
1201 * @param int $user_id user ID.
1202 * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
1203 * 'attribute' and 'js'.
1204 * @return mixed Sanitized value.
1206 function sanitize_user_field($field, $value, $user_id, $context) {
1207 $int_fields = array('ID');
1208 if ( in_array($field, $int_fields) )
1209 $value = (int) $value;
1211 if ( 'raw' == $context )
1214 if ( !is_string($value) && !is_numeric($value) )
1218 if ( false !== strpos($field, 'user_') ) {
1220 $field_no_prefix = str_replace('user_', '', $field);
1223 if ( 'edit' == $context ) {
1225 $value = apply_filters("edit_{$field}", $value, $user_id);
1227 $value = apply_filters("edit_user_{$field}", $value, $user_id);
1230 if ( 'description' == $field )
1231 $value = esc_html( $value ); // textarea_escaped?
1233 $value = esc_attr($value);
1234 } else if ( 'db' == $context ) {
1236 $value = apply_filters("pre_{$field}", $value);
1238 $value = apply_filters("pre_user_{$field}", $value);
1241 // Use display filters by default.
1243 $value = apply_filters($field, $value, $user_id, $context);
1245 $value = apply_filters("user_{$field}", $value, $user_id, $context);
1248 if ( 'user_url' == $field )
1249 $value = esc_url($value);
1251 if ( 'attribute' == $context )
1252 $value = esc_attr($value);
1253 else if ( 'js' == $context )
1254 $value = esc_js($value);
1260 * Update all user caches
1264 * @param object $user User object to be cached
1266 function update_user_caches(&$user) {
1267 wp_cache_add($user->ID, $user, 'users');
1268 wp_cache_add($user->user_login, $user->ID, 'userlogins');
1269 wp_cache_add($user->user_email, $user->ID, 'useremail');
1270 wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
1274 * Clean all user caches
1278 * @param int $id User ID
1280 function clean_user_cache($id) {
1281 $user = new WP_User($id);
1283 wp_cache_delete($id, 'users');
1284 wp_cache_delete($user->user_login, 'userlogins');
1285 wp_cache_delete($user->user_email, 'useremail');
1286 wp_cache_delete($user->user_nicename, 'userslugs');
1287 wp_cache_delete('blogs_of_user-' . $id, 'users');
1291 * Checks whether the given username exists.
1295 * @param string $username Username.
1296 * @return null|int The user's ID on success, and null on failure.
1298 function username_exists( $username ) {
1299 if ( $user = get_userdatabylogin( $username ) ) {
1307 * Checks whether the given email exists.
1312 * @param string $email Email.
1313 * @return bool|int The user's ID on success, and false on failure.
1315 function email_exists( $email ) {
1316 if ( $user = get_user_by_email($email) )
1323 * Checks whether an username is valid.
1326 * @uses apply_filters() Calls 'validate_username' hook on $valid check and $username as parameters
1328 * @param string $username Username.
1329 * @return bool Whether username given is valid
1331 function validate_username( $username ) {
1332 $sanitized = sanitize_user( $username, true );
1333 $valid = ( $sanitized == $username );
1334 return apply_filters( 'validate_username', $valid, $username );
1338 * Insert an user into the database.
1340 * Can update a current user or insert a new user based on whether the user's ID
1343 * Can be used to update the user's info (see below), set the user's role, and
1344 * set the user's preference on whether they want the rich editor on.
1346 * Most of the $userdata array fields have filters associated with the values.
1347 * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
1348 * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
1349 * by the field name. An example using 'description' would have the filter
1350 * called, 'pre_user_description' that can be hooked into.
1352 * The $userdata array can contain the following fields:
1353 * 'ID' - An integer that will be used for updating an existing user.
1354 * 'user_pass' - A string that contains the plain text password for the user.
1355 * 'user_login' - A string that contains the user's username for logging in.
1356 * 'user_nicename' - A string that contains a nicer looking name for the user.
1357 * The default is the user's username.
1358 * 'user_url' - A string containing the user's URL for the user's web site.
1359 * 'user_email' - A string containing the user's email address.
1360 * 'display_name' - A string that will be shown on the site. Defaults to user's
1361 * username. It is likely that you will want to change this, for appearance.
1362 * 'nickname' - The user's nickname, defaults to the user's username.
1363 * 'first_name' - The user's first name.
1364 * 'last_name' - The user's last name.
1365 * 'description' - A string containing content about the user.
1366 * 'rich_editing' - A string for whether to enable the rich editor. False
1368 * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
1369 * 'role' - A string used to set the user's role.
1370 * 'jabber' - User's Jabber account.
1371 * 'aim' - User's AOL IM account.
1372 * 'yim' - User's Yahoo IM account.
1375 * @uses $wpdb WordPress database layer.
1376 * @uses apply_filters() Calls filters for most of the $userdata fields with the prefix 'pre_user'. See note above.
1377 * @uses do_action() Calls 'profile_update' hook when updating giving the user's ID
1378 * @uses do_action() Calls 'user_register' hook when creating a new user giving the user's ID
1380 * @param array $userdata An array of user data.
1381 * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created.
1383 function wp_insert_user($userdata) {
1386 extract($userdata, EXTR_SKIP);
1388 // Are we updating or creating?
1389 if ( !empty($ID) ) {
1392 $old_user_data = get_userdata($ID);
1395 // Hash the password
1396 $user_pass = wp_hash_password($user_pass);
1399 $user_login = sanitize_user($user_login, true);
1400 $user_login = apply_filters('pre_user_login', $user_login);
1402 //Remove any non-printable chars from the login string to see if we have ended up with an empty username
1403 $user_login = trim($user_login);
1405 if ( empty($user_login) )
1406 return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
1408 if ( !$update && username_exists( $user_login ) )
1409 return new WP_Error('existing_user_login', __('This username is already registered.') );
1411 if ( empty($user_nicename) )
1412 $user_nicename = sanitize_title( $user_login );
1413 $user_nicename = apply_filters('pre_user_nicename', $user_nicename);
1415 if ( empty($user_url) )
1417 $user_url = apply_filters('pre_user_url', $user_url);
1419 if ( empty($user_email) )
1421 $user_email = apply_filters('pre_user_email', $user_email);
1423 if ( !$update && ! defined( 'WP_IMPORTING' ) && email_exists($user_email) )
1424 return new WP_Error('existing_user_email', __('This email address is already registered.') );
1426 if ( empty($display_name) )
1427 $display_name = $user_login;
1428 $display_name = apply_filters('pre_user_display_name', $display_name);
1430 if ( empty($nickname) )
1431 $nickname = $user_login;
1432 $nickname = apply_filters('pre_user_nickname', $nickname);
1434 if ( empty($first_name) )
1436 $first_name = apply_filters('pre_user_first_name', $first_name);
1438 if ( empty($last_name) )
1440 $last_name = apply_filters('pre_user_last_name', $last_name);
1442 if ( empty($description) )
1444 $description = apply_filters('pre_user_description', $description);
1446 if ( empty($rich_editing) )
1447 $rich_editing = 'true';
1449 if ( empty($comment_shortcuts) )
1450 $comment_shortcuts = 'false';
1452 if ( empty($admin_color) )
1453 $admin_color = 'fresh';
1454 $admin_color = preg_replace('|[^a-z0-9 _.\-@]|i', '', $admin_color);
1456 if ( empty($use_ssl) )
1459 if ( empty($user_registered) )
1460 $user_registered = gmdate('Y-m-d H:i:s');
1462 if ( empty($show_admin_bar_front) )
1463 $show_admin_bar_front = 'true';
1465 if ( empty($show_admin_bar_admin) )
1466 $show_admin_bar_admin = is_multisite() ? 'true' : 'false';
1468 $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));
1470 if ( $user_nicename_check ) {
1472 while ($user_nicename_check) {
1473 $alt_user_nicename = $user_nicename . "-$suffix";
1474 $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));
1477 $user_nicename = $alt_user_nicename;
1480 $data = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
1481 $data = stripslashes_deep( $data );
1484 $wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
1485 $user_id = (int) $ID;
1487 $wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
1488 $user_id = (int) $wpdb->insert_id;
1491 update_user_meta( $user_id, 'first_name', $first_name );
1492 update_user_meta( $user_id, 'last_name', $last_name );
1493 update_user_meta( $user_id, 'nickname', $nickname );
1494 update_user_meta( $user_id, 'description', $description );
1495 update_user_meta( $user_id, 'rich_editing', $rich_editing );
1496 update_user_meta( $user_id, 'comment_shortcuts', $comment_shortcuts );
1497 update_user_meta( $user_id, 'admin_color', $admin_color );
1498 update_user_meta( $user_id, 'use_ssl', $use_ssl );
1499 update_user_meta( $user_id, 'show_admin_bar_front', $show_admin_bar_front );
1500 update_user_meta( $user_id, 'show_admin_bar_admin', $show_admin_bar_admin );
1502 $user = new WP_User($user_id);
1504 foreach ( _wp_get_user_contactmethods( $user ) as $method => $name ) {
1505 if ( empty($$method) )
1508 update_user_meta( $user_id, $method, $$method );
1512 $user->set_role($role);
1514 $user->set_role(get_option('default_role'));
1516 wp_cache_delete($user_id, 'users');
1517 wp_cache_delete($user_login, 'userlogins');
1520 do_action('profile_update', $user_id, $old_user_data);
1522 do_action('user_register', $user_id);
1528 * Update an user in the database.
1530 * It is possible to update a user's password by specifying the 'user_pass'
1531 * value in the $userdata parameter array.
1533 * If $userdata does not contain an 'ID' key, then a new user will be created
1534 * and the new user's ID will be returned.
1536 * If current user's password is being updated, then the cookies will be
1540 * @see wp_insert_user() For what fields can be set in $userdata
1541 * @uses wp_insert_user() Used to update existing user or add new one if user doesn't exist already
1543 * @param array $userdata An array of user data.
1544 * @return int The updated user's ID.
1546 function wp_update_user($userdata) {
1547 $ID = (int) $userdata['ID'];
1549 // First, get all of the original fields
1550 $user = get_userdata($ID);
1552 // Escape data pulled from DB.
1553 $user = add_magic_quotes(get_object_vars($user));
1555 // If password is changing, hash it now.
1556 if ( ! empty($userdata['user_pass']) ) {
1557 $plaintext_pass = $userdata['user_pass'];
1558 $userdata['user_pass'] = wp_hash_password($userdata['user_pass']);
1561 wp_cache_delete($user[ 'user_email' ], 'useremail');
1563 // Merge old and new fields with new fields overwriting old ones.
1564 $userdata = array_merge($user, $userdata);
1565 $user_id = wp_insert_user($userdata);
1567 // Update the cookies if the password changed.
1568 $current_user = wp_get_current_user();
1569 if ( $current_user->id == $ID ) {
1570 if ( isset($plaintext_pass) ) {
1571 wp_clear_auth_cookie();
1572 wp_set_auth_cookie($ID);
1580 * A simpler way of inserting an user into the database.
1582 * Creates a new user with just the username, password, and email. For a more
1583 * detail creation of a user, use wp_insert_user() to specify more infomation.
1586 * @see wp_insert_user() More complete way to create a new user
1588 * @param string $username The user's username.
1589 * @param string $password The user's password.
1590 * @param string $email The user's email (optional).
1591 * @return int The new user's ID.
1593 function wp_create_user($username, $password, $email = '') {
1594 $user_login = esc_sql( $username );
1595 $user_email = esc_sql( $email );
1596 $user_pass = $password;
1598 $userdata = compact('user_login', 'user_email', 'user_pass');
1599 return wp_insert_user($userdata);
1604 * Set up the default contact methods
1609 * @param object $user User data object (optional)
1610 * @return array $user_contactmethods Array of contact methods and their labels.
1612 function _wp_get_user_contactmethods( $user = null ) {
1613 $user_contactmethods = array(
1615 'yim' => __('Yahoo IM'),
1616 'jabber' => __('Jabber / Google Talk')
1618 return apply_filters( 'user_contactmethods', $user_contactmethods, $user );