3 * WordPress user administration API.
6 * @subpackage Administration
10 * Creates a new user from the "Users" form using $_POST information.
12 * It seems that the first half is for backwards compatibility, but only
13 * has the ability to alter the user's role. WordPress core seems to
14 * use this function only in the second way, running edit_user() with
15 * no id so as to create a new user.
19 * @param int $user_id Optional. User ID.
20 * @return null|WP_Error|int Null when adding user, WP_Error or User ID integer when no parameters.
23 if ( func_num_args() ) { // The hackiest hack that ever did hack
24 global $current_user, $wp_roles;
25 $user_id = (int) func_get_arg( 0 );
27 if ( isset( $_POST['role'] ) ) {
28 $new_role = sanitize_text_field( $_POST['role'] );
29 // Don't let anyone with 'edit_users' (admins) edit their own role to something without it.
30 if ( $user_id != $current_user->id || $wp_roles->role_objects[$new_role]->has_cap( 'edit_users' ) ) {
31 // If the new role isn't editable by the logged-in user die with error
32 $editable_roles = get_editable_roles();
33 if ( !$editable_roles[$new_role] )
34 wp_die(__('You can’t give users that role.'));
36 $user = new WP_User( $user_id );
37 $user->set_role( $new_role );
41 add_action( 'user_register', 'add_user' ); // See above
47 * Edit user settings based on contents of $_POST
49 * Used on user-edit.php and profile.php to manage and process user options, passwords etc.
53 * @param int $user_id Optional. User ID.
54 * @return int user id of the updated user
56 function edit_user( $user_id = 0 ) {
57 global $current_user, $wp_roles, $wpdb;
58 if ( $user_id != 0 ) {
60 $user->ID = (int) $user_id;
61 $userdata = get_userdata( $user_id );
62 $user->user_login = $wpdb->escape( $userdata->user_login );
68 if ( !$update && isset( $_POST['user_login'] ) )
69 $user->user_login = sanitize_user($_POST['user_login'], true);
72 if ( isset( $_POST['pass1'] ))
73 $pass1 = $_POST['pass1'];
74 if ( isset( $_POST['pass2'] ))
75 $pass2 = $_POST['pass2'];
77 if ( isset( $_POST['role'] ) && current_user_can( 'edit_users' ) ) {
78 $new_role = sanitize_text_field( $_POST['role'] );
79 // Don't let anyone with 'edit_users' (admins) edit their own role to something without it.
80 if( $user_id != $current_user->id || $wp_roles->role_objects[$new_role]->has_cap( 'edit_users' ))
81 $user->role = $new_role;
83 // If the new role isn't editable by the logged-in user die with error
84 $editable_roles = get_editable_roles();
85 if ( !$editable_roles[$new_role] )
86 wp_die(__('You can’t give users that role.'));
89 if ( isset( $_POST['email'] ))
90 $user->user_email = sanitize_text_field( $_POST['email'] );
91 if ( isset( $_POST['url'] ) ) {
92 if ( empty ( $_POST['url'] ) || $_POST['url'] == 'http://' ) {
95 $user->user_url = sanitize_url( $_POST['url'] );
96 $user->user_url = preg_match('/^(https?|ftps?|mailto|news|irc|gopher|nntp|feed|telnet):/is', $user->user_url) ? $user->user_url : 'http://'.$user->user_url;
99 if ( isset( $_POST['first_name'] ) )
100 $user->first_name = sanitize_text_field( $_POST['first_name'] );
101 if ( isset( $_POST['last_name'] ) )
102 $user->last_name = sanitize_text_field( $_POST['last_name'] );
103 if ( isset( $_POST['nickname'] ) )
104 $user->nickname = sanitize_text_field( $_POST['nickname'] );
105 if ( isset( $_POST['display_name'] ) )
106 $user->display_name = sanitize_text_field( $_POST['display_name'] );
108 if ( isset( $_POST['description'] ) )
109 $user->description = trim( $_POST['description'] );
111 foreach ( _wp_get_user_contactmethods() as $method => $name ) {
112 if ( isset( $_POST[$method] ))
113 $user->$method = sanitize_text_field( $_POST[$method] );
117 $user->rich_editing = isset( $_POST['rich_editing'] ) && 'false' == $_POST['rich_editing'] ? 'false' : 'true';
118 $user->admin_color = isset( $_POST['admin_color'] ) ? sanitize_text_field( $_POST['admin_color'] ) : 'fresh';
121 $user->comment_shortcuts = isset( $_POST['comment_shortcuts'] ) && 'true' == $_POST['comment_shortcuts'] ? 'true' : '';
124 if ( !empty($_POST['use_ssl']) )
127 $errors = new WP_Error();
129 /* checking that username has been typed */
130 if ( $user->user_login == '' )
131 $errors->add( 'user_login', __( '<strong>ERROR</strong>: Please enter a username.' ));
133 /* checking the password has been typed twice */
134 do_action_ref_array( 'check_passwords', array ( $user->user_login, & $pass1, & $pass2 ));
137 if ( empty($pass1) && !empty($pass2) )
138 $errors->add( 'pass', __( '<strong>ERROR</strong>: You entered your new password only once.' ), array( 'form-field' => 'pass1' ) );
139 elseif ( !empty($pass1) && empty($pass2) )
140 $errors->add( 'pass', __( '<strong>ERROR</strong>: You entered your new password only once.' ), array( 'form-field' => 'pass2' ) );
143 $errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter your password.' ), array( 'form-field' => 'pass1' ) );
144 elseif ( empty($pass2) )
145 $errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter your password twice.' ), array( 'form-field' => 'pass2' ) );
148 /* Check for "\" in password */
149 if ( false !== strpos( stripslashes($pass1), "\\" ) )
150 $errors->add( 'pass', __( '<strong>ERROR</strong>: Passwords may not contain the character "\\".' ), array( 'form-field' => 'pass1' ) );
152 /* checking the password has been typed twice the same */
153 if ( $pass1 != $pass2 )
154 $errors->add( 'pass', __( '<strong>ERROR</strong>: Please enter the same password in the two password fields.' ), array( 'form-field' => 'pass1' ) );
156 if ( !empty( $pass1 ) )
157 $user->user_pass = $pass1;
159 if ( !$update && !validate_username( $user->user_login ) )
160 $errors->add( 'user_login', __( '<strong>ERROR</strong>: This username is invalid. Please enter a valid username.' ));
162 if ( !$update && username_exists( $user->user_login ) )
163 $errors->add( 'user_login', __( '<strong>ERROR</strong>: This username is already registered. Please choose another one.' ));
165 /* checking e-mail address */
166 if ( empty( $user->user_email ) ) {
167 $errors->add( 'empty_email', __( '<strong>ERROR</strong>: Please enter an e-mail address.' ), array( 'form-field' => 'email' ) );
168 } elseif ( !is_email( $user->user_email ) ) {
169 $errors->add( 'invalid_email', __( '<strong>ERROR</strong>: The e-mail address isn’t correct.' ), array( 'form-field' => 'email' ) );
170 } elseif ( ( $owner_id = email_exists($user->user_email) ) && $owner_id != $user->ID ) {
171 $errors->add( 'email_exists', __('<strong>ERROR</strong>: This email is already registered, please choose another one.'), array( 'form-field' => 'email' ) );
174 // Allow plugins to return their own errors.
175 do_action_ref_array('user_profile_update_errors', array ( &$errors, $update, &$user ) );
177 if ( $errors->get_error_codes() )
181 $user_id = wp_update_user( get_object_vars( $user ) );
183 $user_id = wp_insert_user( get_object_vars( $user ) );
184 wp_new_user_notification( $user_id, isset($_POST['send_password']) ? $pass1 : '' );
190 * {@internal Missing Short Description}}
192 * {@internal Missing Long Description}}
196 * @return array List of user IDs.
198 function get_author_user_ids() {
200 $level_key = $wpdb->prefix . 'user_level';
201 return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value != '0'", $level_key) );
205 * {@internal Missing Short Description}}
207 * {@internal Missing Long Description}}
211 * @param int $user_id User ID.
212 * @return array|bool List of editable authors. False if no editable users.
214 function get_editable_authors( $user_id ) {
217 $editable = get_editable_user_ids( $user_id );
222 $editable = join(',', $editable);
223 $authors = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($editable) ORDER BY display_name" );
226 return apply_filters('get_editable_authors', $authors);
230 * {@internal Missing Short Description}}
232 * {@internal Missing Long Description}}
236 * @param int $user_id User ID.
237 * @param bool $exclude_zeros Optional, default is true. Whether to exclude zeros.
240 function get_editable_user_ids( $user_id, $exclude_zeros = true, $post_type = 'post' ) {
243 $user = new WP_User( $user_id );
245 if ( ! $user->has_cap("edit_others_{$post_type}s") ) {
246 if ( $user->has_cap("edit_{$post_type}s") || $exclude_zeros == false )
247 return array($user->id);
252 $level_key = $wpdb->prefix . 'user_level';
254 $query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s", $level_key);
255 if ( $exclude_zeros )
256 $query .= " AND meta_value != '0'";
258 return $wpdb->get_col( $query );
262 * Fetch a filtered list of user roles that the current user is
265 * Simple function who's main purpose is to allow filtering of the
266 * list of roles in the $wp_roles object so that plugins can remove
267 * innappropriate ones depending on the situation or user making edits.
268 * Specifically because without filtering anyone with the edit_users
269 * capability can edit others to be administrators, even if they are
270 * only editors or authors. This filter allows admins to delegate
277 function get_editable_roles() {
280 $all_roles = $wp_roles->roles;
281 $editable_roles = apply_filters('editable_roles', $all_roles);
283 return $editable_roles;
287 * {@internal Missing Short Description}}
289 * {@internal Missing Long Description}}
295 function get_nonauthor_user_ids() {
297 $level_key = $wpdb->prefix . 'user_level';
299 return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value = '0'", $level_key) );
303 * Retrieve editable posts from other users.
307 * @param int $user_id User ID to not retrieve posts from.
308 * @param string $type Optional, defaults to 'any'. Post type to retrieve, can be 'draft' or 'pending'.
309 * @return array List of posts from others.
311 function get_others_unpublished_posts($user_id, $type='any') {
314 $editable = get_editable_user_ids( $user_id );
316 if ( in_array($type, array('draft', 'pending')) )
317 $type_sql = " post_status = '$type' ";
319 $type_sql = " ( post_status = 'draft' OR post_status = 'pending' ) ";
321 $dir = ( 'pending' == $type ) ? 'ASC' : 'DESC';
326 $editable = join(',', $editable);
327 $other_unpubs = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_title, post_author FROM $wpdb->posts WHERE post_type = 'post' AND $type_sql AND post_author IN ($editable) AND post_author != %d ORDER BY post_modified $dir", $user_id) );
330 return apply_filters('get_others_drafts', $other_unpubs);
334 * Retrieve drafts from other users.
338 * @param int $user_id User ID.
339 * @return array List of drafts from other users.
341 function get_others_drafts($user_id) {
342 return get_others_unpublished_posts($user_id, 'draft');
346 * Retrieve pending review posts from other users.
350 * @param int $user_id User ID.
351 * @return array List of posts with pending review post type from other users.
353 function get_others_pending($user_id) {
354 return get_others_unpublished_posts($user_id, 'pending');
358 * Retrieve user data and filter it.
362 * @param int $user_id User ID.
363 * @return object WP_User object with user data.
365 function get_user_to_edit( $user_id ) {
366 $user = new WP_User( $user_id );
368 $user_contactmethods = _wp_get_user_contactmethods();
369 foreach ($user_contactmethods as $method => $name) {
370 if ( empty( $user->{$method} ) )
371 $user->{$method} = '';
374 if ( empty($user->description) )
375 $user->description = '';
377 $user = sanitize_user_object($user, 'edit');
383 * Retrieve the user's drafts.
387 * @param int $user_id User ID.
390 function get_users_drafts( $user_id ) {
392 $query = $wpdb->prepare("SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'draft' AND post_author = %d ORDER BY post_modified DESC", $user_id);
393 $query = apply_filters('get_users_drafts', $query);
394 return $wpdb->get_results( $query );
398 * Remove user and optionally reassign posts and links to another user.
400 * If the $reassign parameter is not assigned to an User ID, then all posts will
401 * be deleted of that user. The action 'delete_user' that is passed the User ID
402 * being deleted will be run after the posts are either reassigned or deleted.
403 * The user meta will also be deleted that are for that User ID.
407 * @param int $id User ID.
408 * @param int $reassign Optional. Reassign posts and links to new User ID.
409 * @return bool True when finished.
411 function wp_delete_user($id, $reassign = 'novalue') {
415 $user = new WP_User($id);
417 // allow for transaction statement
418 do_action('delete_user', $id);
420 if ($reassign == 'novalue') {
421 $post_ids = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id) );
424 foreach ($post_ids as $post_id)
425 wp_delete_post($post_id);
429 $link_ids = $wpdb->get_col( $wpdb->prepare("SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id) );
432 foreach ( $link_ids as $link_id )
433 wp_delete_link($link_id);
437 $reassign = (int) $reassign;
438 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_author = %d WHERE post_author = %d", $reassign, $id) );
439 $wpdb->query( $wpdb->prepare("UPDATE $wpdb->links SET link_owner = %d WHERE link_owner = %d", $reassign, $id) );
442 // FINALLY, delete user
444 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d", $id) );
445 $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->users WHERE ID = %d", $id) );
447 wp_cache_delete($id, 'users');
448 wp_cache_delete($user->user_login, 'userlogins');
449 wp_cache_delete($user->user_email, 'useremail');
450 wp_cache_delete($user->user_nicename, 'userslugs');
452 // allow for commit transaction
453 do_action('deleted_user', $id);
459 * Remove all capabilities from user.
463 * @param int $id User ID.
465 function wp_revoke_user($id) {
468 $user = new WP_User($id);
469 $user->remove_all_caps();
472 if ( !class_exists('WP_User_Search') ) :
474 * WordPress User Search class.
477 * @author Mark Jaquith
479 class WP_User_Search {
482 * {@internal Missing Description}}
491 * {@internal Missing Description}}
509 * Role name that users have.
527 * Amount of users to display per page.
533 var $users_per_page = 50;
536 * {@internal Missing Description}}
545 * {@internal Missing Description}}
554 * {@internal Missing Description}}
563 * {@internal Missing Description}}
572 * {@internal Missing Description}}
578 var $query_from_where;
581 * {@internal Missing Description}}
587 var $total_users_for_query = 0;
590 * {@internal Missing Description}}
596 var $too_many_total_users = false;
599 * {@internal Missing Description}}
608 * {@internal Missing Description}}
617 * PHP4 Constructor - Sets up the object properties.
621 * @param string $search_term Search terms string.
622 * @param int $page Optional. Page ID.
623 * @param string $role Role name.
624 * @return WP_User_Search
626 function WP_User_Search ($search_term = '', $page = '', $role = '') {
627 $this->search_term = $search_term;
628 $this->raw_page = ( '' == $page ) ? false : (int) $page;
629 $this->page = (int) ( '' == $page ) ? 1 : $page;
632 $this->prepare_query();
634 $this->prepare_vars_for_template_usage();
639 * {@internal Missing Short Description}}
641 * {@internal Missing Long Description}}
646 function prepare_query() {
648 $this->first_user = ($this->page - 1) * $this->users_per_page;
649 $this->query_limit = $wpdb->prepare(" LIMIT %d, %d", $this->first_user, $this->users_per_page);
650 $this->query_sort = ' ORDER BY user_login';
652 if ( $this->search_term ) {
654 $search_sql = 'AND (';
655 foreach ( array('user_login', 'user_nicename', 'user_email', 'user_url', 'display_name') as $col )
656 $searches[] = $col . " LIKE '%$this->search_term%'";
657 $search_sql .= implode(' OR ', $searches);
661 $this->query_from_where = "FROM $wpdb->users";
663 $this->query_from_where .= $wpdb->prepare(" INNER JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id WHERE $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities' AND $wpdb->usermeta.meta_value LIKE %s", '%' . $this->role . '%');
665 $this->query_from_where .= " WHERE 1=1";
666 $this->query_from_where .= " $search_sql";
671 * {@internal Missing Short Description}}
673 * {@internal Missing Long Description}}
680 $this->results = $wpdb->get_col('SELECT ID ' . $this->query_from_where . $this->query_sort . $this->query_limit);
682 if ( $this->results )
683 $this->total_users_for_query = $wpdb->get_var('SELECT COUNT(ID) ' . $this->query_from_where); // no limit
685 $this->search_errors = new WP_Error('no_matching_users_found', __('No matching users were found!'));
689 * {@internal Missing Short Description}}
691 * {@internal Missing Long Description}}
696 function prepare_vars_for_template_usage() {
697 $this->search_term = stripslashes($this->search_term); // done with DB, from now on we want slashes gone
701 * {@internal Missing Short Description}}
703 * {@internal Missing Long Description}}
708 function do_paging() {
709 if ( $this->total_users_for_query > $this->users_per_page ) { // have to page the results
711 if( ! empty($this->search_term) )
712 $args['usersearch'] = urlencode($this->search_term);
713 if( ! empty($this->role) )
714 $args['role'] = urlencode($this->role);
716 $this->paging_text = paginate_links( array(
717 'total' => ceil($this->total_users_for_query / $this->users_per_page),
718 'current' => $this->page,
719 'base' => 'users.php?%_%',
720 'format' => 'userspage=%#%',
723 if ( $this->paging_text ) {
724 $this->paging_text = sprintf( '<span class="displaying-num">' . __( 'Displaying %s–%s of %s' ) . '</span>%s',
725 number_format_i18n( ( $this->page - 1 ) * $this->users_per_page + 1 ),
726 number_format_i18n( min( $this->page * $this->users_per_page, $this->total_users_for_query ) ),
727 number_format_i18n( $this->total_users_for_query ),
735 * {@internal Missing Short Description}}
737 * {@internal Missing Long Description}}
744 function get_results() {
745 return (array) $this->results;
749 * Displaying paging text.
751 * @see do_paging() Builds paging text.
756 function page_links() {
757 echo $this->paging_text;
761 * Whether paging is enabled.
763 * @see do_paging() Builds paging text.
770 function results_are_paged() {
771 if ( $this->paging_text )
777 * Whether there are search terms.
784 function is_search() {
785 if ( $this->search_term )
792 add_action('admin_init', 'default_password_nag_handler');
793 function default_password_nag_handler($errors = false) {
795 if ( ! get_usermeta($user_ID, 'default_password_nag') ) //Short circuit it.
798 //get_user_setting = JS saved UI setting. else no-js-falback code.
799 if ( 'hide' == get_user_setting('default_password_nag') || isset($_GET['default_password_nag']) && '0' == $_GET['default_password_nag'] ) {
800 delete_user_setting('default_password_nag');
801 update_usermeta($user_ID, 'default_password_nag', false);
805 add_action('profile_update', 'default_password_nag_edit_user', 10, 2);
806 function default_password_nag_edit_user($user_ID, $old_data) {
808 if ( ! get_usermeta($user_ID, 'default_password_nag') ) //Short circuit it.
811 $new_data = get_userdata($user_ID);
813 if ( $new_data->user_pass != $old_data->user_pass ) { //Remove the nag if the password has been changed.
814 delete_user_setting('default_password_nag');
815 update_usermeta($user_ID, 'default_password_nag', false);
819 add_action('admin_notices', 'default_password_nag');
820 function default_password_nag() {
822 if ( ! get_usermeta($user_ID, 'default_password_nag') )
825 echo '<div class="error default-password-nag"><p>';
826 printf(__("Notice: you're using the auto-generated password for your account. Would you like to change it to something you'll remember easier?<br />
827 <a href='%s'>Yes, Take me to my profile page</a> | <a href='%s' id='default-password-nag-no'>No Thanks, Do not remind me again.</a>"), admin_url('profile.php') . '#password', '?default_password_nag=0');