File "user-20241117115223-20241118164832.php"

Full Path: /home2/sdektunc/cepali.edu.mx/wp-includes/style-engine/user-20241117115223-20241118164832.php
File size: 84 KB
MIME-type: text/x-php
Charset: utf-8

<?php
/**
 * Core User API
 *
 * @package WordPress
 * @subpackage Users
 */

/**
 * Authenticates and logs a user in with 'remember' capability.
 *
 * The credentials is an array that has 'user_login', 'user_password', and
 * 'remember' indices. If the credentials is not given, then the log in form
 * will be assumed and used if set.
 *
 * The various authentication cookies will be set by this function and will be
 * set for a longer period depending on if the 'remember' credential is set to
 * true.
 *
 * Note: wp_signon() doesn't handle setting the current user. This means that if the
 * function is called before the {@see 'init'} hook is fired, is_user_logged_in() will
 * evaluate as false until that point. If is_user_logged_in() is needed in conjunction
 * with wp_signon(), wp_set_current_user() should be called explicitly.
 *
 * @since 2.5.0
 *
 * @global string $auth_secure_cookie
 *
 * @param array       $credentials {
 *     Optional. User info in order to sign on.
 *
 *     @type string $user_login    Username.
 *     @type string $user_password User password.
 *     @type bool   $remember      Whether to 'remember' the user. Increases the time
 *                                 that the cookie will be kept. Default false.
 * }
 * @param string|bool $secure_cookie Optional. Whether to use secure cookie.
 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 */
function wp_signon( $credentials = array(), $secure_cookie = '' ) {
	if ( empty( $credentials ) ) {
		$credentials = array(
			'user_login'    => '',
			'user_password' => '',
			'remember'      => false,
		);

		if ( ! empty( $_POST['log'] ) ) {
			$credentials['user_login'] = wp_unslash( $_POST['log'] );
		}
		if ( ! empty( $_POST['pwd'] ) ) {
			$credentials['user_password'] = $_POST['pwd'];
		}
		if ( ! empty( $_POST['rememberme'] ) ) {
			$credentials['remember'] = $_POST['rememberme'];
		}
	}

	if ( ! empty( $credentials['remember'] ) ) {
		$credentials['remember'] = true;
	} else {
		$credentials['remember'] = false;
	}

	/**
	 * Fires before the user is authenticated.
	 *
	 * The variables passed to the callbacks are passed by reference,
	 * and can be modified by callback functions.
	 *
	 * @since 1.5.1
	 *
	 * @todo Decide whether to deprecate the wp_authenticate action.
	 *
	 * @param string $user_login    Username (passed by reference).
	 * @param string $user_password User password (passed by reference).
	 */
	do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );

	if ( '' === $secure_cookie ) {
		$secure_cookie = is_ssl();
	}

	/**
	 * Filters whether to use a secure sign-on cookie.
	 *
	 * @since 3.1.0
	 *
	 * @param bool  $secure_cookie Whether to use a secure sign-on cookie.
	 * @param array $credentials {
	 *     Array of entered sign-on data.
	 *
	 *     @type string $user_login    Username.
	 *     @type string $user_password Password entered.
	 *     @type bool   $remember      Whether to 'remember' the user. Increases the time
	 *                                 that the cookie will be kept. Default false.
	 * }
	 */
	$secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );

	global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie().
	$auth_secure_cookie = $secure_cookie;

	add_filter( 'authenticate', 'wp_authenticate_cookie', 30, 3 );

	$user = wp_authenticate( $credentials['user_login'], $credentials['user_password'] );

	if ( is_wp_error( $user ) ) {
		return $user;
	}

	wp_set_auth_cookie( $user->ID, $credentials['remember'], $secure_cookie );
	/**
	 * Fires after the user has successfully logged in.
	 *
	 * @since 1.5.0
	 *
	 * @param string  $user_login Username.
	 * @param WP_User $user       WP_User object of the logged-in user.
	 */
	do_action( 'wp_login', $user->user_login, $user );
	return $user;
}

/**
 * Authenticates a user, confirming the username and password are valid.
 *
 * @since 2.8.0
 *
 * @param WP_User|WP_Error|null $user     WP_User or WP_Error object from a previous callback. Default null.
 * @param string                $username Username for authentication.
 * @param string                $password Password for authentication.
 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 */
function wp_authenticate_username_password( $user, $username, $password ) {
	if ( $user instanceof WP_User ) {
		return $user;
	}

	if ( empty( $username ) || empty( $password ) ) {
		if ( is_wp_error( $user ) ) {
			return $user;
		}

		$error = new WP_Error();

		if ( empty( $username ) ) {
			$error->add( 'empty_username', __( '<strong>Error:</strong> The username field is empty.' ) );
		}

		if ( empty( $password ) ) {
			$error->add( 'empty_password', __( '<strong>Error:</strong> The password field is empty.' ) );
		}

		return $error;
	}

	$user = get_user_by( 'login', $username );

	if ( ! $user ) {
		return new WP_Error(
			'invalid_username',
			sprintf(
				/* translators: %s: User name. */
				__( '<strong>Error:</strong> The username <strong>%s</strong> is not registered on this site. If you are unsure of your username, try your email address instead.' ),
				$username
			)
		);
	}

	/**
	 * Filters whether the given user can be authenticated with the provided password.
	 *
	 * @since 2.5.0
	 *
	 * @param WP_User|WP_Error $user     WP_User or WP_Error object if a previous
	 *                                   callback failed authentication.
	 * @param string           $password Password to check against the user.
	 */
	$user = apply_filters( 'wp_authenticate_user', $user, $password );
	if ( is_wp_error( $user ) ) {
		return $user;
	}

	if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {
		return new WP_Error(
			'incorrect_password',
			sprintf(
				/* translators: %s: User name. */
				__( '<strong>Error:</strong> The password you entered for the username %s is incorrect.' ),
				'<strong>' . $username . '</strong>'
			) .
			' <a href="' . wp_lostpassword_url() . '">' .
			__( 'Lost your password?' ) .
			'</a>'
		);
	}

	return $user;
}

/**
 * Authenticates a user using the email and password.
 *
 * @since 4.5.0
 *
 * @param WP_User|WP_Error|null $user     WP_User or WP_Error object if a previous
 *                                        callback failed authentication.
 * @param string                $email    Email address for authentication.
 * @param string                $password Password for authentication.
 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 */
function wp_authenticate_email_password( $user, $email, $password ) {
	if ( $user instanceof WP_User ) {
		return $user;
	}

	if ( empty( $email ) || empty( $password ) ) {
		if ( is_wp_error( $user ) ) {
			return $user;
		}

		$error = new WP_Error();

		if ( empty( $email ) ) {
			// Uses 'empty_username' for back-compat with wp_signon().
			$error->add( 'empty_username', __( '<strong>Error:</strong> The email field is empty.' ) );
		}

		if ( empty( $password ) ) {
			$error->add( 'empty_password', __( '<strong>Error:</strong> The password field is empty.' ) );
		}

		return $error;
	}

	if ( ! is_email( $email ) ) {
		return $user;
	}

	$user = get_user_by( 'email', $email );

	if ( ! $user ) {
		return new WP_Error(
			'invalid_email',
			__( 'Unknown email address. Check again or try your username.' )
		);
	}

	/** This filter is documented in wp-includes/user.php */
	$user = apply_filters( 'wp_authenticate_user', $user, $password );

	if ( is_wp_error( $user ) ) {
		return $user;
	}

	if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {
		return new WP_Error(
			'incorrect_password',
			sprintf(
				/* translators: %s: Email address. */
				__( '<strong>Error:</strong> The password you entered for the email address %s is incorrect.' ),
				'<strong>' . $email . '</strong>'
			) .
			' <a href="' . wp_lostpassword_url() . '">' .
			__( 'Lost your password?' ) .
			'</a>'
		);
	}

	return $user;
}

/**
 * Authenticates the user using the WordPress auth cookie.
 *
 * @since 2.8.0
 *
 * @global string $auth_secure_cookie
 *
 * @param WP_User|WP_Error|null $user     WP_User or WP_Error object from a previous callback. Default null.
 * @param string                $username Username. If not empty, cancels the cookie authentication.
 * @param string                $password Password. If not empty, cancels the cookie authentication.
 * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 */
function wp_authenticate_cookie( $user, $username, $password ) {
	if ( $user instanceof WP_User ) {
		return $user;
	}

	if ( empty( $username ) && empty( $password ) ) {
		$user_id = wp_validate_auth_cookie();
		if ( $user_id ) {
			return new WP_User( $user_id );
		}

		global $auth_secure_cookie;

		if ( $auth_secure_cookie ) {
			$auth_cookie = SECURE_AUTH_COOKIE;
		} else {
			$auth_cookie = AUTH_COOKIE;
		}

		if ( ! empty( $_COOKIE[ $auth_cookie ] ) ) {
			return new WP_Error( 'expired_session', __( 'Please log in again.' ) );
		}

		// If the cookie is not set, be silent.
	}

	return $user;
}

/**
 * Authenticates the user using an application password.
 *
 * @since 5.6.0
 *
 * @param WP_User|WP_Error|null $input_user WP_User or WP_Error object if a previous
 *                                          callback failed authentication.
 * @param string                $username   Username for authentication.
 * @param string                $password   Password for authentication.
 * @return WP_User|WP_Error|null WP_User on success, WP_Error on failure, null if
 *                               null is passed in and this isn't an API request.
 */
function wp_authenticate_application_password( $input_user, $username, $password ) {
	if ( $input_user instanceof WP_User ) {
		return $input_user;
	}

	if ( ! WP_Application_Passwords::is_in_use() ) {
		return $input_user;
	}

	// The 'REST_REQUEST' check here may happen too early for the constant to be available.
	$is_api_request = ( ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) );

	/**
	 * Filters whether this is an API request that Application Passwords can be used on.
	 *
	 * By default, Application Passwords is available for the REST API and XML-RPC.
	 *
	 * @since 5.6.0
	 *
	 * @param bool $is_api_request If this is an acceptable API request.
	 */
	$is_api_request = apply_filters( 'application_password_is_api_request', $is_api_request );

	if ( ! $is_api_request ) {
		return $input_user;
	}

	$error = null;
	$user  = get_user_by( 'login', $username );

	if ( ! $user && is_email( $username ) ) {
		$user = get_user_by( 'email', $username );
	}

	// If the login name is invalid, short circuit.
	if ( ! $user ) {
		if ( is_email( $username ) ) {
			$error = new WP_Error(
				'invalid_email',
				__( '<strong>Error:</strong> Unknown email address. Check again or try your username.' )
			);
		} else {
			$error = new WP_Error(
				'invalid_username',
				__( '<strong>Error:</strong> Unknown username. Check again or try your email address.' )
			);
		}
	} elseif ( ! wp_is_application_passwords_available() ) {
		$error = new WP_Error(
			'application_passwords_disabled',
			__( 'Application passwords are not available.' )
		);
	} elseif ( ! wp_is_application_passwords_available_for_user( $user ) ) {
		$error = new WP_Error(
			'application_passwords_disabled_for_user',
			__( 'Application passwords are not available for your account. Please contact the site administrator for assistance.' )
		);
	}

	if ( $error ) {
		/**
		 * Fires when an application password failed to authenticate the user.
		 *
		 * @since 5.6.0
		 *
		 * @param WP_Error $error The authentication error.
		 */
		do_action( 'application_password_failed_authentication', $error );

		return $error;
	}

	/*
	 * Strips out anything non-alphanumeric. This is so passwords can be used with
	 * or without spaces to indicate the groupings for readability.
	 *
	 * Generated application passwords are exclusively alphanumeric.
	 */
	$password = preg_replace( '/[^a-z\d]/i', '', $password );

	$hashed_passwords = WP_Application_Passwords::get_user_application_passwords( $user->ID );

	foreach ( $hashed_passwords as $key => $item ) {
		if ( ! wp_check_password( $password, $item['password'], $user->ID ) ) {
			continue;
		}

		$error = new WP_Error();

		/**
		 * Fires when an application password has been successfully checked as valid.
		 *
		 * This allows for plugins to add additional constraints to prevent an application password from being used.
		 *
		 * @since 5.6.0
		 *
		 * @param WP_Error $error    The error object.
		 * @param WP_User  $user     The user authenticating.
		 * @param array    $item     The details about the application password.
		 * @param string   $password The raw supplied password.
		 */
		do_action( 'wp_authenticate_application_password_errors', $error, $user, $item, $password );

		if ( is_wp_error( $error ) && $error->has_errors() ) {
			/** This action is documented in wp-includes/user.php */
			do_action( 'application_password_failed_authentication', $error );

			return $error;
		}

		WP_Application_Passwords::record_application_password_usage( $user->ID, $item['uuid'] );

		/**
		 * Fires after an application password was used for authentication.
		 *
		 * @since 5.6.0
		 *
		 * @param WP_User $user The user who was authenticated.
		 * @param array   $item The application password used.
		 */
		do_action( 'application_password_did_authenticate', $user, $item );

		return $user;
	}

	$error = new WP_Error(
		'incorrect_password',
		__( 'The provided password is an invalid application password.' )
	);

	/** This action is documented in wp-includes/user.php */
	do_action( 'application_password_failed_authentication', $error );

	return $error;
}

/**
 * Validates the application password credentials passed via Basic Authentication.
 *
 * @since 5.6.0
 *
 * @param int|false $input_user User ID if one has been determined, false otherwise.
 * @return int|false The authenticated user ID if successful, false otherwise.
 */
function wp_validate_application_password( $input_user ) {
	// Don't authenticate twice.
	if ( ! empty( $input_user ) ) {
		return $input_user;
	}

	if ( ! wp_is_application_passwords_available() ) {
		return $input_user;
	}

	// Both $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] must be set in order to attempt authentication.
	if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
		return $input_user;
	}

	$authenticated = wp_authenticate_application_password( null, $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] );

	if ( $authenticated instanceof WP_User ) {
		return $authenticated->ID;
	}

	// If it wasn't a user what got returned, just pass on what we had received originally.
	return $input_user;
}

/**
 * For Multisite blogs, checks if the authenticated user has been marked as a
 * spammer, or if the user's primary blog has been marked as spam.
 *
 * @since 3.7.0
 *
 * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
 * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
 */
function wp_authenticate_spam_check( $user ) {
	if ( $user instanceof WP_User && is_multisite() ) {
		/**
		 * Filters whether the user has been marked as a spammer.
		 *
		 * @since 3.7.0
		 *
		 * @param bool    $spammed Whether the user is considered a spammer.
		 * @param WP_User $user    User to check against.
		 */
		$spammed = apply_filters( 'check_is_user_spammed', is_user_spammy( $user ), $user );

		if ( $spammed ) {
			return new WP_Error( 'spammer_account', __( '<strong>Error:</strong> Your account has been marked as a spammer.' ) );
		}
	}
	return $user;
}

/**
 * Validates the logged-in cookie.
 *
 * Checks the logged-in cookie if the previous auth cookie could not be
 * validated and parsed.
 *
 * This is a callback for the {@see 'determine_current_user'} filter, rather than API.
 *
 * @since 3.9.0
 *
 * @param int|false $user_id The user ID (or false) as received from
 *                           the `determine_current_user` filter.
 * @return int|false User ID if validated, false otherwise. If a user ID from
 *                   an earlier filter callback is received, that value is returned.
 */
function wp_validate_logged_in_cookie( $user_id ) {
	if ( $user_id ) {
		return $user_id;
	}

	if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
		return false;
	}

	return wp_validate_auth_cookie( $_COOKIE[ LOGGED_IN_COOKIE ], 'logged_in' );
}

/**
 * Gets the number of posts a user has written.
 *
 * @since 3.0.0
 * @since 4.1.0 Added `$post_type` argument.
 * @since 4.3.0 Added `$public_only` argument. Added the ability to pass an array
 *              of post types to `$post_type`.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int          $userid      User ID.
 * @param array|string $post_type   Optional. Single post type or array of post types to count the number of posts for. Default 'post'.
 * @param bool         $public_only Optional. Whether to only return counts for public posts. Default false.
 * @return string Number of posts the user has written in this post type.
 */
function count_user_posts( $userid, $post_type = 'post', $public_only = false ) {
	global $wpdb;

	$where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );

	$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );

	/**
	 * Filters the number of posts a user has written.
	 *
	 * @since 2.7.0
	 * @since 4.1.0 Added `$post_type` argument.
	 * @since 4.3.1 Added `$public_only` argument.
	 *
	 * @param int          $count       The user's post count.
	 * @param int          $userid      User ID.
	 * @param string|array $post_type   Single post type or array of post types to count the number of posts for.
	 * @param bool         $public_only Whether to limit counted posts to public posts.
	 */
	return apply_filters( 'get_usernumposts', $count, $userid, $post_type, $public_only );
}

/**
 * Gets the number of posts written by a list of users.
 *
 * @since 3.0.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int[]           $users       Array of user IDs.
 * @param string|string[] $post_type   Optional. Single post type or array of post types to check. Defaults to 'post'.
 * @param bool            $public_only Optional. Only return counts for public posts.  Defaults to false.
 * @return string[] Amount of posts each user has written, as strings, keyed by user ID.
 */
function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
	global $wpdb;

	$count = array();
	if ( empty( $users ) || ! is_array( $users ) ) {
		return $count;
	}

	$userlist = implode( ',', array_map( 'absint', $users ) );
	$where    = get_posts_by_author_sql( $post_type, true, null, $public_only );

	$result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
	foreach ( $result as $row ) {
		$count[ $row[0] ] = $row[1];
	}

	foreach ( $users as $id ) {
		if ( ! isset( $count[ $id ] ) ) {
			$count[ $id ] = 0;
		}
	}

	return $count;
}

//
// User option functions.
//

/**
 * Gets the current user's ID.
 *
 * @since MU (3.0.0)
 *
 * @return int The current user's ID, or 0 if no user is logged in.
 */
function get_current_user_id() {
	if ( ! function_exists( 'wp_get_current_user' ) ) {
		return 0;
	}
	$user = wp_get_current_user();
	return ( isset( $user->ID ) ? (int) $user->ID : 0 );
}

/**
 * Retrieves user option that can be either per Site or per Network.
 *
 * If the user ID is not given, then the current user will be used instead. If
 * the user ID is given, then the user data will be retrieved. The filter for
 * the result, will also pass the original option name and finally the user data
 * object as the third parameter.
 *
 * The option will first check for the per site name and then the per Network name.
 *
 * @since 2.0.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param string $option     User option name.
 * @param int    $user       Optional. User ID.
 * @param string $deprecated Use get_option() to check for an option in the options table.
 * @return mixed User option value on success, false on failure.
 */
function get_user_option( $option, $user = 0, $deprecated = '' ) {
	global $wpdb;

	if ( ! empty( $deprecated ) ) {
		_deprecated_argument( __FUNCTION__, '3.0.0' );
	}

	if ( empty( $user ) ) {
		$user = get_current_user_id();
	}

	$user = get_userdata( $user );
	if ( ! $user ) {
		return false;
	}

	$prefix = $wpdb->get_blog_prefix();
	if ( $user->has_prop( $prefix . $option ) ) { // Blog-specific.
		$result = $user->get( $prefix . $option );
	} elseif ( $user->has_prop( $option ) ) { // User-specific and cross-blog.
		$result = $user->get( $option );
	} else {
		$result = false;
	}

	/**
	 * Filters a specific user option value.
	 *
	 * The dynamic portion of the hook name, `$option`, refers to the user option name.
	 *
	 * @since 2.5.0
	 *
	 * @param mixed   $result Value for the user's option.
	 * @param string  $option Name of the option being retrieved.
	 * @param WP_User $user   WP_User object of the user whose option is being retrieved.
	 */
	return apply_filters( "get_user_option_{$option}", $result, $option, $user );
}

/**
 * Updates user option with global blog capability.
 *
 * User options are just like user metadata except that they have support for
 * global blog options. If the 'is_global' parameter is false, which it is by default,
 * it will prepend the WordPress table prefix to the option name.
 *
 * Deletes the user option if $newvalue is empty.
 *
 * @since 2.0.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int    $user_id     User ID.
 * @param string $option_name User option name.
 * @param mixed  $newvalue    User option value.
 * @param bool   $is_global   Optional. Whether option name is global or blog specific.
 *                            Default false (blog specific).
 * @return int|bool User meta ID if the option didn't exist, true on successful update,
 *                  false on failure.
 */
function update_user_option( $user_id, $option_name, $newvalue, $is_global = false ) {
	global $wpdb;

	if ( ! $is_global ) {
		$option_name = $wpdb->get_blog_prefix() . $option_name;
	}

	return update_user_meta( $user_id, $option_name, $newvalue );
}

/**
 * Deletes user option with global blog capability.
 *
 * User options are just like user metadata except that they have support for
 * global blog options. If the 'is_global' parameter is false, which it is by default,
 * it will prepend the WordPress table prefix to the option name.
 *
 * @since 3.0.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int    $user_id     User ID
 * @param string $option_name User option name.
 * @param bool   $is_global   Optional. Whether option name is global or blog specific.
 *                            Default false (blog specific).
 * @return bool True on success, false on failure.
 */
function delete_user_option( $user_id, $option_name, $is_global = false ) {
	global $wpdb;

	if ( ! $is_global ) {
		$option_name = $wpdb->get_blog_prefix() . $option_name;
	}

	return delete_user_meta( $user_id, $option_name );
}

/**
 * Retrieves list of users matching criteria.
 *
 * @since 3.1.0
 *
 * @see WP_User_Query
 *
 * @param array $args Optional. Arguments to retrieve users. See WP_User_Query::prepare_query()
 *                    for more information on accepted arguments.
 * @return array List of users.
 */
function get_users( $args = array() ) {

	$args                = wp_parse_args( $args );
	$args['count_total'] = false;

	$user_search = new WP_User_Query( $args );

	return (array) $user_search->get_results();
}

/**
 * Lists all the users of the site, with several options available.
 *
 * @since 5.9.0
 *
 * @param string|array $args {
 *     Optional. Array or string of default arguments.
 *
 *     @type string $orderby       How to sort the users. Accepts 'nicename', 'email', 'url', 'registered',
 *                                 'user_nicename', 'user_email', 'user_url', 'user_registered', 'name',
 *                                 'display_name', 'post_count', 'ID', 'meta_value', 'user_login'. Default 'name'.
 *     @type string $order         Sorting direction for $orderby. Accepts 'ASC', 'DESC'. Default 'ASC'.
 *     @type int    $number        Maximum users to return or display. Default empty (all users).
 *     @type bool   $exclude_admin Whether to exclude the 'admin' account, if it exists. Default false.
 *     @type bool   $show_fullname Whether to show the user's full name. Default false.
 *     @type string $feed          If not empty, show a link to the user's feed and use this text as the alt
 *                                 parameter of the link. Default empty.
 *     @type string $feed_image    If not empty, show a link to the user's feed and use this image URL as
 *                                 clickable anchor. Default empty.
 *     @type string $feed_type     The feed type to link to, such as 'rss2'. Defaults to default feed type.
 *     @type bool   $echo          Whether to output the result or instead return it. Default true.
 *     @type string $style         If 'list', each user is wrapped in an `<li>` element, otherwise the users
 *                                 will be separated by commas.
 *     @type bool   $html          Whether to list the items in HTML form or plaintext. Default true.
 *     @type string $exclude       An array, comma-, or space-separated list of user IDs to exclude. Default empty.
 *     @type string $include       An array, comma-, or space-separated list of user IDs to include. Default empty.
 * }
 * @return string|null The output if echo is false. Otherwise null.
 */
function wp_list_users( $args = array() ) {
	$defaults = array(
		'orderby'       => 'name',
		'order'         => 'ASC',
		'number'        => '',
		'exclude_admin' => true,
		'show_fullname' => false,
		'feed'          => '',
		'feed_image'    => '',
		'feed_type'     => '',
		'echo'          => true,
		'style'         => 'list',
		'html'          => true,
		'exclude'       => '',
		'include'       => '',
	);

	$parsed_args = wp_parse_args( $args, $defaults );

	$return = '';

	$query_args           = wp_array_slice_assoc( $parsed_args, array( 'orderby', 'order', 'number', 'exclude', 'include' ) );
	$query_args['fields'] = 'ids';

	/**
	 * Filters the query arguments for the list of all users of the site.
	 *
	 * @since 6.1.0
	 *
	 * @param array $query_args  The query arguments for get_users().
	 * @param array $parsed_args The arguments passed to wp_list_users() combined with the defaults.
	 */
	$query_args = apply_filters( 'wp_list_users_args', $query_args, $parsed_args );

	$users = get_users( $query_args );

	foreach ( $users as $user_id ) {
		$user = get_userdata( $user_id );

		if ( $parsed_args['exclude_admin'] && 'admin' === $user->display_name ) {
			continue;
		}

		if ( $parsed_args['show_fullname'] && '' !== $user->first_name && '' !== $user->last_name ) {
			$name = sprintf(
				/* translators: 1: User's first name, 2: Last name. */
				_x( '%1$s %2$s', 'Display name based on first name and last name' ),
				$user->first_name,
				$user->last_name
			);
		} else {
			$name = $user->display_name;
		}

		if ( ! $parsed_args['html'] ) {
			$return .= $name . ', ';

			continue; // No need to go further to process HTML.
		}

		if ( 'list' === $parsed_args['style'] ) {
			$return .= '<li>';
		}

		$row = $name;

		if ( ! empty( $parsed_args['feed_image'] ) || ! empty( $parsed_args['feed'] ) ) {
			$row .= ' ';
			if ( empty( $parsed_args['feed_image'] ) ) {
				$row .= '(';
			}

			$row .= '<a href="' . get_author_feed_link( $user->ID, $parsed_args['feed_type'] ) . '"';

			$alt = '';
			if ( ! empty( $parsed_args['feed'] ) ) {
				$alt  = ' alt="' . esc_attr( $parsed_args['feed'] ) . '"';
				$name = $parsed_args['feed'];
			}

			$row .= '>';

			if ( ! empty( $parsed_args['feed_image'] ) ) {
				$row .= '<img src="' . esc_url( $parsed_args['feed_image'] ) . '" style="border: none;"' . $alt . ' />';
			} else {
				$row .= $name;
			}

			$row .= '</a>';

			if ( empty( $parsed_args['feed_image'] ) ) {
				$row .= ')';
			}
		}

		$return .= $row;
		$return .= ( 'list' === $parsed_args['style'] ) ? '</li>' : ', ';
	}

	$return = rtrim( $return, ', ' );

	if ( ! $parsed_args['echo'] ) {
		return $return;
	}
	echo $return;
}

/**
 * Gets the sites a user belongs to.
 *
 * @since 3.0.0
 * @since 4.7.0 Converted to use `get_sites()`.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int  $user_id User ID
 * @param bool $all     Whether to retrieve all sites, or only sites that are not
 *                      marked as deleted, archived, or spam.
 * @return object[] A list of the user's sites. An empty array if the user doesn't exist
 *                  or belongs to no sites.
 */
function get_blogs_of_user( $user_id, $all = false ) {
	global $wpdb;

	$user_id = (int) $user_id;

	// Logged out users can't have sites.
	if ( empty( $user_id ) ) {
		return array();
	}

	/**
	 * Filters the list of a user's sites before it is populated.
	 *
	 * Returning a non-null value from the filter will effectively short circuit
	 * get_blogs_of_user(), returning that value instead.
	 *
	 * @since 4.6.0
	 *
	 * @param null|object[] $sites   An array of site objects of which the user is a member.
	 * @param int           $user_id User ID.
	 * @param bool          $all     Whether the returned array should contain all sites, including
	 *                               those marked 'deleted', 'archived', or 'spam'. Default false.
	 */
	$sites = apply_filters( 'pre_get_blogs_of_user', null, $user_id, $all );

	if ( null !== $sites ) {
		return $sites;
	}

	$keys = get_user_meta( $user_id );
	if ( empty( $keys ) ) {
		return array();
	}

	if ( ! is_multisite() ) {
		$site_id                        = get_current_blog_id();
		$sites                          = array( $site_id => new stdClass() );
		$sites[ $site_id ]->userblog_id = $site_id;
		$sites[ $site_id ]->blogname    = get_option( 'blogname' );
		$sites[ $site_id ]->domain      = '';
		$sites[ $site_id ]->path        = '';
		$sites[ $site_id ]->site_id     = 1;
		$sites[ $site_id ]->siteurl     = get_option( 'siteurl' );
		$sites[ $site_id ]->archived    = 0;
		$sites[ $site_id ]->spam        = 0;
		$sites[ $site_id ]->deleted     = 0;
		return $sites;
	}

	$site_ids = array();

	if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
		$site_ids[] = 1;
		unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
	}

	$keys = array_keys( $keys );

	foreach ( $keys as $key ) {
		if ( ! str_ends_with( $key, 'capabilities' ) ) {
			continue;
		}
		if ( $wpdb->base_prefix && ! str_starts_with( $key, $wpdb->base_prefix ) ) {
			continue;
		}
		$site_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
		if ( ! is_numeric( $site_id ) ) {
			continue;
		}

		$site_ids[] = (int) $site_id;
	}

	$sites = array();

	if ( ! empty( $site_ids ) ) {
		$args = array(
			'number'   => '',
			'site__in' => $site_ids,
		);
		if ( ! $all ) {
			$args['archived'] = 0;
			$args['spam']     = 0;
			$args['deleted']  = 0;
		}

		$_sites = get_sites( $args );

		foreach ( $_sites as $site ) {
			$sites[ $site->id ] = (object) array(
				'userblog_id' => $site->id,
				'blogname'    => $site->blogname,
				'domain'      => $site->domain,
				'path'        => $site->path,
				'site_id'     => $site->network_id,
				'siteurl'     => $site->siteurl,
				'archived'    => $site->archived,
				'mature'      => $site->mature,
				'spam'        => $site->spam,
				'deleted'     => $site->deleted,
			);
		}
	}

	/**
	 * Filters the list of sites a user belongs to.
	 *
	 * @since MU (3.0.0)
	 *
	 * @param object[] $sites   An array of site objects belonging to the user.
	 * @param int      $user_id User ID.
	 * @param bool     $all     Whether the returned sites array should contain all sites, including
	 *                          those marked 'deleted', 'archived', or 'spam'. Default false.
	 */
	return apply_filters( 'get_blogs_of_user', $sites, $user_id, $all );
}

/**
 * Finds out whether a user is a member of a given blog.
 *
 * @since MU (3.0.0)
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
 * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
 * @return bool
 */
function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
	global $wpdb;

	$user_id = (int) $user_id;
	$blog_id = (int) $blog_id;

	if ( empty( $user_id ) ) {
		$user_id = get_current_user_id();
	}

	/*
	 * Technically not needed, but does save calls to get_site() and get_user_meta()
	 * in the event that the function is called when a user isn't logged in.
	 */
	if ( empty( $user_id ) ) {
		return false;
	} else {
		$user = get_userdata( $user_id );
		if ( ! $user instanceof WP_User ) {
			return false;
		}
	}

	if ( ! is_multisite() ) {
		return true;
	}

	if ( empty( $blog_id ) ) {
		$blog_id = get_current_blog_id();
	}

	$blog = get_site( $blog_id );

	if ( ! $blog || ! isset( $blog->domain ) || $blog->archived || $blog->spam || $blog->deleted ) {
		return false;
	}

	$keys = get_user_meta( $user_id );
	if ( empty( $keys ) ) {
		return false;
	}

	// No underscore before capabilities in $base_capabilities_key.
	$base_capabilities_key = $wpdb->base_prefix . 'capabilities';
	$site_capabilities_key = $wpdb->base_prefix . $blog_id . '_capabilities';

	if ( isset( $keys[ $base_capabilities_key ] ) && 1 == $blog_id ) {
		return true;
	}

	if ( isset( $keys[ $site_capabilities_key ] ) ) {
		return true;
	}

	return false;
}

/**
 * Adds meta data to a user.
 *
 * @since 3.0.0
 *
 * @param int    $user_id    User ID.
 * @param string $meta_key   Metadata name.
 * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
 * @param bool   $unique     Optional. Whether the same key should not be added.
 *                           Default false.
 * @return int|false Meta ID on success, false on failure.
 */
function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
	return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
}

/**
 * Removes metadata matching criteria from a user.
 *
 * You can match based on the key, or key and value. Removing based on key and
 * value, will keep from removing duplicate metadata with the same key. It also
 * allows removing all metadata matching key, if needed.
 *
 * @since 3.0.0
 *
 * @link https://developer.wordpress.org/reference/functions/delete_user_meta/
 *
 * @param int    $user_id    User ID
 * @param string $meta_key   Metadata name.
 * @param mixed  $meta_value Optional. Metadata value. If provided,
 *                           rows will only be removed that match the value.
 *                           Must be serializable if non-scalar. Default empty.
 * @return bool True on success, false on failure.
 */
function delete_user_meta( $user_id, $meta_key, $meta_value = '' ) {
	return delete_metadata( 'user', $user_id, $meta_key, $meta_value );
}

/**
 * Retrieves user meta field for a user.
 *
 * @since 3.0.0
 *
 * @link https://developer.wordpress.org/reference/functions/get_user_meta/
 *
 * @param int    $user_id User ID.
 * @param string $key     Optional. The meta key to retrieve. By default,
 *                        returns data for all keys.
 * @param bool   $single  Optional. Whether to return a single value.
 *                        This parameter has no effect if `$key` is not specified.
 *                        Default false.
 * @return mixed An array of values if `$single` is false.
 *               The value of meta data field if `$single` is true.
 *               False for an invalid `$user_id` (non-numeric, zero, or negative value).
 *               An empty string if a valid but non-existing user ID is passed.
 */
function get_user_meta( $user_id, $key = '', $single = false ) {
	return get_metadata( 'user', $user_id, $key, $single );
}

/**
 * Updates user meta field based on user ID.
 *
 * Use the $prev_value parameter to differentiate between meta fields with the
 * same key and user ID.
 *
 * If the meta field for the user does not exist, it will be added.
 *
 * @since 3.0.0
 *
 * @link https://developer.wordpress.org/reference/functions/update_user_meta/
 *
 * @param int    $user_id    User ID.
 * @param string $meta_key   Metadata key.
 * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
 * @param mixed  $prev_value Optional. Previous value to check before updating.
 *                           If specified, only update existing metadata entries with
 *                           this value. Otherwise, update all entries. Default empty.
 * @return int|bool Meta ID if the key didn't exist, true on successful update,
 *                  false on failure or if the value passed to the function
 *                  is the same as the one that is already in the database.
 */
function update_user_meta( $user_id, $meta_key, $meta_value, $prev_value = '' ) {
	return update_metadata( 'user', $user_id, $meta_key, $meta_value, $prev_value );
}

/**
 * Counts number of users who have each of the user roles.
 *
 * Assumes there are neither duplicated nor orphaned capabilities meta_values.
 * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
 * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
 * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
 *
 * @since 3.0.0
 * @since 4.4.0 The number of users with no role is now included in the `none` element.
 * @since 4.9.0 The `$site_id` parameter was added to support multisite.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param string   $strategy Optional. The computational strategy to use when counting the users.
 *                           Accepts either 'time' or 'memory'. Default 'time'.
 * @param int|null $site_id  Optional. The site ID to count users for. Defaults to the current site.
 * @return array {
 *     User counts.
 *
 *     @type int   $total_users Total number of users on the site.
 *     @type int[] $avail_roles Array of user counts keyed by user role.
 * }
 */
function count_users( $strategy = 'time', $site_id = null ) {
	global $wpdb;

	// Initialize.
	if ( ! $site_id ) {
		$site_id = get_current_blog_id();
	}

	/**
	 * Filters the user count before queries are run.
	 *
	 * Return a non-null value to cause count_users() to return early.
	 *
	 * @since 5.1.0
	 *
	 * @param null|array $result   The value to return instead. Default null to continue with the query.
	 * @param string     $strategy Optional. The computational strategy to use when counting the users.
	 *                             Accepts either 'time' or 'memory'. Default 'time'.
	 * @param int        $site_id  The site ID to count users for.
	 */
	$pre = apply_filters( 'pre_count_users', null, $strategy, $site_id );

	if ( null !== $pre ) {
		return $pre;
	}

	$blog_prefix = $wpdb->get_blog_prefix( $site_id );
	$result      = array();

	if ( 'time' === $strategy ) {
		if ( is_multisite() && get_current_blog_id() != $site_id ) {
			switch_to_blog( $site_id );
			$avail_roles = wp_roles()->get_names();
			restore_current_blog();
		} else {
			$avail_roles = wp_roles()->get_names();
		}

		// Build a CPU-intensive query that will return concise information.
		$select_count = array();
		foreach ( $avail_roles as $this_role => $name ) {
			$select_count[] = $wpdb->prepare( 'COUNT(NULLIF(`meta_value` LIKE %s, false))', '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%' );
		}
		$select_count[] = "COUNT(NULLIF(`meta_value` = 'a:0:{}', false))";
		$select_count   = implode( ', ', $select_count );

		// Add the meta_value index to the selection list, then run the query.
		$row = $wpdb->get_row(
			"
			SELECT {$select_count}, COUNT(*)
			FROM {$wpdb->usermeta}
			INNER JOIN {$wpdb->users} ON user_id = ID
			WHERE meta_key = '{$blog_prefix}capabilities'
		",
			ARRAY_N
		);

		// Run the previous loop again to associate results with role names.
		$col         = 0;
		$role_counts = array();
		foreach ( $avail_roles as $this_role => $name ) {
			$count = (int) $row[ $col++ ];
			if ( $count > 0 ) {
				$role_counts[ $this_role ] = $count;
			}
		}

		$role_counts['none'] = (int) $row[ $col++ ];

		// Get the meta_value index from the end of the result set.
		$total_users = (int) $row[ $col ];

		$result['total_users'] = $total_users;
		$result['avail_roles'] =& $role_counts;
	} else {
		$avail_roles = array(
			'none' => 0,
		);

		$users_of_blog = $wpdb->get_col(
			"
			SELECT meta_value
			FROM {$wpdb->usermeta}
			INNER JOIN {$wpdb->users} ON user_id = ID
			WHERE meta_key = '{$blog_prefix}capabilities'
		"
		);

		foreach ( $users_of_blog as $caps_meta ) {
			$b_roles = maybe_unserialize( $caps_meta );
			if ( ! is_array( $b_roles ) ) {
				continue;
			}
			if ( empty( $b_roles ) ) {
				++$avail_roles['none'];
			}
			foreach ( $b_roles as $b_role => $val ) {
				if ( isset( $avail_roles[ $b_role ] ) ) {
					++$avail_roles[ $b_role ];
				} else {
					$avail_roles[ $b_role ] = 1;
				}
			}
		}

		$result['total_users'] = count( $users_of_blog );
		$result['avail_roles'] =& $avail_roles;
	}

	return $result;
}

/**
 * Returns the number of active users in your installation.
 *
 * Note that on a large site the count may be cached and only updated twice daily.
 *
 * @since MU (3.0.0)
 * @since 4.8.0 The `$network_id` parameter has been added.
 * @since 6.0.0 Moved to wp-includes/user.php.
 *
 * @param int|null $network_id ID of the network. Defaults to the current network.
 * @return int Number of active users on the network.
 */
function get_user_count( $network_id = null ) {
	if ( ! is_multisite() && null !== $network_id ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: %s: $network_id */
				__( 'Unable to pass %s if not using multisite.' ),
				'<code>$network_id</code>'
			),
			'6.0.0'
		);
	}

	return (int) get_network_option( $network_id, 'user_count', -1 );
}

/**
 * Updates the total count of users on the site if live user counting is enabled.
 *
 * @since 6.0.0
 *
 * @param int|null $network_id ID of the network. Defaults to the current network.
 * @return bool Whether the update was successful.
 */
function wp_maybe_update_user_counts( $network_id = null ) {
	if ( ! is_multisite() && null !== $network_id ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: %s: $network_id */
				__( 'Unable to pass %s if not using multisite.' ),
				'<code>$network_id</code>'
			),
			'6.0.0'
		);
	}

	$is_small_network = ! wp_is_large_user_count( $network_id );
	/** This filter is documented in wp-includes/ms-functions.php */
	if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'users' ) ) {
		return false;
	}

	return wp_update_user_counts( $network_id );
}

/**
 * Updates the total count of users on the site.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 * @since 6.0.0
 *
 * @param int|null $network_id ID of the network. Defaults to the current network.
 * @return bool Whether the update was successful.
 */
function wp_update_user_counts( $network_id = null ) {
	global $wpdb;

	if ( ! is_multisite() && null !== $network_id ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: %s: $network_id */
				__( 'Unable to pass %s if not using multisite.' ),
				'<code>$network_id</code>'
			),
			'6.0.0'
		);
	}

	$query = "SELECT COUNT(ID) as c FROM $wpdb->users";
	if ( is_multisite() ) {
		$query .= " WHERE spam = '0' AND deleted = '0'";
	}

	$count = $wpdb->get_var( $query );

	return update_network_option( $network_id, 'user_count', $count );
}

/**
 * Schedules a recurring recalculation of the total count of users.
 *
 * @since 6.0.0
 */
function wp_schedule_update_user_counts() {
	if ( ! is_main_site() ) {
		return;
	}

	if ( ! wp_next_scheduled( 'wp_update_user_counts' ) && ! wp_installing() ) {
		wp_schedule_event( time(), 'twicedaily', 'wp_update_user_counts' );
	}
}

/**
 * Determines whether the site has a large number of users.
 *
 * The default criteria for a large site is more than 10,000 users.
 *
 * @since 6.0.0
 *
 * @param int|null $network_id ID of the network. Defaults to the current network.
 * @return bool Whether the site has a large number of users.
 */
function wp_is_large_user_count( $network_id = null ) {
	if ( ! is_multisite() && null !== $network_id ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: %s: $network_id */
				__( 'Unable to pass %s if not using multisite.' ),
				'<code>$network_id</code>'
			),
			'6.0.0'
		);
	}

	$count = get_user_count( $network_id );

	/**
	 * Filters whether the site is considered large, based on its number of users.
	 *
	 * @since 6.0.0
	 *
	 * @param bool     $is_large_user_count Whether the site has a large number of users.
	 * @param int      $count               The total number of users.
	 * @param int|null $network_id          ID of the network. `null` represents the current network.
	 */
	return apply_filters( 'wp_is_large_user_count', $count > 10000, $count, $network_id );
}

//
// Private helper functions.
//

/**
 * Sets up global user vars.
 *
 * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
 *
 * @since 2.0.4
 *
 * @global string  $user_login    The user username for logging in
 * @global WP_User $userdata      User data.
 * @global int     $user_level    The level of the user
 * @global int     $user_ID       The ID of the user
 * @global string  $user_email    The email address of the user
 * @global string  $user_url      The url in the user's profile
 * @global string  $user_identity The display name of the user
 *
 * @param int $for_user_id Optional. User ID to set up global data. Default 0.
 */
function setup_userdata( $for_user_id = 0 ) {
	global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;

	if ( ! $for_user_id ) {
		$for_user_id = get_current_user_id();
	}
	$user = get_userdata( $for_user_id );

	if ( ! $user ) {
		$user_ID       = 0;
		$user_level    = 0;
		$userdata      = null;
		$user_login    = '';
		$user_email    = '';
		$user_url      = '';
		$user_identity = '';
		return;
	}

	$user_ID       = (int) $user->ID;
	$user_level    = (int) $user->user_level;
	$userdata      = $user;
	$user_login    = $user->user_login;
	$user_email    = $user->user_email;
	$user_url      = $user->user_url;
	$user_identity = $user->display_name;
}

/**
 * Creates dropdown HTML content of users.
 *
 * The content can either be displayed, which it is by default or retrieved by
 * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
 * need to be used; all users will be displayed in that case. Only one can be
 * used, either 'include' or 'exclude', but not both.
 *
 * The available arguments are as follows:
 *
 * @since 2.3.0
 * @since 4.5.0 Added the 'display_name_with_login' value for 'show'.
 * @since 4.7.0 Added the `$role`, `$role__in`, and `$role__not_in` parameters.
 *
 * @param array|string $args {
 *     Optional. Array or string of arguments to generate a drop-down of users.
 *     See WP_User_Query::prepare_query() for additional available arguments.
 *
 *     @type string       $show_option_all         Text to show as the drop-down default (all).
 *                                                 Default empty.
 *     @type string       $show_option_none        Text to show as the drop-down default when no
 *                                                 users were found. Default empty.
 *     @type int|string   $option_none_value       Value to use for $show_option_none when no users
 *                                                 were found. Default -1.
 *     @type string       $hide_if_only_one_author Whether to skip generating the drop-down
 *                                                 if only one user was found. Default empty.
 *     @type string       $orderby                 Field to order found users by. Accepts user fields.
 *                                                 Default 'display_name'.
 *     @type string       $order                   Whether to order users in ascending or descending
 *                                                 order. Accepts 'ASC' (ascending) or 'DESC' (descending).
 *                                                 Default 'ASC'.
 *     @type int[]|string $include                 Array or comma-separated list of user IDs to include.
 *                                                 Default empty.
 *     @type int[]|string $exclude                 Array or comma-separated list of user IDs to exclude.
 *                                                 Default empty.
 *     @type bool|int     $multi                   Whether to skip the ID attribute on the 'select' element.
 *                                                 Accepts 1|true or 0|false. Default 0|false.
 *     @type string       $show                    User data to display. If the selected item is empty
 *                                                 then the 'user_login' will be displayed in parentheses.
 *                                                 Accepts any user field, or 'display_name_with_login' to show
 *                                                 the display name with user_login in parentheses.
 *                                                 Default 'display_name'.
 *     @type int|bool     $echo                    Whether to echo or return the drop-down. Accepts 1|true (echo)
 *                                                 or 0|false (return). Default 1|true.
 *     @type int          $selected                Which user ID should be selected. Default 0.
 *     @type bool         $include_selected        Whether to always include the selected user ID in the drop-
 *                                                 down. Default false.
 *     @type string       $name                    Name attribute of select element. Default 'user'.
 *     @type string       $id                      ID attribute of the select element. Default is the value of $name.
 *     @type string       $class                   Class attribute of the select element. Default empty.
 *     @type int          $blog_id                 ID of blog (Multisite only). Default is ID of the current blog.
 *     @type string       $who                     Which type of users to query. Accepts only an empty string or
 *                                                 'authors'. Default empty.
 *     @type string|array $role                    An array or a comma-separated list of role names that users must
 *                                                 match to be included in results. Note that this is an inclusive
 *                                                 list: users must match *each* role. Default empty.
 *     @type string[]     $role__in                An array of role names. Matched users must have at least one of
 *                                                 these roles. Default empty array.
 *     @type string[]     $role__not_in            An array of role names to exclude. Users matching one or more of
 *                                                 these roles will not be included in results. Default empty array.
 * }
 * @return string HTML dropdown list of users.
 */
function wp_dropdown_users( $args = '' ) {
	$defaults = array(
		'show_option_all'         => '',
		'show_option_none'        => '',
		'hide_if_only_one_author' => '',
		'orderby'                 => 'display_name',
		'order'                   => 'ASC',
		'include'                 => '',
		'exclude'                 => '',
		'multi'                   => 0,
		'show'                    => 'display_name',
		'echo'                    => 1,
		'selected'                => 0,
		'name'                    => 'user',
		'class'                   => '',
		'id'                      => '',
		'blog_id'                 => get_current_blog_id(),
		'who'                     => '',
		'include_selected'        => false,
		'option_none_value'       => -1,
		'role'                    => '',
		'role__in'                => array(),
		'role__not_in'            => array(),
		'capability'              => '',
		'capability__in'          => array(),
		'capability__not_in'      => array(),
	);

	$defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;

	$parsed_args = wp_parse_args( $args, $defaults );

	$query_args = wp_array_slice_assoc(
		$parsed_args,
		array(
			'blog_id',
			'include',
			'exclude',
			'orderby',
			'order',
			'who',
			'role',
			'role__in',
			'role__not_in',
			'capability',
			'capability__in',
			'capability__not_in',
		)
	);

	$fields = array( 'ID', 'user_login' );

	$show = ! empty( $parsed_args['show'] ) ? $parsed_args['show'] : 'display_name';
	if ( 'display_name_with_login' === $show ) {
		$fields[] = 'display_name';
	} else {
		$fields[] = $show;
	}

	$query_args['fields'] = $fields;

	$show_option_all   = $parsed_args['show_option_all'];
	$show_option_none  = $parsed_args['show_option_none'];
	$option_none_value = $parsed_args['option_none_value'];

	/**
	 * Filters the query arguments for the list of users in the dropdown.
	 *
	 * @since 4.4.0
	 *
	 * @param array $query_args  The query arguments for get_users().
	 * @param array $parsed_args The arguments passed to wp_dropdown_users() combined with the defaults.
	 */
	$query_args = apply_filters( 'wp_dropdown_users_args', $query_args, $parsed_args );

	$users = get_users( $query_args );

	$output = '';
	if ( ! empty( $users ) && ( empty( $parsed_args['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
		$name = esc_attr( $parsed_args['name'] );
		if ( $parsed_args['multi'] && ! $parsed_args['id'] ) {
			$id = '';
		} else {
			$id = $parsed_args['id'] ? " id='" . esc_attr( $parsed_args['id'] ) . "'" : " id='$name'";
		}
		$output = "<select name='{$name}'{$id} class='" . $parsed_args['class'] . "'>\n";

		if ( $show_option_all ) {
			$output .= "\t<option value='0'>$show_option_all</option>\n";
		}

		if ( $show_option_none ) {
			$_selected = selected( $option_none_value, $parsed_args['selected'], false );
			$output   .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
		}

		if ( $parsed_args['include_selected'] && ( $parsed_args['selected'] > 0 ) ) {
			$found_selected          = false;
			$parsed_args['selected'] = (int) $parsed_args['selected'];

			foreach ( (array) $users as $user ) {
				$user->ID = (int) $user->ID;
				if ( $user->ID === $parsed_args['selected'] ) {
					$found_selected = true;
				}
			}

			if ( ! $found_selected ) {
				$selected_user = get_userdata( $parsed_args['selected'] );
				if ( $selected_user ) {
					$users[] = $selected_user;
				}
			}
		}

		foreach ( (array) $users as $user ) {
			if ( 'display_name_with_login' === $show ) {
				/* translators: 1: User's display name, 2: User login. */
				$display = sprintf( _x( '%1$s (%2$s)', 'user dropdown' ), $user->display_name, $user->user_login );
			} elseif ( ! empty( $user->$show ) ) {
				$display = $user->$show;
			} else {
				$display = '(' . $user->user_login . ')';
			}

			$_selected = selected( $user->ID, $parsed_args['selected'], false );
			$output   .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
		}

		$output .= '</select>';
	}

	/**
	 * Filters the wp_dropdown_users() HTML output.
	 *
	 * @since 2.3.0
	 *
	 * @param string $output HTML output generated by wp_dropdown_users().
	 */
	$html = apply_filters( 'wp_dropdown_users', $output );

	if ( $parsed_args['echo'] ) {
		echo $html;
	}
	return $html;
}

/**
 * Sanitizes user field based on context.
 *
 * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
 * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
 * when calling filters.
 *
 * @since 2.3.0
 *
 * @param string $field   The user Object field name.
 * @param mixed  $value   The user Object value.
 * @param int    $user_id User ID.
 * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
 *                        'attribute' and 'js'.
 * @return mixed Sanitized value.
 */
function sanitize_user_field( $field, $value, $user_id, $context ) {
	$int_fields = array( 'ID' );
	if ( in_array( $field, $int_fields, true ) ) {
		$value = (int) $value;
	}

	if ( 'raw' === $context ) {
		return $value;
	}

	if ( ! is_string( $value ) && ! is_numeric( $value ) ) {
		return $value;
	}

	$prefixed = str_contains( $field, 'user_' );

	if ( 'edit' === $context ) {
		if ( $prefixed ) {

			/** This filter is documented in wp-includes/post.php */
			$value = apply_filters( "edit_{$field}", $value, $user_id );
		} else {

			/**
			 * Filters a user field value in the 'edit' context.
			 *
			 * The dynamic portion of the hook name, `$field`, refers to the prefixed user
			 * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
			 *
			 * @since 2.9.0
			 *
			 * @param mixed $value   Value of the prefixed user field.
			 * @param int   $user_id User ID.
			 */
			$value = apply_filters( "edit_user_{$field}", $value, $user_id );
		}

		if ( 'description' === $field ) {
			$value = esc_html( $value ); // textarea_escaped?
		} else {
			$value = esc_attr( $value );
		}
	} elseif ( 'db' === $context ) {
		if ( $prefixed ) {
			/** This filter is documented in wp-includes/post.php */
			$value = apply_filters( "pre_{$field}", $value );
		} else {

			/**
			 * Filters the value of a user field in the 'db' context.
			 *
			 * The dynamic portion of the hook name, `$field`, refers to the prefixed user
			 * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
			 *
			 * @since 2.9.0
			 *
			 * @param mixed $value Value of the prefixed user field.
			 */
			$value = apply_filters( "pre_user_{$field}", $value );
		}
	} else {
		// Use display filters by default.
		if ( $prefixed ) {

			/** This filter is documented in wp-includes/post.php */
			$value = apply_filters( "{$field}", $value, $user_id, $context );
		} else {

			/**
			 * Filters the value of a user field in a standard context.
			 *
			 * The dynamic portion of the hook name, `$field`, refers to the prefixed user
			 * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
			 *
			 * @since 2.9.0
			 *
			 * @param mixed  $value   The user object value to sanitize.
			 * @param int    $user_id User ID.
			 * @param string $context The context to filter within.
			 */
			$value = apply_filters( "user_{$field}", $value, $user_id, $context );
		}
	}

	if ( 'user_url' === $field ) {
		$value = esc_url( $value );
	}

	if ( 'attribute' === $context ) {
		$value = esc_attr( $value );
	} elseif ( 'js' === $context ) {
		$value = esc_js( $value );
	}

	// Restore the type for integer fields after esc_attr().
	if ( in_array( $field, $int_fields, true ) ) {
		$value = (int) $value;
	}

	return $value;
}

/**
 * Updates all user caches.
 *
 * @since 3.0.0
 *
 * @param object|WP_User $user User object or database row to be cached
 * @return void|false Void on success, false on failure.
 */
function update_user_caches( $user ) {
	if ( $user instanceof WP_User ) {
		if ( ! $user->exists() ) {
			return false;
		}

		$user = $user->data;
	}

	wp_cache_add( $user->ID, $user, 'users' );
	wp_cache_add( $user->user_login, $user->ID, 'userlogins' );
	wp_cache_add( $user->user_nicename, $user->ID, 'userslugs' );

	if ( ! empty( $user->user_email ) ) {
		wp_cache_add( $user->user_email, $user->ID, 'useremail' );
	}
}

/**
 * Cleans all user caches.
 *
 * @since 3.0.0
 * @since 4.4.0 'clean_user_cache' action was added.
 * @since 6.2.0 User metadata caches are now cleared.
 *
 * @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_nicename, 'userslugs' );

	if ( ! empty( $user->user_email ) ) {
		wp_cache_delete( $user->user_email, 'useremail' );
	}

	wp_cache_delete( $user->ID, 'user_meta' );
	wp_cache_set_users_last_changed();

	/**
	 * Fires immediately after the given user's cache is cleaned.
	 *
	 * @since 4.4.0
	 *
	 * @param int     $user_id User ID.
	 * @param WP_User $user    User object.
	 */
	do_action( 'clean_user_cache', $user->ID, $user );
}

/**
 * Determines whether the given username exists.
 *
 * For more information on this and similar theme functions, check out
 * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
 * Conditional Tags} article in the Theme Developer Handbook.
 *
 * @since 2.0.0
 *
 * @param string $username The username to check for existence.
 * @return int|false The user ID on success, false on failure.
 */
function username_exists( $username ) {
	$user = get_user_by( 'login', $username );
	if ( $user ) {
		$user_id = $user->ID;
	} else {
		$user_id = false;
	}

	/**
	 * Filters whether the given username exists.
	 *
	 * @since 4.9.0
	 *
	 * @param int|false $user_id  The user ID associated with the username,
	 *                            or false if the username does not exist.
	 * @param string    $username The username to check for existence.
	 */
	return apply_filters( 'username_exists', $user_id, $username );
}

/**
 * Determines whether the given email exists.
 *
 * For more information on this and similar theme functions, check out
 * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
 * Conditional Tags} article in the Theme Developer Handbook.
 *
 * @since 2.1.0
 *
 * @param string $email The email to check for existence.
 * @return int|false The user ID on success, false on failure.
 */
function email_exists( $email ) {
	$user = get_user_by( 'email', $email );
	if ( $user ) {
		$user_id = $user->ID;
	} else {
		$user_id = false;
	}

	/**
	 * Filters whether the given email exists.
	 *
	 * @since 5.6.0
	 *
	 * @param int|false $user_id The user ID associated with the email,
	 *                           or false if the email does not exist.
	 * @param string    $email   The email to check for existence.
	 */
	return apply_filters( 'email_exists', $user_id, $email );
}

/**
 * Checks whether a username is valid.
 *
 * @since 2.0.1
 * @since 4.4.0 Empty sanitized usernames are now considered invalid.
 *
 * @param string $username Username.
 * @return bool Whether username given is valid.
 */
function validate_username( $username ) {
	$sanitized = sanitize_user( $username, true );
	$valid     = ( $sanitized == $username && ! empty( $sanitized ) );

	/**
	 * Filters whether the provided username is valid.
	 *
	 * @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 );
}

/**
 * Inserts a user into the database.
 *
 * Most of the `$userdata` array fields have filters associated with the values. Exceptions are
 * 'ID', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl',
 * 'user_registered', 'user_activation_key', 'spam', and 'role'. 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.
 *
 * @since 2.0.0
 * @since 3.6.0 The `aim`, `jabber`, and `yim` fields were removed as default user contact
 *              methods for new installations. See wp_get_user_contact_methods().
 * @since 4.7.0 The `locale` field can be passed to `$userdata`.
 * @since 5.3.0 The `user_activation_key` field can be passed to `$userdata`.
 * @since 5.3.0 The `spam` field can be passed to `$userdata` (Multisite only).
 * @since 5.9.0 The `meta_input` field can be passed to `$userdata` to allow addition of user meta data.
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param array|object|WP_User $userdata {
 *     An array, object, or WP_User object of user data arguments.
 *
 *     @type int    $ID                   User ID. If supplied, the user will be updated.
 *     @type string $user_pass            The plain-text user password for new users.
 *                                        Hashed password for existing users.
 *     @type string $user_login           The user's login username.
 *     @type string $user_nicename        The URL-friendly user name.
 *     @type string $user_url             The user URL.
 *     @type string $user_email           The user email address.
 *     @type string $display_name         The user's display name.
 *                                        Default is the user's username.
 *     @type string $nickname             The user's nickname.
 *                                        Default is the user's username.
 *     @type string $first_name           The user's first name. For new users, will be used
 *                                        to build the first part of the user's display name
 *                                        if `$display_name` is not specified.
 *     @type string $last_name            The user's last name. For new users, will be used
 *                                        to build the second part of the user's display name
 *                                        if `$display_name` is not specified.
 *     @type string $description          The user's biographical description.
 *     @type string $rich_editing         Whether to enable the rich-editor for the user.
 *                                        Accepts 'true' or 'false' as a string literal,
 *                                        not boolean. Default 'true'.
 *     @type string $syntax_highlighting  Whether to enable the rich code editor for the user.
 *                                        Accepts 'true' or 'false' as a string literal,
 *                                        not boolean. Default 'true'.
 *     @type string $comment_shortcuts    Whether to enable comment moderation keyboard
 *                                        shortcuts for the user. Accepts 'true' or 'false'
 *                                        as a string literal, not boolean. Default 'false'.
 *     @type string $admin_color          Admin color scheme for the user. Default 'fresh'.
 *     @type bool   $use_ssl              Whether the user should always access the admin over
 *                                        https. Default false.
 *     @type string $user_registered      Date the user registered in UTC. Format is 'Y-m-d H:i:s'.
 *     @type string $user_activation_key  Password reset key. Default empty.
 *     @type bool   $spam                 Multisite only. Whether the user is marked as spam.
 *                                        Default false.
 *     @type string $show_admin_bar_front Whether to display the Admin Bar for the user
 *                                        on the site's front end. Accepts 'true' or 'false'
 *                                        as a string literal, not boolean. Default 'true'.
 *     @type string $role                 User's role.
 *     @type string $locale               User's locale. Default empty.
 *     @type array  $meta_input           Array of custom user meta values keyed by meta key.
 *                                        Default empty.
 * }
 * @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 ( $userdata instanceof stdClass ) {
		$userdata = get_object_vars( $userdata );
	} elseif ( $userdata instanceof WP_User ) {
		$userdata = $userdata->to_array();
	}

	// Are we updating or creating?
	if ( ! empty( $userdata['ID'] ) ) {
		$user_id       = (int) $userdata['ID'];
		$update        = true;
		$old_user_data = get_userdata( $user_id );

		if ( ! $old_user_data ) {
			return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
		}

		// Slash current user email to compare it later with slashed new user email.
		$old_user_data->user_email = wp_slash( $old_user_data->user_email );

		// Hashed in wp_update_user(), plaintext if called directly.
		$user_pass = ! empty( $userdata['user_pass'] ) ? $userdata['user_pass'] : $old_user_data->user_pass;
	} else {
		$update = false;
		// Hash the password.
		$user_pass = wp_hash_password( $userdata['user_pass'] );
	}

	$sanitized_user_login = sanitize_user( $userdata['user_login'], true );

	/**
	 * Filters a username after it has been sanitized.
	 *
	 * This filter is called before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $sanitized_user_login Username after it has been sanitized.
	 */
	$pre_user_login = apply_filters( 'pre_user_login', $sanitized_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( $pre_user_login );

	// user_login must be between 0 and 60 characters.
	if ( empty( $user_login ) ) {
		return new WP_Error( 'empty_user_login', __( 'Cannot create a user with an empty login name.' ) );
	} elseif ( mb_strlen( $user_login ) > 60 ) {
		return new WP_Error( 'user_login_too_long', __( 'Username may not be longer than 60 characters.' ) );
	}

	if ( ! $update && username_exists( $user_login ) ) {
		return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
	}

	/**
	 * Filters the list of disallowed usernames.
	 *
	 * @since 4.4.0
	 *
	 * @param array $usernames Array of disallowed usernames.
	 */
	$illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );

	if ( in_array( strtolower( $user_login ), array_map( 'strtolower', $illegal_logins ), true ) ) {
		return new WP_Error( 'invalid_username', __( 'Sorry, that username is not allowed.' ) );
	}

	/*
	 * If a nicename is provided, remove unsafe user characters before using it.
	 * Otherwise build a nicename from the user_login.
	 */
	if ( ! empty( $userdata['user_nicename'] ) ) {
		$user_nicename = sanitize_user( $userdata['user_nicename'], true );
	} else {
		$user_nicename = mb_substr( $user_login, 0, 50 );
	}

	$user_nicename = sanitize_title( $user_nicename );

	/**
	 * Filters 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 ( mb_strlen( $user_nicename ) > 50 ) {
		return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
	}

	$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 ) {
			// user_nicename allows 50 chars. Subtract one for a hyphen, plus the length of the suffix.
			$base_length         = 49 - mb_strlen( $suffix );
			$alt_user_nicename   = mb_substr( $user_nicename, 0, $base_length ) . "-$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;
	}

	$raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];

	/**
	 * Filters a user's email before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $raw_user_email The user's email.
	 */
	$user_email = apply_filters( 'pre_user_email', $raw_user_email );

	/*
	 * If there is no update, just check for `email_exists`. If there is an update,
	 * check if current email and new email are the same, and check `email_exists`
	 * accordingly.
	 */
	if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) )
		&& ! defined( 'WP_IMPORTING' )
		&& email_exists( $user_email )
	) {
		return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
	}

	$raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];

	/**
	 * Filters a user's URL before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $raw_user_url The user's URL.
	 */
	$user_url = apply_filters( 'pre_user_url', $raw_user_url );

	if ( mb_strlen( $user_url ) > 100 ) {
		return new WP_Error( 'user_url_too_long', __( 'User URL may not be longer than 100 characters.' ) );
	}

	$user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];

	$user_activation_key = empty( $userdata['user_activation_key'] ) ? '' : $userdata['user_activation_key'];

	if ( ! empty( $userdata['spam'] ) && ! is_multisite() ) {
		return new WP_Error( 'no_spam', __( 'Sorry, marking a user as spam is only supported on Multisite.' ) );
	}

	$spam = empty( $userdata['spam'] ) ? 0 : (bool) $userdata['spam'];

	// Store values to save in user meta.
	$meta = array();

	$nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];

	/**
	 * Filters a user's nickname before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $nickname The user's nickname.
	 */
	$meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );

	$first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];

	/**
	 * Filters 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.
	 */
	$meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );

	$last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];

	/**
	 * Filters 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.
	 */
	$meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );

	if ( empty( $userdata['display_name'] ) ) {
		if ( $update ) {
			$display_name = $user_login;
		} elseif ( $meta['first_name'] && $meta['last_name'] ) {
			$display_name = sprintf(
				/* translators: 1: User's first name, 2: Last name. */
				_x( '%1$s %2$s', 'Display name based on first name and last name' ),
				$meta['first_name'],
				$meta['last_name']
			);
		} elseif ( $meta['first_name'] ) {
			$display_name = $meta['first_name'];
		} elseif ( $meta['last_name'] ) {
			$display_name = $meta['last_name'];
		} else {
			$display_name = $user_login;
		}
	} else {
		$display_name = $userdata['display_name'];
	}

	/**
	 * Filters 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 );

	$description = empty( $userdata['description'] ) ? '' : $userdata['description'];

	/**
	 * Filters a user's description before the user is created or updated.
	 *
	 * @since 2.0.3
	 *
	 * @param string $description The user's description.
	 */
	$meta['description'] = apply_filters( 'pre_user_description', $description );

	$meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];

	$meta['syntax_highlighting'] = empty( $userdata['syntax_highlighting'] ) ? 'true' : $userdata['syntax_highlighting'];

	$meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';

	$admin_color         = empty( $userdata['admin_color'] ) ? 'fresh' : $userdata['admin_color'];
	$meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );

	$meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? 0 : (bool) $userdata['use_ssl'];

	$meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];

	$meta['locale'] = isset( $userdata['locale'] ) ? $userdata['locale'] : '';

	$compacted = compact( 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'display_name' );
	$data      = wp_unslash( $compacted );

	if ( ! $update ) {
		$data = $data + compact( 'user_login' );
	}

	if ( is_multisite() ) {
		$data = $data + compact( 'spam' );
	}

	/**
	 * Filters user data before the record is created or updated.
	 *
	 * It only includes data in the users table, not any user metadata.
	 *
	 * @since 4.9.0
	 * @since 5.8.0 The `$userdata` parameter was added.
	 *
	 * @param array    $data {
	 *     Values and keys for the user.
	 *
	 *     @type string $user_login      The user's login. Only included if $update == false
	 *     @type string $user_pass       The user's password.
	 *     @type string $user_email      The user's email.
	 *     @type string $user_url        The user's url.
	 *     @type string $user_nicename   The user's nice name. Defaults to a URL-safe version of user's login
	 *     @type string $display_name    The user's display name.
	 *     @type string $user_registered MySQL timestamp describing the moment when the user registered. Defaults to
	 *                                   the current UTC timestamp.
	 * }
	 * @param bool     $update   Whether the user is being updated rather than created.
	 * @param int|null $user_id  ID of the user to be updated, or NULL if the user is being created.
	 * @param array    $userdata The raw array of data passed to wp_insert_user().
	 */
	$data = apply_filters( 'wp_pre_insert_user_data', $data, $update, ( $update ? $user_id : null ), $userdata );

	if ( empty( $data ) || ! is_array( $data ) ) {
		return new WP_Error( 'empty_data', __( 'Not enough data to create this user.' ) );
	}

	if ( $update ) {
		if ( $user_email !== $old_user_data->user_email || $user_pass !== $old_user_data->user_pass ) {
			$data['user_activation_key'] = '';
		}
		$wpdb->update( $wpdb->users, $data, array( 'ID' => $user_id ) );
	} else {
		$wpdb->insert( $wpdb->users, $data );
		$user_id = (int) $wpdb->insert_id;
	}

	$user = new WP_User( $user_id );

	/**
	 * Filters a user's meta values and keys immediately after the user is created or updated
	 * and before any user meta is inserted or updated.
	 *
	 * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`.
	 *
	 * For custom meta fields, see the {@see 'insert_custom_user_meta'} filter.
	 *
	 * @since 4.4.0
	 * @since 5.8.0 The `$userdata` parameter was added.
	 *
	 * @param array $meta {
	 *     Default meta values and keys for the user.
	 *
	 *     @type string   $nickname             The user's nickname. Default is the user's username.
	 *     @type string   $first_name           The user's first name.
	 *     @type string   $last_name            The user's last name.
	 *     @type string   $description          The user's description.
	 *     @type string   $rich_editing         Whether to enable the rich-editor for the user. Default 'true'.
	 *     @type string   $syntax_highlighting  Whether to enable the rich code editor for the user. Default 'true'.
	 *     @type string   $comment_shortcuts    Whether to enable keyboard shortcuts for the user. Default 'false'.
	 *     @type string   $admin_color          The color scheme for a user's admin screen. Default 'fresh'.
	 *     @type int|bool $use_ssl              Whether to force SSL on the user's admin area. 0|false if SSL
	 *                                          is not forced.
	 *     @type string   $show_admin_bar_front Whether to show the admin bar on the front end for the user.
	 *                                          Default 'true'.
	 *     @type string   $locale               User's locale. Default empty.
	 * }
	 * @param WP_User $user     User object.
	 * @param bool    $update   Whether the user is being updated rather than created.
	 * @param array   $userdata The raw array of data passed to wp_insert_user().
	 */
	$meta = apply_filters( 'insert_user_meta', $meta, $user, $update, $userdata );

	$custom_meta = array();
	if ( array_key_exists( 'meta_input', $userdata ) && is_array( $userdata['meta_input'] ) && ! empty( $userdata['meta_input'] ) ) {
		$custom_meta = $userdata['meta_input'];
	}

	/**
	 * Filters a user's custom meta values and keys immediately after the user is created or updated
	 * and before any user meta is inserted or updated.
	 *
	 * For non-custom meta fields, see the {@see 'insert_user_meta'} filter.
	 *
	 * @since 5.9.0
	 *
	 * @param array   $custom_meta Array of custom user meta values keyed by meta key.
	 * @param WP_User $user        User object.
	 * @param bool    $update      Whether the user is being updated rather than created.
	 * @param array   $userdata    The raw array of data passed to wp_insert_user().
	 */
	$custom_meta = apply_filters( 'insert_custom_user_meta', $custom_meta, $user, $update, $userdata );

	$meta = array_merge( $meta, $custom_meta );

	if ( $update ) {
		// Update user meta.
		foreach ( $meta as $key => $value ) {
			update_user_meta( $user_id, $key, $value );
		}
	} else {
		// Add user meta.
		foreach ( $meta as $key => $value ) {
			add_user_meta( $user_id, $key, $value );
		}
	}

	foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
		if ( isset( $userdata[ $key ] ) ) {
			update_user_meta( $user_id, $key, $userdata[ $key ] );
		}
	}

	if ( isset( $userdata['role'] ) ) {
		$user->set_role( $userdata['role'] );
	} elseif ( ! $update ) {
		$user->set_role( get_option( 'default_role' ) );
	}

	clean_user_cache( $user_id );

	if ( $update ) {
		/**
		 * Fires immediately after an existing user is updated.
		 *
		 * @since 2.0.0
		 * @since 5.8.0 The `$userdata` parameter was added.
		 *
		 * @param int     $user_id       User ID.
		 * @param WP_User $old_user_data Object containing user's data prior to update.
		 * @param array   $userdata      The raw array of data passed to wp_insert_user().
		 */
		do_action( 'profile_update', $user_id, $old_user_data, $userdata );

		if ( isset( $userdata['spam'] ) && $userdata['spam'] != $old_user_data->spam ) {
			if ( 1 == $userdata['spam'] ) {
				/**
				 * Fires after the user is marked as a SPAM user.
				 *
				 * @since 3.0.0
				 *
				 * @param int $user_id ID of the user marked as SPAM.
				 */
				do_action( 'make_spam_user', $user_id );
			} else {
				/**
				 * Fires after the user is marked as a HAM user. Opposite of SPAM.
				 *
				 * @since 3.0.0
				 *
				 * @param int $user_id ID of the user marked as HAM.
				 */
				do_action( 'make_ham_user', $user_id );
			}
		}
	} else {
		/**
		 * Fires immediately after a new user is registered.
		 *
		 * @since 1.5.0
		 * @since 5.8.0 The `$userdata` parameter was added.
		 *
		 * @param int   $user_id  User ID.
		 * @param array $userdata The raw array of data passed to wp_insert_user().
		 */
		do_action( 'user_register', $user_id, $userdata );
	}

	return $user_id;
}

/**
 * Updates a 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 array|object|WP_User $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 ( $userdata instanceof stdClass ) {
		$userdata = get_object_vars( $userdata );
	} elseif ( $userdata instanceof WP_User ) {
		$userdata = $userdata->to_array();
	}

	$userdata_raw = $userdata;

	$user_id = isset( $userdata['ID'] ) ? (int) $userdata['ID'] : 0;
	if ( ! $user_id ) {
		return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
	}

	// First, get all of the original fields.
	$user_obj = get_userdata( $user_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( $user_id, $key, true );
	}

	// Escape data pulled from DB.
	$user = add_magic_quotes( $user );

	if ( ! empty( $userdata['user_pass'] ) && $userdata['user_pass'] !== $user_obj->user_pass ) {
		// If password is changing, hash it now.
		$plaintext_pass        = $userdata['user_pass'];
		$userdata['user_pass'] = wp_hash_password( $userdata['user_pass'] );

		/**
		 * Filters whether to send the password change email.
		 *
		 * @since 4.3.0
		 *
		 * @see wp_insert_user() For `$user` and `$userdata` fields.
		 *
		 * @param bool  $send     Whether to send the email.
		 * @param array $user     The original user array.
		 * @param array $userdata The updated user array.
		 */
		$send_password_change_email = apply_filters( 'se