user_login ) { return __( 'That is already this user\'s username.', 'all-in-one-utilities' ); } if ( ! validate_username( $new_username ) ) { return __( 'That username contains invalid characters.', 'all-in-one-utilities' ); } // Taken, waiting in a pending request, or blocked all get the same // answer, so the form can't be used to find out which usernames // exist (and then guess their passwords). if ( ! self::is_available( $new_username, $user ) ) { $suggestions = self::suggestions( $new_username, $user ); if ( ! $suggestions ) { return __( 'That username is not available. Please choose another.', 'all-in-one-utilities' ); } return sprintf( /* translators: %s: comma-separated list of suggested usernames */ __( 'That username is not available. Try another, for example: %s', 'all-in-one-utilities' ), implode( ', ', $suggestions ) ); } return ''; } /** * Whether a valid username is free for this user to take: no other * account has it, no pending request is waiting for it, and it isn't * blocked. * * @param string $username Username. * @param WP_User $user The user being renamed. * @return bool */ private static function is_available( string $username, WP_User $user ): bool { if ( username_exists( $username ) ) { return false; } $illegal = apply_filters( 'illegal_user_logins', array() ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- this is WordPress core's own hook (wp-includes/user.php), not one this plugin defines. if ( in_array( strtolower( $username ), array_map( 'strtolower', (array) $illegal ), true ) ) { return false; } /** * Filters whether a username is held for someone else, e.g. by * Pro's pending username change requests. * * @since 2.0.0 * * @param bool $reserved Whether the username is held. * @param string $username The username. * @param WP_User $user The user being renamed. */ return ! apply_filters( 'aiou_username_is_reserved', false, $username, $user ); } /** * Up to three available usernames based on the one asked for. * * @param string $username The unavailable username. * @param WP_User $user The user being renamed. * @return string[] */ private static function suggestions( string $username, WP_User $user ): array { $base = substr( $username, 0, 52 ); $suggestions = array(); for ( $try = 0; $try < 12; $try++ ) { $candidate = $base . wp_rand( 10, 9999 ); if ( ! in_array( $candidate, $suggestions, true ) && self::is_available( $candidate, $user ) ) { $suggestions[] = $candidate; if ( 3 === count( $suggestions ) ) { break; } } } return $suggestions; } }