<?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
* @global wpdb $wpdb WordPress database abstraction object.
*
* @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 = '' ) {
global $auth_secure_cookie, $wpdb;
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 );
// 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 );
// Clear `user_activation_key` after a successful login.
if ( ! empty( $user->user_activation_key ) ) {
$wpdb->update(
$wpdb->users,
array(
'user_activation_key' => '',
),
array( 'ID' => $user->ID )
);
$user->user_activation_key = '';
}
/**
* 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 ) {
global $auth_secure_cookie;
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 );
}
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 user info by user ID.
*
* @since 6.7.0
*
* @param int $user_id User ID.
*
* @return WP_User|false WP_User object on success, false on failure.
*/
function get_user( $user_id ) {
return get_user_by( 'id', $user_id );
}
/**
* 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_Qu