10 * Authenticate user with remember capability.
12 * The credentials is an array that has 'user_login', 'user_password', and
13 * 'remember' indices. If the credentials is not given, then the log in form
14 * will be assumed and used if set.
16 * The various authentication cookies will be set by this function and will be
17 * set for a longer period depending on if the 'remember' credential is set to
22 * @param array $credentials Optional. User info in order to sign on.
23 * @param bool $secure_cookie Optional. Whether to use secure cookie.
24 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
26 function wp_signon( $credentials = array(), $secure_cookie = '' ) {
27 if ( empty($credentials) ) {
28 if ( ! empty($_POST['log']) )
29 $credentials['user_login'] = $_POST['log'];
30 if ( ! empty($_POST['pwd']) )
31 $credentials['user_password'] = $_POST['pwd'];
32 if ( ! empty($_POST['rememberme']) )
33 $credentials['remember'] = $_POST['rememberme'];
36 if ( !empty($credentials['remember']) )
37 $credentials['remember'] = true;
39 $credentials['remember'] = false;
42 * Fires before the user is authenticated.
44 * The variables passed to the callbacks are passed by reference,
45 * and can be modified by callback functions.
49 * @todo Decide whether to deprecate the wp_authenticate action.
51 * @param string $user_login Username, passed by reference.
52 * @param string $user_password User password, passed by reference.
54 do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );
56 if ( '' === $secure_cookie )
57 $secure_cookie = is_ssl();
60 * Filter whether to use a secure sign-on cookie.
64 * @param bool $secure_cookie Whether to use a secure sign-on cookie.
65 * @param array $credentials {
66 * Array of entered sign-on data.
68 * @type string $user_login Username.
69 * @type string $user_password Password entered.
70 * @type bool $remember Whether to 'remember' the user. Increases the time
71 * that the cookie will be kept. Default false.
74 $secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );
76 global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
77 $auth_secure_cookie = $secure_cookie;
79 add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
81 $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
83 if ( is_wp_error($user) ) {
84 if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
85 $user = new WP_Error('', '');
91 wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
93 * Fires after the user has successfully logged in.
97 * @param string $user_login Username.
98 * @param WP_User $user WP_User object of the logged-in user.
100 do_action( 'wp_login', $user->user_login, $user );
105 * Authenticate the user using the username and password.
109 * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
110 * @param string $username Username for authentication.
111 * @param string $password Password for authentication.
112 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
114 function wp_authenticate_username_password($user, $username, $password) {
115 if ( is_a( $user, 'WP_User' ) ) {
119 if ( empty($username) || empty($password) ) {
120 if ( is_wp_error( $user ) )
123 $error = new WP_Error();
125 if ( empty($username) )
126 $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
128 if ( empty($password) )
129 $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
134 $user = get_user_by('login', $username);
137 return new WP_Error( 'invalid_username', sprintf( __( '<strong>ERROR</strong>: Invalid username. <a href="%s" title="Password Lost and Found">Lost your password</a>?' ), wp_lostpassword_url() ) );
140 * Filter whether the given user can be authenticated with the provided $password.
144 * @param WP_User|WP_Error $user WP_User or WP_Error object if a previous
145 * callback failed authentication.
146 * @param string $password Password to check against the user.
148 $user = apply_filters( 'wp_authenticate_user', $user, $password );
149 if ( is_wp_error($user) )
152 if ( !wp_check_password($password, $user->user_pass, $user->ID) )
153 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>?' ),
154 $username, wp_lostpassword_url() ) );
160 * Authenticate the user using the WordPress auth cookie.
164 * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
165 * @param string $username Username. If not empty, cancels the cookie authentication.
166 * @param string $password Password. If not empty, cancels the cookie authentication.
167 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
169 function wp_authenticate_cookie($user, $username, $password) {
170 if ( is_a( $user, 'WP_User' ) ) {
174 if ( empty($username) && empty($password) ) {
175 $user_id = wp_validate_auth_cookie();
177 return new WP_User($user_id);
179 global $auth_secure_cookie;
181 if ( $auth_secure_cookie )
182 $auth_cookie = SECURE_AUTH_COOKIE;
184 $auth_cookie = AUTH_COOKIE;
186 if ( !empty($_COOKIE[$auth_cookie]) )
187 return new WP_Error('expired_session', __('Please log in again.'));
189 // If the cookie is not set, be silent.
196 * For Multisite blogs, check if the authenticated user has been marked as a
197 * spammer, or if the user's primary blog has been marked as spam.
201 * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
202 * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
204 function wp_authenticate_spam_check( $user ) {
205 if ( $user && is_a( $user, 'WP_User' ) && is_multisite() ) {
207 * Filter whether the user has been marked as a spammer.
211 * @param bool $spammed Whether the user is considered a spammer.
212 * @param WP_User $user User to check against.
214 $spammed = apply_filters( 'check_is_user_spammed', is_user_spammy(), $user );
217 return new WP_Error( 'spammer_account', __( '<strong>ERROR</strong>: Your account has been marked as a spammer.' ) );
223 * Validate the logged-in cookie.
225 * Checks the logged-in cookie if the previous auth cookie could not be
226 * validated and parsed.
228 * This is a callback for the determine_current_user filter, rather than API.
232 * @param int|bool $user The user ID (or false) as received from the
233 * determine_current_user filter.
234 * @return int|bool User ID if validated, false otherwise. If a user ID from
235 * an earlier filter callback is received, that value is returned.
237 function wp_validate_logged_in_cookie( $user_id ) {
242 if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[LOGGED_IN_COOKIE] ) ) {
246 return wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' );
250 * Number of posts user has written.
254 * @global wpdb $wpdb WordPress database object for queries.
256 * @param int $userid User ID.
257 * @return int Amount of posts user has written.
259 function count_user_posts($userid) {
262 $where = get_posts_by_author_sql('post', true, $userid);
264 $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
267 * Filter the number of posts a user has written.
271 * @param int $count The user's post count.
272 * @param int $userid User ID.
274 return apply_filters( 'get_usernumposts', $count, $userid );
278 * Number of posts written by a list of users.
282 * @param array $users Array of user IDs.
283 * @param string $post_type Optional. Post type to check. Defaults to post.
284 * @param bool $public_only Optional. Only return counts for public posts. Defaults to false.
285 * @return array Amount of posts each user has written.
287 function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
291 if ( empty( $users ) || ! is_array( $users ) )
294 $userlist = implode( ',', array_map( 'absint', $users ) );
295 $where = get_posts_by_author_sql( $post_type, true, null, $public_only );
297 $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
298 foreach ( $result as $row ) {
299 $count[ $row[0] ] = $row[1];
302 foreach ( $users as $id ) {
303 if ( ! isset( $count[ $id ] ) )
311 // User option functions
315 * Get the current user's ID
319 * @uses wp_get_current_user
321 * @return int The current user's ID
323 function get_current_user_id() {
324 if ( ! function_exists( 'wp_get_current_user' ) )
326 $user = wp_get_current_user();
327 return ( isset( $user->ID ) ? (int) $user->ID : 0 );
331 * Retrieve user option that can be either per Site or per Network.
333 * If the user ID is not given, then the current user will be used instead. If
334 * the user ID is given, then the user data will be retrieved. The filter for
335 * the result, will also pass the original option name and finally the user data
336 * object as the third parameter.
338 * The option will first check for the per site name and then the per Network name.
342 * @global wpdb $wpdb WordPress database object for queries.
344 * @param string $option User option name.
345 * @param int $user Optional. User ID.
346 * @param bool $deprecated Use get_option() to check for an option in the options table.
347 * @return mixed User option value on success, false on failure.
349 function get_user_option( $option, $user = 0, $deprecated = '' ) {
352 if ( !empty( $deprecated ) )
353 _deprecated_argument( __FUNCTION__, '3.0' );
355 if ( empty( $user ) )
356 $user = get_current_user_id();
358 if ( ! $user = get_userdata( $user ) )
361 $prefix = $wpdb->get_blog_prefix();
362 if ( $user->has_prop( $prefix . $option ) ) // Blog specific
363 $result = $user->get( $prefix . $option );
364 elseif ( $user->has_prop( $option ) ) // User specific and cross-blog
365 $result = $user->get( $option );
370 * Filter a specific user option value.
372 * The dynamic portion of the hook name, $option, refers to the user option name.
376 * @param mixed $result Value for the user's option.
377 * @param string $option Name of the option being retrieved.
378 * @param WP_User $user WP_User object of the user whose option is being retrieved.
380 return apply_filters( "get_user_option_{$option}", $result, $option, $user );
384 * Update user option with global blog capability.
386 * User options are just like user metadata except that they have support for
387 * global blog options. If the 'global' parameter is false, which it is by default
388 * it will prepend the WordPress table prefix to the option name.
390 * Deletes the user option if $newvalue is empty.
394 * @global wpdb $wpdb WordPress database object for queries.
396 * @param int $user_id User ID.
397 * @param string $option_name User option name.
398 * @param mixed $newvalue User option value.
399 * @param bool $global Optional. Whether option name is global or blog specific.
400 * Default false (blog specific).
401 * @return int|bool User meta ID if the option didn't exist, true on successful update,
404 function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
408 $option_name = $wpdb->get_blog_prefix() . $option_name;
410 return update_user_meta( $user_id, $option_name, $newvalue );
414 * Delete user option with global blog capability.
416 * User options are just like user metadata except that they have support for
417 * global blog options. If the 'global' parameter is false, which it is by default
418 * it will prepend the WordPress table prefix to the option name.
422 * @global wpdb $wpdb WordPress database object for queries.
424 * @param int $user_id User ID
425 * @param string $option_name User option name.
426 * @param bool $global Optional. Whether option name is global or blog specific.
427 * Default false (blog specific).
428 * @return bool True on success, false on failure.
430 function delete_user_option( $user_id, $option_name, $global = false ) {
434 $option_name = $wpdb->get_blog_prefix() . $option_name;
435 return delete_user_meta( $user_id, $option_name );
439 * WordPress User Query class.
443 class WP_User_Query {
446 * Query vars, after parsing
452 var $query_vars = array();
455 * List of found user ids
464 * Total number of found users for the current query
470 var $total_users = 0;
484 * @param string|array $args Optional. The query variables.
485 * @return WP_User_Query
487 function __construct( $query = null ) {
488 if ( ! empty( $query ) ) {
489 $this->prepare_query( $query );
495 * Prepare the query variables.
499 * @param string|array $args Optional. The query variables.
501 function prepare_query( $query = array() ) {
504 if ( empty( $this->query_vars ) || ! empty( $query ) ) {
505 $this->query_limit = null;
506 $this->query_vars = wp_parse_args( $query, array(
507 'blog_id' => $GLOBALS['blog_id'],
511 'meta_compare' => '',
512 'include' => array(),
513 'exclude' => array(),
515 'search_columns' => array(),
516 'orderby' => 'login',
520 'count_total' => true,
526 $qv =& $this->query_vars;
528 if ( is_array( $qv['fields'] ) ) {
529 $qv['fields'] = array_unique( $qv['fields'] );
531 $this->query_fields = array();
532 foreach ( $qv['fields'] as $field ) {
533 $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
534 $this->query_fields[] = "$wpdb->users.$field";
536 $this->query_fields = implode( ',', $this->query_fields );
537 } elseif ( 'all' == $qv['fields'] ) {
538 $this->query_fields = "$wpdb->users.*";
540 $this->query_fields = "$wpdb->users.ID";
543 if ( isset( $qv['count_total'] ) && $qv['count_total'] )
544 $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
546 $this->query_from = "FROM $wpdb->users";
547 $this->query_where = "WHERE 1=1";
550 if ( isset( $qv['orderby'] ) ) {
551 if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) {
552 $orderby = 'user_' . $qv['orderby'];
553 } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) {
554 $orderby = $qv['orderby'];
555 } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) {
556 $orderby = 'display_name';
557 } elseif ( 'post_count' == $qv['orderby'] ) {
558 // todo: avoid the JOIN
559 $where = get_posts_by_author_sql('post');
560 $this->query_from .= " LEFT OUTER JOIN (
561 SELECT post_author, COUNT(*) as post_count
565 ) p ON ({$wpdb->users}.ID = p.post_author)
567 $orderby = 'post_count';
568 } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) {
570 } elseif ( 'meta_value' == $qv['orderby'] ) {
571 $orderby = "$wpdb->usermeta.meta_value";
573 $orderby = 'user_login';
577 if ( empty( $orderby ) )
578 $orderby = 'user_login';
580 $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
581 if ( 'ASC' == $qv['order'] )
585 $this->query_orderby = "ORDER BY $orderby $order";
588 if ( isset( $qv['number'] ) && $qv['number'] ) {
590 $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
592 $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']);
596 if ( isset( $qv['search'] ) )
597 $search = trim( $qv['search'] );
600 $leading_wild = ( ltrim($search, '*') != $search );
601 $trailing_wild = ( rtrim($search, '*') != $search );
602 if ( $leading_wild && $trailing_wild )
604 elseif ( $leading_wild )
606 elseif ( $trailing_wild )
611 $search = trim($search, '*');
613 $search_columns = array();
614 if ( $qv['search_columns'] )
615 $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
616 if ( ! $search_columns ) {
617 if ( false !== strpos( $search, '@') )
618 $search_columns = array('user_email');
619 elseif ( is_numeric($search) )
620 $search_columns = array('user_login', 'ID');
621 elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
622 $search_columns = array('user_url');
624 $search_columns = array('user_login', 'user_nicename');
628 * Filter the columns to search in a WP_User_Query search.
630 * The default columns depend on the search term, and include 'user_email',
631 * 'user_login', 'ID', 'user_url', and 'user_nicename'.
635 * @param array $search_columns Array of column names to be searched.
636 * @param string $search Text being searched.
637 * @param WP_User_Query $this The current WP_User_Query instance.
639 $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
641 $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
645 if ( isset( $qv['blog_id'] ) )
646 $blog_id = absint( $qv['blog_id'] );
648 if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
649 $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
650 $qv['meta_value'] = 0;
651 $qv['meta_compare'] = '!=';
652 $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
656 if ( isset( $qv['role'] ) )
657 $role = trim( $qv['role'] );
659 if ( $blog_id && ( $role || is_multisite() ) ) {
660 $cap_meta_query = array();
661 $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities';
664 $cap_meta_query['value'] = '"' . $role . '"';
665 $cap_meta_query['compare'] = 'like';
668 if ( empty( $qv['meta_query'] ) || ! in_array( $cap_meta_query, $qv['meta_query'], true ) ) {
669 $qv['meta_query'][] = $cap_meta_query;
673 $meta_query = new WP_Meta_Query();
674 $meta_query->parse_query_vars( $qv );
676 if ( !empty( $meta_query->queries ) ) {
677 $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
678 $this->query_from .= $clauses['join'];
679 $this->query_where .= $clauses['where'];
681 if ( 'OR' == $meta_query->relation )
682 $this->query_fields = 'DISTINCT ' . $this->query_fields;
685 if ( ! empty( $qv['include'] ) ) {
686 $ids = implode( ',', wp_parse_id_list( $qv['include'] ) );
687 $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
688 } elseif ( ! empty( $qv['exclude'] ) ) {
689 $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
690 $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
694 * Fires after the WP_User_Query has been parsed, and before
695 * the query is executed.
697 * The passed WP_User_Query object contains SQL parts formed
698 * from parsing the given query.
702 * @param WP_User_Query $this The current WP_User_Query instance,
703 * passed by reference.
705 do_action_ref_array( 'pre_user_query', array( &$this ) );
709 * Execute the query, with the current variables.
713 * @global wpdb $wpdb WordPress database object for queries.
718 $qv =& $this->query_vars;
720 $query = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
722 if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
723 $this->results = $wpdb->get_results( $query );
725 $this->results = $wpdb->get_col( $query );
729 * Filter SELECT FOUND_ROWS() query for the current WP_User_Query instance.
733 * @global wpdb $wpdb WordPress database object.
735 * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
737 if ( isset( $qv['count_total'] ) && $qv['count_total'] )
738 $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
740 if ( !$this->results )
743 if ( 'all_with_meta' == $qv['fields'] ) {
744 cache_users( $this->results );
747 foreach ( $this->results as $userid )
748 $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
751 } elseif ( 'all' == $qv['fields'] ) {
752 foreach ( $this->results as $key => $user ) {
753 $this->results[ $key ] = new WP_User( $user );
759 * Retrieve query variable.
764 * @param string $query_var Query variable key.
767 function get( $query_var ) {
768 if ( isset( $this->query_vars[$query_var] ) )
769 return $this->query_vars[$query_var];
775 * Set query variable.
780 * @param string $query_var Query variable key.
781 * @param mixed $value Query variable value.
783 function set( $query_var, $value ) {
784 $this->query_vars[$query_var] = $value;
788 * Used internally to generate an SQL string for searching across multiple columns
793 * @param string $string
795 * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for
796 * single site. Single site allows leading and trailing wildcards, Network Admin only trailing.
799 function get_search_sql( $string, $cols, $wild = false ) {
800 $string = esc_sql( $string );
803 $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
804 $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
805 foreach ( $cols as $col ) {
807 $searches[] = "$col = '$string'";
809 $searches[] = "$col LIKE '$leading_wild" . like_escape($string) . "$trailing_wild'";
812 return ' AND (' . implode(' OR ', $searches) . ')';
816 * Return the list of users.
821 * @return array Array of results.
823 function get_results() {
824 return $this->results;
828 * Return the total number of users for the current query.
833 * @return array Array of total users.
835 function get_total() {
836 return $this->total_users;
841 * Retrieve list of users matching criteria.
845 * @uses WP_User_Query See for default arguments and information.
847 * @param array $args Optional. Array of arguments.
848 * @return array List of users.
850 function get_users( $args = array() ) {
852 $args = wp_parse_args( $args );
853 $args['count_total'] = false;
855 $user_search = new WP_User_Query($args);
857 return (array) $user_search->get_results();
861 * Get the blogs a user belongs to.
865 * @global wpdb $wpdb WordPress database object for queries.
867 * @param int $user_id User ID
868 * @param bool $all Whether to retrieve all blogs, or only blogs that are not
869 * marked as deleted, archived, or spam.
870 * @return array A list of the user's blogs. An empty array if the user doesn't exist
871 * or belongs to no blogs.
873 function get_blogs_of_user( $user_id, $all = false ) {
876 $user_id = (int) $user_id;
878 // Logged out users can't have blogs
879 if ( empty( $user_id ) )
882 $keys = get_user_meta( $user_id );
883 if ( empty( $keys ) )
886 if ( ! is_multisite() ) {
887 $blog_id = get_current_blog_id();
888 $blogs = array( $blog_id => new stdClass );
889 $blogs[ $blog_id ]->userblog_id = $blog_id;
890 $blogs[ $blog_id ]->blogname = get_option('blogname');
891 $blogs[ $blog_id ]->domain = '';
892 $blogs[ $blog_id ]->path = '';
893 $blogs[ $blog_id ]->site_id = 1;
894 $blogs[ $blog_id ]->siteurl = get_option('siteurl');
895 $blogs[ $blog_id ]->archived = 0;
896 $blogs[ $blog_id ]->spam = 0;
897 $blogs[ $blog_id ]->deleted = 0;
903 if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
904 $blog = get_blog_details( 1 );
905 if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
906 $blogs[ 1 ] = (object) array(
908 'blogname' => $blog->blogname,
909 'domain' => $blog->domain,
910 'path' => $blog->path,
911 'site_id' => $blog->site_id,
912 'siteurl' => $blog->siteurl,
918 unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
921 $keys = array_keys( $keys );
923 foreach ( $keys as $key ) {
924 if ( 'capabilities' !== substr( $key, -12 ) )
926 if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) )
928 $blog_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
929 if ( ! is_numeric( $blog_id ) )
932 $blog_id = (int) $blog_id;
933 $blog = get_blog_details( $blog_id );
934 if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) {
935 $blogs[ $blog_id ] = (object) array(
936 'userblog_id' => $blog_id,
937 'blogname' => $blog->blogname,
938 'domain' => $blog->domain,
939 'path' => $blog->path,
940 'site_id' => $blog->site_id,
941 'siteurl' => $blog->siteurl,
950 * Filter the list of blogs a user belongs to.
954 * @param array $blogs An array of blog objects belonging to the user.
955 * @param int $user_id User ID.
956 * @param bool $all Whether the returned blogs array should contain all blogs, including
957 * those marked 'deleted', 'archived', or 'spam'. Default false.
959 return apply_filters( 'get_blogs_of_user', $blogs, $user_id, $all );
963 * Find out whether a user is a member of a given blog.
966 * @uses get_blogs_of_user()
968 * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
969 * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
972 function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
973 $user_id = (int) $user_id;
974 $blog_id = (int) $blog_id;
976 if ( empty( $user_id ) )
977 $user_id = get_current_user_id();
979 if ( empty( $blog_id ) )
980 $blog_id = get_current_blog_id();
982 $blogs = get_blogs_of_user( $user_id );
983 return array_key_exists( $blog_id, $blogs );
987 * Add meta data field to a user.
989 * Post meta data is called "Custom Fields" on the Administration Screens.
992 * @uses add_metadata()
993 * @link http://codex.wordpress.org/Function_Reference/add_user_meta
995 * @param int $user_id User ID.
996 * @param string $meta_key Metadata name.
997 * @param mixed $meta_value Metadata value.
998 * @param bool $unique Optional, default is false. Whether the same key should not be added.
999 * @return int|bool Meta ID on success, false on failure.
1001 function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
1002 return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
1006 * Remove metadata matching criteria from a user.
1008 * You can match based on the key, or key and value. Removing based on key and
1009 * value, will keep from removing duplicate metadata with the same key. It also
1010 * allows removing all metadata matching key, if needed.
1013 * @uses delete_metadata()
1014 * @link http://codex.wordpress.org/Function_Reference/delete_user_meta
1016 * @param int $user_id user ID
1017 * @param string $meta_key Metadata name.
1018 * @param mixed $meta_value Optional. Metadata value.
1019 * @return bool True on success, false on failure.
1021 function delete_user_meta($user_id, $meta_key, $meta_value = '') {
1022 return delete_metadata('user', $user_id, $meta_key, $meta_value);
1026 * Retrieve user meta field for a user.
1029 * @uses get_metadata()
1030 * @link http://codex.wordpress.org/Function_Reference/get_user_meta
1032 * @param int $user_id User ID.
1033 * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
1034 * @param bool $single Whether to return a single value.
1035 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
1038 function get_user_meta($user_id, $key = '', $single = false) {
1039 return get_metadata('user', $user_id, $key, $single);
1043 * Update user meta field based on user ID.
1045 * Use the $prev_value parameter to differentiate between meta fields with the
1046 * same key and user ID.
1048 * If the meta field for the user does not exist, it will be added.
1051 * @uses update_metadata
1052 * @link http://codex.wordpress.org/Function_Reference/update_user_meta
1054 * @param int $user_id User ID.
1055 * @param string $meta_key Metadata key.
1056 * @param mixed $meta_value Metadata value.
1057 * @param mixed $prev_value Optional. Previous value to check before removing.
1058 * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
1060 function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
1061 return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
1065 * Count number of users who have each of the user roles.
1067 * Assumes there are neither duplicated nor orphaned capabilities meta_values.
1068 * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
1069 * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
1070 * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
1073 * @param string $strategy 'time' or 'memory'
1074 * @return array Includes a grand total and an array of counts indexed by role strings.
1076 function count_users($strategy = 'time') {
1077 global $wpdb, $wp_roles;
1080 $id = get_current_blog_id();
1081 $blog_prefix = $wpdb->get_blog_prefix($id);
1084 if ( 'time' == $strategy ) {
1087 if ( ! isset( $wp_roles ) )
1088 $wp_roles = new WP_Roles();
1090 $avail_roles = $wp_roles->get_names();
1092 // Build a CPU-intensive query that will return concise information.
1093 $select_count = array();
1094 foreach ( $avail_roles as $this_role => $name ) {
1095 $select_count[] = "COUNT(NULLIF(`meta_value` LIKE '%\"" . like_escape( $this_role ) . "\"%', false))";
1097 $select_count = implode(', ', $select_count);
1099 // Add the meta_value index to the selection list, then run the query.
1100 $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
1102 // Run the previous loop again to associate results with role names.
1104 $role_counts = array();
1105 foreach ( $avail_roles as $this_role => $name ) {
1106 $count = (int) $row[$col++];
1108 $role_counts[$this_role] = $count;
1112 // Get the meta_value index from the end of the result set.
1113 $total_users = (int) $row[$col];
1115 $result['total_users'] = $total_users;
1116 $result['avail_roles'] =& $role_counts;
1118 $avail_roles = array();
1120 $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
1122 foreach ( $users_of_blog as $caps_meta ) {
1123 $b_roles = maybe_unserialize($caps_meta);
1124 if ( ! is_array( $b_roles ) )
1126 foreach ( $b_roles as $b_role => $val ) {
1127 if ( isset($avail_roles[$b_role]) ) {
1128 $avail_roles[$b_role]++;
1130 $avail_roles[$b_role] = 1;
1135 $result['total_users'] = count( $users_of_blog );
1136 $result['avail_roles'] =& $avail_roles;
1143 // Private helper functions
1147 * Set up global user vars.
1149 * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
1152 * @global string $userdata User description.
1153 * @global string $user_login The user username for logging in
1154 * @global int $user_level The level of the user
1155 * @global int $user_ID The ID of the user
1156 * @global string $user_email The email address of the user
1157 * @global string $user_url The url in the user's profile
1158 * @global string $user_identity The display name of the user
1160 * @param int $for_user_id Optional. User ID to set up global data.
1162 function setup_userdata($for_user_id = '') {
1163 global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
1165 if ( '' == $for_user_id )
1166 $for_user_id = get_current_user_id();
1167 $user = get_userdata( $for_user_id );
1173 $user_login = $user_email = $user_url = $user_identity = '';
1177 $user_ID = (int) $user->ID;
1178 $user_level = (int) $user->user_level;
1180 $user_login = $user->user_login;
1181 $user_email = $user->user_email;
1182 $user_url = $user->user_url;
1183 $user_identity = $user->display_name;
1187 * Create dropdown HTML content of users.
1189 * The content can either be displayed, which it is by default or retrieved by
1190 * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
1191 * need to be used; all users will be displayed in that case. Only one can be
1192 * used, either 'include' or 'exclude', but not both.
1194 * The available arguments are as follows:
1196 * <li>show_option_all - Text to show all and whether HTML option exists.</li>
1197 * <li>show_option_none - Text for show none and whether HTML option exists.</li>
1198 * <li>hide_if_only_one_author - Don't create the dropdown if there is only one user.</li>
1199 * <li>orderby - SQL order by clause for what order the users appear. Default is 'display_name'.</li>
1200 * <li>order - Default is 'ASC'. Can also be 'DESC'.</li>
1201 * <li>include - User IDs to include.</li>
1202 * <li>exclude - User IDs to exclude.</li>
1203 * <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>
1204 * <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>
1205 * <li>echo - Default is '1'. Whether to display or retrieve content.</li>
1206 * <li>selected - Which User ID is selected.</li>
1207 * <li>include_selected - Always include the selected user ID in the dropdown. Default is false.</li>
1208 * <li>name - Default is 'user'. Name attribute of select element.</li>
1209 * <li>id - Default is the value of the 'name' parameter. ID attribute of select element.</li>
1210 * <li>class - Class attribute of select element.</li>
1211 * <li>blog_id - ID of blog (Multisite only). Defaults to ID of current blog.</li>
1212 * <li>who - Which users to query. Currently only 'authors' is supported. Default is all users.</li>
1217 * @global wpdb $wpdb WordPress database object for queries.
1219 * @todo Hash-notate arguments array.
1221 * @param string|array $args Optional. Array of user arguments.
1222 * @return string|null Null on display. String of HTML content on retrieve.
1224 function wp_dropdown_users( $args = '' ) {
1226 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '',
1227 'orderby' => 'display_name', 'order' => 'ASC',
1228 'include' => '', 'exclude' => '', 'multi' => 0,
1229 'show' => 'display_name', 'echo' => 1,
1230 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '',
1231 'blog_id' => $GLOBALS['blog_id'], 'who' => '', 'include_selected' => false
1234 $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
1236 $r = wp_parse_args( $args, $defaults );
1237 extract( $r, EXTR_SKIP );
1239 $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who' ) );
1240 $query_args['fields'] = array( 'ID', 'user_login', $show );
1241 $users = get_users( $query_args );
1244 if ( !empty($users) && ( empty($hide_if_only_one_author) || count($users) > 1 ) ) {
1245 $name = esc_attr( $name );
1246 if ( $multi && ! $id )
1249 $id = $id ? " id='" . esc_attr( $id ) . "'" : " id='$name'";
1251 $output = "<select name='{$name}'{$id} class='$class'>\n";
1253 if ( $show_option_all )
1254 $output .= "\t<option value='0'>$show_option_all</option>\n";
1256 if ( $show_option_none ) {
1257 $_selected = selected( -1, $selected, false );
1258 $output .= "\t<option value='-1'$_selected>$show_option_none</option>\n";
1261 $found_selected = false;
1262 foreach ( (array) $users as $user ) {
1263 $user->ID = (int) $user->ID;
1264 $_selected = selected( $user->ID, $selected, false );
1266 $found_selected = true;
1267 $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
1268 $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n";
1271 if ( $include_selected && ! $found_selected && ( $selected > 0 ) ) {
1272 $user = get_userdata( $selected );
1273 $_selected = selected( $user->ID, $selected, false );
1274 $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')';
1275 $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n";
1278 $output .= "</select>";
1282 * Filter the wp_dropdown_users() HTML output.
1286 * @param string $output HTML output generated by wp_dropdown_users().
1288 $output = apply_filters( 'wp_dropdown_users', $output );
1297 * Sanitize user field based on context.
1299 * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1300 * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1301 * when calling filters.
1305 * @param string $field The user Object field name.
1306 * @param mixed $value The user Object value.
1307 * @param int $user_id user ID.
1308 * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
1309 * 'attribute' and 'js'.
1310 * @return mixed Sanitized value.
1312 function sanitize_user_field($field, $value, $user_id, $context) {
1313 $int_fields = array('ID');
1314 if ( in_array($field, $int_fields) )
1315 $value = (int) $value;
1317 if ( 'raw' == $context )
1320 if ( !is_string($value) && !is_numeric($value) )
1323 $prefixed = false !== strpos( $field, 'user_' );
1325 if ( 'edit' == $context ) {
1328 /** This filter is documented in wp-includes/post.php */
1329 $value = apply_filters( "edit_{$field}", $value, $user_id );
1333 * Filter a user field value in the 'edit' context.
1335 * The dynamic portion of the hook name, $field, refers to the prefixed user
1336 * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1340 * @param mixed $value Value of the prefixed user field.
1341 * @param int $user_id User ID.
1343 $value = apply_filters( "edit_user_{$field}", $value, $user_id );
1346 if ( 'description' == $field )
1347 $value = esc_html( $value ); // textarea_escaped?
1349 $value = esc_attr($value);
1350 } else if ( 'db' == $context ) {
1352 /** This filter is documented in wp-includes/post.php */
1353 $value = apply_filters( "pre_{$field}", $value );
1357 * Filter the value of a user field in the 'db' context.
1359 * The dynamic portion of the hook name, $field, refers to the prefixed user
1360 * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1364 * @param mixed $value Value of the prefixed user field.
1366 $value = apply_filters( "pre_user_{$field}", $value );
1369 // Use display filters by default.
1372 /** This filter is documented in wp-includes/post.php */
1373 $value = apply_filters( $field, $value, $user_id, $context );
1377 * Filter the value of a user field in a standard context.
1379 * The dynamic portion of the hook name, $field, refers to the prefixed user
1380 * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1384 * @param mixed $value The user object value to sanitize.
1385 * @param int $user_id User ID.
1386 * @param string $context The context to filter within.
1388 $value = apply_filters( "user_{$field}", $value, $user_id, $context );
1392 if ( 'user_url' == $field )
1393 $value = esc_url($value);
1395 if ( 'attribute' == $context )
1396 $value = esc_attr($value);
1397 else if ( 'js' == $context )
1398 $value = esc_js($value);
1404 * Update all user caches
1408 * @param object $user User object to be cached
1410 function update_user_caches($user) {
1411 wp_cache_add($user->ID, $user, 'users');
1412 wp_cache_add($user->user_login, $user->ID, 'userlogins');
1413 wp_cache_add($user->user_email, $user->ID, 'useremail');
1414 wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
1418 * Clean all user caches
1422 * @param WP_User|int $user User object or ID to be cleaned from the cache
1424 function clean_user_cache( $user ) {
1425 if ( is_numeric( $user ) )
1426 $user = new WP_User( $user );
1428 if ( ! $user->exists() )
1431 wp_cache_delete( $user->ID, 'users' );
1432 wp_cache_delete( $user->user_login, 'userlogins' );
1433 wp_cache_delete( $user->user_email, 'useremail' );
1434 wp_cache_delete( $user->user_nicename, 'userslugs' );
1438 * Checks whether the given username exists.
1442 * @param string $username Username.
1443 * @return null|int The user's ID on success, and null on failure.
1445 function username_exists( $username ) {
1446 if ( $user = get_user_by('login', $username ) ) {
1454 * Checks whether the given email exists.
1458 * @param string $email Email.
1459 * @return bool|int The user's ID on success, and false on failure.
1461 function email_exists( $email ) {
1462 if ( $user = get_user_by('email', $email) )
1469 * Checks whether an username is valid.
1472 * @uses apply_filters() Calls 'validate_username' hook on $valid check and $username as parameters
1474 * @param string $username Username.
1475 * @return bool Whether username given is valid
1477 function validate_username( $username ) {
1478 $sanitized = sanitize_user( $username, true );
1479 $valid = ( $sanitized == $username );
1481 * Filter whether the provided username is valid or not.
1485 * @param bool $valid Whether given username is valid.
1486 * @param string $username Username to check.
1488 return apply_filters( 'validate_username', $valid, $username );
1492 * Insert an user into the database.
1494 * Most of the $userdata array fields have filters associated with the values.
1495 * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
1496 * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
1497 * by the field name. An example using 'description' would have the filter
1498 * called, 'pre_user_description' that can be hooked into.
1500 * The $userdata array can contain the following fields:
1501 * 'ID' - An integer that will be used for updating an existing user.
1502 * 'user_pass' - A string that contains the plain text password for the user.
1503 * 'user_login' - A string that contains the user's username for logging in.
1504 * 'user_nicename' - A string that contains a URL-friendly name for the user.
1505 * The default is the user's username.
1506 * 'user_url' - A string containing the user's URL for the user's web site.
1507 * 'user_email' - A string containing the user's email address.
1508 * 'display_name' - A string that will be shown on the site. Defaults to user's
1509 * username. It is likely that you will want to change this, for appearance.
1510 * 'nickname' - The user's nickname, defaults to the user's username.
1511 * 'first_name' - The user's first name.
1512 * 'last_name' - The user's last name.
1513 * 'description' - A string containing content about the user.
1514 * 'rich_editing' - A string for whether to enable the rich editor. False
1516 * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
1517 * 'role' - A string used to set the user's role.
1518 * 'jabber' - User's Jabber account.
1519 * 'aim' - User's AOL IM account.
1520 * 'yim' - User's Yahoo IM account.
1524 * @global wpdb $wpdb WordPress database object for queries.
1526 * @todo Hash-notate arguments array.
1528 * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
1529 * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created.
1531 function wp_insert_user( $userdata ) {
1534 if ( is_a( $userdata, 'stdClass' ) )
1535 $userdata = get_object_vars( $userdata );
1536 elseif ( is_a( $userdata, 'WP_User' ) )
1537 $userdata = $userdata->to_array();
1539 extract( $userdata, EXTR_SKIP );
1541 // Are we updating or creating?
1542 if ( !empty($ID) ) {
1545 $old_user_data = WP_User::get_data_by( 'id', $ID );
1548 // Hash the password
1549 $user_pass = wp_hash_password($user_pass);
1552 $user_login = sanitize_user($user_login, true);
1555 * Filter a username after it has been sanitized.
1557 * This filter is called before the user is created or updated.
1561 * @param string $user_login Username after it has been sanitized.
1563 $user_login = apply_filters( 'pre_user_login', $user_login );
1565 //Remove any non-printable chars from the login string to see if we have ended up with an empty username
1566 $user_login = trim($user_login);
1568 if ( empty($user_login) )
1569 return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
1571 if ( !$update && username_exists( $user_login ) )
1572 return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
1574 if ( empty($user_nicename) )
1575 $user_nicename = sanitize_title( $user_login );
1578 * Filter a user's nicename before the user is created or updated.
1582 * @param string $user_nicename The user's nicename.
1584 $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
1586 if ( empty($user_url) )
1590 * Filter a user's URL before the user is created or updated.
1594 * @param string $user_url The user's URL.
1596 $user_url = apply_filters( 'pre_user_url', $user_url );
1598 if ( empty($user_email) )
1602 * Filter a user's email before the user is created or updated.
1606 * @param string $user_email The user's email.
1608 $user_email = apply_filters( 'pre_user_email', $user_email );
1610 if ( !$update && ! defined( 'WP_IMPORTING' ) && email_exists($user_email) )
1611 return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
1613 if ( empty($nickname) )
1614 $nickname = $user_login;
1617 * Filter a user's nickname before the user is created or updated.
1621 * @param string $nickname The user's nickname.
1623 $nickname = apply_filters( 'pre_user_nickname', $nickname );
1625 if ( empty($first_name) )
1629 * Filter a user's first name before the user is created or updated.
1633 * @param string $first_name The user's first name.
1635 $first_name = apply_filters( 'pre_user_first_name', $first_name );
1637 if ( empty($last_name) )
1641 * Filter a user's last name before the user is created or updated.
1645 * @param string $last_name The user's last name.
1647 $last_name = apply_filters( 'pre_user_last_name', $last_name );
1649 if ( empty( $display_name ) ) {
1651 $display_name = $user_login;
1652 elseif ( $first_name && $last_name )
1653 /* translators: 1: first name, 2: last name */
1654 $display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $first_name, $last_name );
1655 elseif ( $first_name )
1656 $display_name = $first_name;
1657 elseif ( $last_name )
1658 $display_name = $last_name;
1660 $display_name = $user_login;
1664 * Filter a user's display name before the user is created or updated.
1668 * @param string $display_name The user's display name.
1670 $display_name = apply_filters( 'pre_user_display_name', $display_name );
1672 if ( empty($description) )
1676 * Filter a user's description before the user is created or updated.
1680 * @param string $description The user's description.
1682 $description = apply_filters( 'pre_user_description', $description );
1684 if ( empty($rich_editing) )
1685 $rich_editing = 'true';
1687 if ( empty($comment_shortcuts) )
1688 $comment_shortcuts = 'false';
1690 if ( empty($admin_color) )
1691 $admin_color = 'fresh';
1692 $admin_color = preg_replace('|[^a-z0-9 _.\-@]|i', '', $admin_color);
1694 if ( empty($use_ssl) )
1697 if ( empty($user_registered) )
1698 $user_registered = gmdate('Y-m-d H:i:s');
1700 if ( empty($show_admin_bar_front) )
1701 $show_admin_bar_front = 'true';
1703 $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));
1705 if ( $user_nicename_check ) {
1707 while ($user_nicename_check) {
1708 $alt_user_nicename = $user_nicename . "-$suffix";
1709 $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));
1712 $user_nicename = $alt_user_nicename;
1715 $data = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
1716 $data = wp_unslash( $data );
1719 $wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
1720 $user_id = (int) $ID;
1722 $wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
1723 $user_id = (int) $wpdb->insert_id;
1726 $user = new WP_User( $user_id );
1728 foreach ( _get_additional_user_keys( $user ) as $key ) {
1729 if ( isset( $$key ) )
1730 update_user_meta( $user_id, $key, $$key );
1734 $user->set_role($role);
1736 $user->set_role(get_option('default_role'));
1738 wp_cache_delete($user_id, 'users');
1739 wp_cache_delete($user_login, 'userlogins');
1743 * Fires immediately after an existing user is updated.
1747 * @param int $user_id User ID.
1748 * @param object $old_user_data Object containing user's data prior to update.
1750 do_action( 'profile_update', $user_id, $old_user_data );
1753 * Fires immediately after a new user is registered.
1757 * @param int $user_id User ID.
1759 do_action( 'user_register', $user_id );
1766 * Update an user in the database.
1768 * It is possible to update a user's password by specifying the 'user_pass'
1769 * value in the $userdata parameter array.
1771 * If current user's password is being updated, then the cookies will be
1776 * @see wp_insert_user() For what fields can be set in $userdata.
1778 * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
1779 * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
1781 function wp_update_user($userdata) {
1782 if ( is_a( $userdata, 'stdClass' ) )
1783 $userdata = get_object_vars( $userdata );
1784 elseif ( is_a( $userdata, 'WP_User' ) )
1785 $userdata = $userdata->to_array();
1787 $ID = (int) $userdata['ID'];
1789 // First, get all of the original fields
1790 $user_obj = get_userdata( $ID );
1792 return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
1794 $user = $user_obj->to_array();
1796 // Add additional custom fields
1797 foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
1798 $user[ $key ] = get_user_meta( $ID, $key, true );
1801 // Escape data pulled from DB.
1802 $user = add_magic_quotes( $user );
1804 // If password is changing, hash it now.
1805 if ( ! empty($userdata['user_pass']) ) {
1806 $plaintext_pass = $userdata['user_pass'];
1807 $userdata['user_pass'] = wp_hash_password($userdata['user_pass']);
1810 wp_cache_delete($user[ 'user_email' ], 'useremail');
1812 // Merge old and new fields with new fields overwriting old ones.
1813 $userdata = array_merge($user, $userdata);
1814 $user_id = wp_insert_user($userdata);
1816 // Update the cookies if the password changed.
1817 $current_user = wp_get_current_user();
1818 if ( $current_user->ID == $ID ) {
1819 if ( isset($plaintext_pass) ) {
1820 wp_clear_auth_cookie();
1821 wp_set_auth_cookie($ID);
1829 * A simpler way of inserting an user into the database.
1831 * Creates a new user with just the username, password, and email. For more
1832 * complex user creation use wp_insert_user() to specify more information.
1835 * @see wp_insert_user() More complete way to create a new user
1837 * @param string $username The user's username.
1838 * @param string $password The user's password.
1839 * @param string $email The user's email (optional).
1840 * @return int The new user's ID.
1842 function wp_create_user($username, $password, $email = '') {
1843 $user_login = wp_slash( $username );
1844 $user_email = wp_slash( $email );
1845 $user_pass = $password;
1847 $userdata = compact('user_login', 'user_email', 'user_pass');
1848 return wp_insert_user($userdata);
1852 * Return a list of meta keys that wp_insert_user() is supposed to set.
1857 * @param object $user WP_User instance.
1860 function _get_additional_user_keys( $user ) {
1861 $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front' );
1862 return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
1866 * Set up the user contact methods.
1868 * Default contact methods were removed in 3.6. A filter dictates contact methods.
1872 * @param WP_User $user Optional. WP_User object.
1873 * @return array Array of contact methods and their labels.
1875 function wp_get_user_contact_methods( $user = null ) {
1877 if ( get_site_option( 'initial_db_version' ) < 23588 ) {
1879 'aim' => __( 'AIM' ),
1880 'yim' => __( 'Yahoo IM' ),
1881 'jabber' => __( 'Jabber / Google Talk' )
1886 * Filter the user contact methods.
1890 * @param array $methods Array of contact methods and their labels.
1891 * @param WP_User $user WP_User object.
1893 return apply_filters( 'user_contactmethods', $methods, $user );
1897 * The old private function for setting up user contact methods.
1902 function _wp_get_user_contactmethods( $user = null ) {
1903 return wp_get_user_contact_methods( $user );
1907 * Retrieves a user row based on password reset key and login
1909 * A key is considered 'expired' if it exactly matches the value of the
1910 * user_activation_key field, rather than being matched after going through the
1911 * hashing process. This field is now hashed; old values are no longer accepted
1912 * but have a different WP_Error code so good user feedback can be provided.
1914 * @global wpdb $wpdb WordPress database object for queries.
1916 * @param string $key Hash to validate sending user's password.
1917 * @param string $login The user login.
1918 * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
1920 function check_password_reset_key($key, $login) {
1921 global $wpdb, $wp_hasher;
1923 $key = preg_replace('/[^a-z0-9]/i', '', $key);
1925 if ( empty( $key ) || !is_string( $key ) )
1926 return new WP_Error('invalid_key', __('Invalid key'));
1928 if ( empty($login) || !is_string($login) )
1929 return new WP_Error('invalid_key', __('Invalid key'));
1931 $row = $wpdb->get_row( $wpdb->prepare( "SELECT ID, user_activation_key FROM $wpdb->users WHERE user_login = %s", $login ) );
1933 return new WP_Error('invalid_key', __('Invalid key'));
1935 if ( empty( $wp_hasher ) ) {
1936 require_once ABSPATH . 'wp-includes/class-phpass.php';
1937 $wp_hasher = new PasswordHash( 8, true );
1940 if ( $wp_hasher->CheckPassword( $key, $row->user_activation_key ) )
1941 return get_userdata( $row->ID );
1943 if ( $key === $row->user_activation_key ) {
1944 $return = new WP_Error( 'expired_key', __( 'Invalid key' ) );
1945 $user_id = $row->ID;
1948 * Filter the return value of check_password_reset_key() when an
1949 * old-style key is used (plain-text key was stored in the database).
1953 * @param WP_Error $return A WP_Error object denoting an expired key.
1954 * Return a WP_User object to validate the key.
1955 * @param int $user_id The matched user ID.
1957 return apply_filters( 'password_reset_key_expired', $return, $user_id );
1960 return new WP_Error( 'invalid_key', __( 'Invalid key' ) );
1964 * Handles resetting the user's password.
1966 * @param object $user The user
1967 * @param string $new_pass New password for the user in plaintext
1969 function reset_password( $user, $new_pass ) {
1971 * Fires before the user's password is reset.
1975 * @param object $user The user.
1976 * @param string $new_pass New user password.
1978 do_action( 'password_reset', $user, $new_pass );
1980 wp_set_password( $new_pass, $user->ID );
1981 update_user_option( $user->ID, 'default_password_nag', false, true );
1983 wp_password_change_notification( $user );
1987 * Handles registering a new user.
1989 * @param string $user_login User's username for logging in
1990 * @param string $user_email User's email address to send password and add
1991 * @return int|WP_Error Either user's ID or error on failure.
1993 function register_new_user( $user_login, $user_email ) {
1994 $errors = new WP_Error();
1996 $sanitized_user_login = sanitize_user( $user_login );
1998 * Filter the email address of a user being registered.
2002 * @param string $user_email The email address of the new user.
2004 $user_email = apply_filters( 'user_registration_email', $user_email );
2006 // Check the username
2007 if ( $sanitized_user_login == '' ) {
2008 $errors->add( 'empty_username', __( '<strong>ERROR</strong>: Please enter a username.' ) );
2009 } elseif ( ! validate_username( $user_login ) ) {
2010 $errors->add( 'invalid_username', __( '<strong>ERROR</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
2011 $sanitized_user_login = '';
2012 } elseif ( username_exists( $sanitized_user_login ) ) {
2013 $errors->add( 'username_exists', __( '<strong>ERROR</strong>: This username is already registered. Please choose another one.' ) );
2016 // Check the e-mail address
2017 if ( $user_email == '' ) {
2018 $errors->add( 'empty_email', __( '<strong>ERROR</strong>: Please type your e-mail address.' ) );
2019 } elseif ( ! is_email( $user_email ) ) {
2020 $errors->add( 'invalid_email', __( '<strong>ERROR</strong>: The email address isn’t correct.' ) );
2022 } elseif ( email_exists( $user_email ) ) {
2023 $errors->add( 'email_exists', __( '<strong>ERROR</strong>: This email is already registered, please choose another one.' ) );
2027 * Fires when submitting registration form data, before the user is created.
2031 * @param string $sanitized_user_login The submitted username after being sanitized.
2032 * @param string $user_email The submitted email.
2033 * @param WP_Error $errors Contains any errors with submitted username and email,
2034 * e.g., an empty field, an invalid username or email,
2035 * or an existing username or email.
2037 do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
2040 * Filter the errors encountered when a new user is being registered.
2042 * The filtered WP_Error object may, for example, contain errors for an invalid
2043 * or existing username or email address. A WP_Error object should always returned,
2044 * but may or may not contain errors.
2046 * If any errors are present in $errors, this will abort the user's registration.
2050 * @param WP_Error $errors A WP_Error object containing any errors encountered
2051 * during registration.
2052 * @param string $sanitized_user_login User's username after it has been sanitized.
2053 * @param string $user_email User's email.
2055 $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
2057 if ( $errors->get_error_code() )
2060 $user_pass = wp_generate_password( 12, false );
2061 $user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
2062 if ( ! $user_id || is_wp_error( $user_id ) ) {
2063 $errors->add( 'registerfail', sprintf( __( '<strong>ERROR</strong>: Couldn’t register you… please contact the <a href="mailto:%s">webmaster</a> !' ), get_option( 'admin_email' ) ) );
2067 update_user_option( $user_id, 'default_password_nag', true, true ); //Set up the Password change nag.
2069 wp_new_user_notification( $user_id, $user_pass );