+/**
+ * Update all user caches
+ *
+ * @since 3.0.0
+ *
+ * @param object $user User object to be cached
+ */
+function update_user_caches($user) {
+ wp_cache_add($user->ID, $user, 'users');
+ wp_cache_add($user->user_login, $user->ID, 'userlogins');
+ wp_cache_add($user->user_email, $user->ID, 'useremail');
+ wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
+}
+
+/**
+ * Clean all user caches
+ *
+ * @since 3.0.0
+ *
+ * @param WP_User|int $user User object or ID to be cleaned from the cache
+ */
+function clean_user_cache( $user ) {
+ if ( is_numeric( $user ) )
+ $user = new WP_User( $user );
+
+ if ( ! $user->exists() )
+ return;
+
+ wp_cache_delete( $user->ID, 'users' );
+ wp_cache_delete( $user->user_login, 'userlogins' );
+ wp_cache_delete( $user->user_email, 'useremail' );
+ wp_cache_delete( $user->user_nicename, 'userslugs' );
+}
+
+/**
+ * Checks whether the given username exists.
+ *
+ * @since 2.0.0
+ *
+ * @param string $username Username.
+ * @return null|int The user's ID on success, and null on failure.
+ */
+function username_exists( $username ) {
+ if ( $user = get_user_by('login', $username ) ) {
+ return $user->ID;
+ } else {
+ return null;
+ }
+}
+
+/**
+ * Checks whether the given email exists.
+ *
+ * @since 2.1.0
+ *
+ * @param string $email Email.
+ * @return bool|int The user's ID on success, and false on failure.
+ */
+function email_exists( $email ) {
+ if ( $user = get_user_by('email', $email) )
+ return $user->ID;
+
+ return false;
+}
+
+/**
+ * Checks whether an username is valid.
+ *
+ * @since 2.0.1
+ * @uses apply_filters() Calls 'validate_username' hook on $valid check and $username as parameters
+ *
+ * @param string $username Username.
+ * @return bool Whether username given is valid
+ */
+function validate_username( $username ) {
+ $sanitized = sanitize_user( $username, true );
+ $valid = ( $sanitized == $username );
+ /**
+ * Filter whether the provided username is valid or not.
+ *
+ * @since 2.0.1
+ *
+ * @param bool $valid Whether given username is valid.
+ * @param string $username Username to check.
+ */
+ return apply_filters( 'validate_username', $valid, $username );
+}
+
+/**
+ * Insert an user into the database.
+ *
+ * Most of the $userdata array fields have filters associated with the values.
+ * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
+ * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
+ * by the field name. An example using 'description' would have the filter
+ * called, 'pre_user_description' that can be hooked into.
+ *
+ * The $userdata array can contain the following fields:
+ * 'ID' - An integer that will be used for updating an existing user.
+ * 'user_pass' - A string that contains the plain text password for the user.
+ * 'user_login' - A string that contains the user's username for logging in.
+ * 'user_nicename' - A string that contains a URL-friendly name for the user.
+ * The default is the user's username.
+ * 'user_url' - A string containing the user's URL for the user's web site.
+ * 'user_email' - A string containing the user's email address.
+ * 'display_name' - A string that will be shown on the site. Defaults to user's
+ * username. It is likely that you will want to change this, for appearance.
+ * 'nickname' - The user's nickname, defaults to the user's username.
+ * 'first_name' - The user's first name.
+ * 'last_name' - The user's last name.
+ * 'description' - A string containing content about the user.
+ * 'rich_editing' - A string for whether to enable the rich editor. False
+ * if not empty.
+ * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
+ * 'role' - A string used to set the user's role.
+ * 'jabber' - User's Jabber account.
+ * 'aim' - User's AOL IM account.
+ * 'yim' - User's Yahoo IM account.
+ *
+ * @since 2.0.0
+ *
+ * @global wpdb $wpdb WordPress database object for queries.
+ *
+ * @todo Hash-notate arguments array.
+ *
+ * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
+ * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created.
+ */
+function wp_insert_user( $userdata ) {
+ global $wpdb;
+
+ if ( is_a( $userdata, 'stdClass' ) )
+ $userdata = get_object_vars( $userdata );
+ elseif ( is_a( $userdata, 'WP_User' ) )
+ $userdata = $userdata->to_array();
+
+ extract( $userdata, EXTR_SKIP );
+
+ // Are we updating or creating?
+ if ( !empty($ID) ) {
+ $ID = (int) $ID;
+ $update = true;
+ $old_user_data = WP_User::get_data_by( 'id', $ID );
+ } else {
+ $update = false;
+ // Hash the password
+ $user_pass = wp_hash_password($user_pass);
+ }
+
+ $user_login = sanitize_user($user_login, true);
+
+ /**
+ * Filter a username after it has been sanitized.
+ *
+ * This filter is called before the user is created or updated.
+ *
+ * @since 2.0.3
+ *
+ * @param string $user_login Username after it has been sanitized.
+ */
+ $user_login = apply_filters( 'pre_user_login', $user_login );
+
+ //Remove any non-printable chars from the login string to see if we have ended up with an empty username
+ $user_login = trim($user_login);
+
+ if ( empty($user_login) )
+ return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
+
+ if ( !$update && username_exists( $user_login ) )
+ return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
+
+ if ( empty($user_nicename) )
+ $user_nicename = sanitize_title( $user_login );
+
+ /**
+ * Filter a user's nicename before the user is created or updated.
+ *
+ * @since 2.0.3
+ *
+ * @param string $user_nicename The user's nicename.
+ */
+ $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
+
+ if ( empty($user_url) )
+ $user_url = '';
+
+ /**
+ * Filter a user's URL before the user is created or updated.
+ *
+ * @since 2.0.3
+ *
+ * @param string $user_url The user's URL.
+ */
+ $user_url = apply_filters( 'pre_user_url', $user_url );
+
+ if ( empty($user_email) )
+ $user_email = '';
+
+ /**
+ * Filter a user's email before the user is created or updated.
+ *
+ * @since 2.0.3
+ *
+ * @param string $user_email The user's email.
+ */
+ $user_email = apply_filters( 'pre_user_email', $user_email );
+
+ if ( !$update && ! defined( 'WP_IMPORTING' ) && email_exists($user_email) )
+ return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
+
+ if ( empty($nickname) )
+ $nickname = $user_login;
+
+ /**
+ * Filter a user's nickname before the user is created or updated.
+ *
+ * @since 2.0.3
+ *
+ * @param string $nickname The user's nickname.
+ */
+ $nickname = apply_filters( 'pre_user_nickname', $nickname );
+
+ if ( empty($first_name) )
+ $first_name = '';
+
+ /**
+ * Filter a user's first name before the user is created or updated.
+ *
+ * @since 2.0.3
+ *
+ * @param string $first_name The user's first name.
+ */
+ $first_name = apply_filters( 'pre_user_first_name', $first_name );
+
+ if ( empty($last_name) )
+ $last_name = '';
+
+ /**
+ * Filter a user's last name before the user is created or updated.
+ *
+ * @since 2.0.3
+ *
+ * @param string $last_name The user's last name.
+ */
+ $last_name = apply_filters( 'pre_user_last_name', $last_name );
+
+ if ( empty( $display_name ) ) {
+ if ( $update )
+ $display_name = $user_login;
+ elseif ( $first_name && $last_name )
+ /* translators: 1: first name, 2: last name */
+ $display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $first_name, $last_name );
+ elseif ( $first_name )
+ $display_name = $first_name;
+ elseif ( $last_name )
+ $display_name = $last_name;
+ else
+ $display_name = $user_login;
+ }
+
+ /**
+ * Filter a user's display name before the user is created or updated.
+ *
+ * @since 2.0.3
+ *
+ * @param string $display_name The user's display name.
+ */
+ $display_name = apply_filters( 'pre_user_display_name', $display_name );
+
+ if ( empty($description) )
+ $description = '';
+
+ /**
+ * Filter a user's description before the user is created or updated.
+ *
+ * @since 2.0.3
+ *
+ * @param string $description The user's description.
+ */
+ $description = apply_filters( 'pre_user_description', $description );
+
+ if ( empty($rich_editing) )
+ $rich_editing = 'true';
+
+ if ( empty($comment_shortcuts) )
+ $comment_shortcuts = 'false';
+
+ if ( empty($admin_color) )
+ $admin_color = 'fresh';
+ $admin_color = preg_replace('|[^a-z0-9 _.\-@]|i', '', $admin_color);
+
+ if ( empty($use_ssl) )
+ $use_ssl = 0;
+
+ if ( empty($user_registered) )
+ $user_registered = gmdate('Y-m-d H:i:s');
+
+ if ( empty($show_admin_bar_front) )
+ $show_admin_bar_front = 'true';
+
+ $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));
+
+ if ( $user_nicename_check ) {
+ $suffix = 2;
+ while ($user_nicename_check) {
+ $alt_user_nicename = $user_nicename . "-$suffix";
+ $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));
+ $suffix++;
+ }
+ $user_nicename = $alt_user_nicename;
+ }
+
+ $data = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
+ $data = wp_unslash( $data );
+
+ if ( $update ) {
+ $wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
+ $user_id = (int) $ID;
+ } else {
+ $wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
+ $user_id = (int) $wpdb->insert_id;
+ }
+
+ $user = new WP_User( $user_id );
+
+ foreach ( _get_additional_user_keys( $user ) as $key ) {
+ if ( isset( $$key ) )
+ update_user_meta( $user_id, $key, $$key );
+ }
+
+ if ( isset($role) )
+ $user->set_role($role);
+ elseif ( !$update )
+ $user->set_role(get_option('default_role'));
+
+ wp_cache_delete($user_id, 'users');
+ wp_cache_delete($user_login, 'userlogins');
+
+ if ( $update ) {
+ /**
+ * Fires immediately after an existing user is updated.
+ *
+ * @since 2.0.0
+ *
+ * @param int $user_id User ID.
+ * @param object $old_user_data Object containing user's data prior to update.
+ */
+ do_action( 'profile_update', $user_id, $old_user_data );
+ } else {
+ /**
+ * Fires immediately after a new user is registered.
+ *
+ * @since 1.5.0
+ *
+ * @param int $user_id User ID.
+ */
+ do_action( 'user_register', $user_id );
+ }
+
+ return $user_id;
+}
+
+/**
+ * Update an user in the database.
+ *
+ * It is possible to update a user's password by specifying the 'user_pass'
+ * value in the $userdata parameter array.
+ *
+ * If current user's password is being updated, then the cookies will be
+ * cleared.
+ *
+ * @since 2.0.0
+ *
+ * @see wp_insert_user() For what fields can be set in $userdata.
+ *
+ * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
+ * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
+ */
+function wp_update_user($userdata) {
+ if ( is_a( $userdata, 'stdClass' ) )
+ $userdata = get_object_vars( $userdata );
+ elseif ( is_a( $userdata, 'WP_User' ) )
+ $userdata = $userdata->to_array();
+
+ $ID = (int) $userdata['ID'];
+
+ // First, get all of the original fields
+ $user_obj = get_userdata( $ID );
+ if ( ! $user_obj )
+ return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
+
+ $user = $user_obj->to_array();
+
+ // Add additional custom fields
+ foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
+ $user[ $key ] = get_user_meta( $ID, $key, true );
+ }
+
+ // Escape data pulled from DB.
+ $user = add_magic_quotes( $user );
+
+ // If password is changing, hash it now.
+ if ( ! empty($userdata['user_pass']) ) {
+ $plaintext_pass = $userdata['user_pass'];
+ $userdata['user_pass'] = wp_hash_password($userdata['user_pass']);
+ }
+
+ wp_cache_delete($user[ 'user_email' ], 'useremail');
+
+ // Merge old and new fields with new fields overwriting old ones.
+ $userdata = array_merge($user, $userdata);
+ $user_id = wp_insert_user($userdata);
+
+ // Update the cookies if the password changed.
+ $current_user = wp_get_current_user();
+ if ( $current_user->ID == $ID ) {
+ if ( isset($plaintext_pass) ) {
+ wp_clear_auth_cookie();
+ wp_set_auth_cookie($ID);
+ }
+ }
+
+ return $user_id;
+}
+
+/**
+ * A simpler way of inserting an user into the database.
+ *
+ * Creates a new user with just the username, password, and email. For more
+ * complex user creation use wp_insert_user() to specify more information.
+ *
+ * @since 2.0.0
+ * @see wp_insert_user() More complete way to create a new user
+ *
+ * @param string $username The user's username.
+ * @param string $password The user's password.
+ * @param string $email The user's email (optional).
+ * @return int The new user's ID.
+ */
+function wp_create_user($username, $password, $email = '') {
+ $user_login = wp_slash( $username );
+ $user_email = wp_slash( $email );
+ $user_pass = $password;
+
+ $userdata = compact('user_login', 'user_email', 'user_pass');
+ return wp_insert_user($userdata);
+}
+
+/**
+ * Return a list of meta keys that wp_insert_user() is supposed to set.
+ *
+ * @since 3.3.0
+ * @access private
+ *
+ * @param object $user WP_User instance.
+ * @return array
+ */
+function _get_additional_user_keys( $user ) {
+ $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front' );
+ return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
+}
+
+/**
+ * Set up the user contact methods.
+ *
+ * Default contact methods were removed in 3.6. A filter dictates contact methods.
+ *
+ * @since 3.7.0
+ *
+ * @param WP_User $user Optional. WP_User object.
+ * @return array Array of contact methods and their labels.
+ */
+function wp_get_user_contact_methods( $user = null ) {
+ $methods = array();
+ if ( get_site_option( 'initial_db_version' ) < 23588 ) {
+ $methods = array(
+ 'aim' => __( 'AIM' ),
+ 'yim' => __( 'Yahoo IM' ),
+ 'jabber' => __( 'Jabber / Google Talk' )
+ );
+ }
+
+ /**
+ * Filter the user contact methods.
+ *
+ * @since 2.9.0
+ *
+ * @param array $methods Array of contact methods and their labels.
+ * @param WP_User $user WP_User object.
+ */
+ return apply_filters( 'user_contactmethods', $methods, $user );
+}
+
+/**
+ * The old private function for setting up user contact methods.
+ *
+ * @since 2.9.0
+ * @access private
+ */
+function _wp_get_user_contactmethods( $user = null ) {
+ return wp_get_user_contact_methods( $user );
+}
+
+/**
+ * Retrieves a user row based on password reset key and login
+ *
+ * A key is considered 'expired' if it exactly matches the value of the
+ * user_activation_key field, rather than being matched after going through the
+ * hashing process. This field is now hashed; old values are no longer accepted
+ * but have a different WP_Error code so good user feedback can be provided.
+ *
+ * @global wpdb $wpdb WordPress database object for queries.
+ *
+ * @param string $key Hash to validate sending user's password.
+ * @param string $login The user login.
+ * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
+ */
+function check_password_reset_key($key, $login) {
+ global $wpdb, $wp_hasher;
+
+ $key = preg_replace('/[^a-z0-9]/i', '', $key);
+
+ if ( empty( $key ) || !is_string( $key ) )
+ return new WP_Error('invalid_key', __('Invalid key'));
+
+ if ( empty($login) || !is_string($login) )
+ return new WP_Error('invalid_key', __('Invalid key'));
+
+ $row = $wpdb->get_row( $wpdb->prepare( "SELECT ID, user_activation_key FROM $wpdb->users WHERE user_login = %s", $login ) );
+ if ( ! $row )
+ return new WP_Error('invalid_key', __('Invalid key'));
+
+ if ( empty( $wp_hasher ) ) {
+ require_once ABSPATH . 'wp-includes/class-phpass.php';
+ $wp_hasher = new PasswordHash( 8, true );
+ }
+
+ if ( $wp_hasher->CheckPassword( $key, $row->user_activation_key ) )
+ return get_userdata( $row->ID );
+
+ if ( $key === $row->user_activation_key ) {
+ $return = new WP_Error( 'expired_key', __( 'Invalid key' ) );
+ $user_id = $row->ID;
+
+ /**
+ * Filter the return value of check_password_reset_key() when an
+ * old-style key is used (plain-text key was stored in the database).
+ *
+ * @since 3.7.0
+ *
+ * @param WP_Error $return A WP_Error object denoting an expired key.
+ * Return a WP_User object to validate the key.
+ * @param int $user_id The matched user ID.
+ */
+ return apply_filters( 'password_reset_key_expired', $return, $user_id );
+ }
+
+ return new WP_Error( 'invalid_key', __( 'Invalid key' ) );
+}
+
+/**
+ * Handles resetting the user's password.
+ *
+ * @param object $user The user
+ * @param string $new_pass New password for the user in plaintext
+ */
+function reset_password( $user, $new_pass ) {
+ /**
+ * Fires before the user's password is reset.
+ *
+ * @since 1.5.0
+ *
+ * @param object $user The user.
+ * @param string $new_pass New user password.
+ */
+ do_action( 'password_reset', $user, $new_pass );
+
+ wp_set_password( $new_pass, $user->ID );
+ update_user_option( $user->ID, 'default_password_nag', false, true );
+
+ wp_password_change_notification( $user );
+}
+
+/**
+ * Handles registering a new user.
+ *
+ * @param string $user_login User's username for logging in
+ * @param string $user_email User's email address to send password and add
+ * @return int|WP_Error Either user's ID or error on failure.
+ */
+function register_new_user( $user_login, $user_email ) {
+ $errors = new WP_Error();
+
+ $sanitized_user_login = sanitize_user( $user_login );
+ /**
+ * Filter the email address of a user being registered.
+ *
+ * @since 2.1.0
+ *
+ * @param string $user_email The email address of the new user.
+ */
+ $user_email = apply_filters( 'user_registration_email', $user_email );
+
+ // Check the username
+ if ( $sanitized_user_login == '' ) {
+ $errors->add( 'empty_username', __( '<strong>ERROR</strong>: Please enter a username.' ) );
+ } elseif ( ! validate_username( $user_login ) ) {
+ $errors->add( 'invalid_username', __( '<strong>ERROR</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
+ $sanitized_user_login = '';
+ } elseif ( username_exists( $sanitized_user_login ) ) {
+ $errors->add( 'username_exists', __( '<strong>ERROR</strong>: This username is already registered. Please choose another one.' ) );
+ }
+
+ // Check the e-mail address
+ if ( $user_email == '' ) {
+ $errors->add( 'empty_email', __( '<strong>ERROR</strong>: Please type your e-mail address.' ) );
+ } elseif ( ! is_email( $user_email ) ) {
+ $errors->add( 'invalid_email', __( '<strong>ERROR</strong>: The email address isn’t correct.' ) );
+ $user_email = '';
+ } elseif ( email_exists( $user_email ) ) {
+ $errors->add( 'email_exists', __( '<strong>ERROR</strong>: This email is already registered, please choose another one.' ) );
+ }
+
+ /**
+ * Fires when submitting registration form data, before the user is created.
+ *
+ * @since 2.1.0
+ *
+ * @param string $sanitized_user_login The submitted username after being sanitized.
+ * @param string $user_email The submitted email.
+ * @param WP_Error $errors Contains any errors with submitted username and email,
+ * e.g., an empty field, an invalid username or email,
+ * or an existing username or email.
+ */
+ do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
+
+ /**
+ * Filter the errors encountered when a new user is being registered.
+ *
+ * The filtered WP_Error object may, for example, contain errors for an invalid
+ * or existing username or email address. A WP_Error object should always returned,
+ * but may or may not contain errors.
+ *
+ * If any errors are present in $errors, this will abort the user's registration.
+ *
+ * @since 2.1.0
+ *
+ * @param WP_Error $errors A WP_Error object containing any errors encountered
+ * during registration.
+ * @param string $sanitized_user_login User's username after it has been sanitized.
+ * @param string $user_email User's email.
+ */
+ $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
+
+ if ( $errors->get_error_code() )
+ return $errors;
+
+ $user_pass = wp_generate_password( 12, false );
+ $user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
+ if ( ! $user_id || is_wp_error( $user_id ) ) {
+ $errors->add( 'registerfail', sprintf( __( '<strong>ERROR</strong>: Couldn’t register you… please contact the <a href="mailto:%s">webmaster</a> !' ), get_option( 'admin_email' ) ) );
+ return $errors;
+ }
+
+ update_user_option( $user_id, 'default_password_nag', true, true ); //Set up the Password change nag.
+
+ wp_new_user_notification( $user_id, $user_pass );
+
+ return $user_id;
+}