[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> user.php (source)

   1  <?php
   2  /**
   3   * Core User API
   4   *
   5   * @package WordPress
   6   * @subpackage Users
   7   */
   8  
   9  /**
  10   * Authenticates and logs a user in with 'remember' capability.
  11   *
  12   * The credentials is an array that has 'user_login', 'user_password', and
  13   * 'remember' indices. If the credentials is not given, then the log in form
  14   * will be assumed and used if set.
  15   *
  16   * The various authentication cookies will be set by this function and will be
  17   * set for a longer period depending on if the 'remember' credential is set to
  18   * true.
  19   *
  20   * Note: wp_signon() doesn't handle setting the current user. This means that if the
  21   * function is called before the {@see 'init'} hook is fired, is_user_logged_in() will
  22   * evaluate as false until that point. If is_user_logged_in() is needed in conjunction
  23   * with wp_signon(), wp_set_current_user() should be called explicitly.
  24   *
  25   * @since 2.5.0
  26   *
  27   * @global string $auth_secure_cookie
  28   * @global wpdb   $wpdb               WordPress database abstraction object.
  29   *
  30   * @param array       $credentials {
  31   *     Optional. User info in order to sign on.
  32   *
  33   *     @type string $user_login    Username.
  34   *     @type string $user_password User password.
  35   *     @type bool   $remember      Whether to 'remember' the user. Increases the time
  36   *                                 that the cookie will be kept. Default false.
  37   * }
  38   * @param string|bool $secure_cookie Optional. Whether to use secure cookie.
  39   * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  40   */
  41  function wp_signon( $credentials = array(), $secure_cookie = '' ) {
  42      global $auth_secure_cookie, $wpdb;
  43  
  44      if ( empty( $credentials ) ) {
  45          $credentials = array(
  46              'user_login'    => '',
  47              'user_password' => '',
  48              'remember'      => false,
  49          );
  50  
  51          if ( ! empty( $_POST['log'] ) && is_string( $_POST['log'] ) ) {
  52              $credentials['user_login'] = wp_unslash( $_POST['log'] );
  53          }
  54          if ( ! empty( $_POST['pwd'] ) && is_string( $_POST['pwd'] ) ) {
  55              $credentials['user_password'] = $_POST['pwd'];
  56          }
  57          if ( ! empty( $_POST['rememberme'] ) ) {
  58              $credentials['remember'] = $_POST['rememberme'];
  59          }
  60      }
  61  
  62      if ( ! empty( $credentials['remember'] ) ) {
  63          $credentials['remember'] = true;
  64      } else {
  65          $credentials['remember'] = false;
  66      }
  67  
  68      /**
  69       * Fires before the user is authenticated.
  70       *
  71       * The variables passed to the callbacks are passed by reference,
  72       * and can be modified by callback functions.
  73       *
  74       * @since 1.5.1
  75       *
  76       * @todo Decide whether to deprecate the wp_authenticate action.
  77       *
  78       * @param string $user_login    Username (passed by reference).
  79       * @param string $user_password User password (passed by reference).
  80       */
  81      do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );
  82  
  83      if ( '' === $secure_cookie ) {
  84          $secure_cookie = is_ssl();
  85      }
  86  
  87      /**
  88       * Filters whether to use a secure sign-on cookie.
  89       *
  90       * @since 3.1.0
  91       *
  92       * @param bool  $secure_cookie Whether to use a secure sign-on cookie.
  93       * @param array $credentials {
  94       *     Array of entered sign-on data.
  95       *
  96       *     @type string $user_login    Username.
  97       *     @type string $user_password Password entered.
  98       *     @type bool   $remember      Whether to 'remember' the user. Increases the time
  99       *                                 that the cookie will be kept. Default false.
 100       * }
 101       */
 102      $secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );
 103  
 104      // XXX ugly hack to pass this to wp_authenticate_cookie().
 105      $auth_secure_cookie = $secure_cookie;
 106  
 107      add_filter( 'authenticate', 'wp_authenticate_cookie', 30, 3 );
 108  
 109      $user = wp_authenticate( $credentials['user_login'], $credentials['user_password'] );
 110  
 111      if ( is_wp_error( $user ) ) {
 112          return $user;
 113      }
 114  
 115      wp_set_auth_cookie( $user->ID, $credentials['remember'], $secure_cookie );
 116  
 117      // Clear `user_activation_key` after a successful login.
 118      if ( ! empty( $user->user_activation_key ) ) {
 119          $wpdb->update(
 120              $wpdb->users,
 121              array(
 122                  'user_activation_key' => '',
 123              ),
 124              array( 'ID' => $user->ID )
 125          );
 126  
 127          $user->user_activation_key = '';
 128      }
 129  
 130      /**
 131       * Fires after the user has successfully logged in.
 132       *
 133       * @since 1.5.0
 134       *
 135       * @param string  $user_login Username.
 136       * @param WP_User $user       WP_User object of the logged-in user.
 137       */
 138      do_action( 'wp_login', $user->user_login, $user );
 139  
 140      return $user;
 141  }
 142  
 143  /**
 144   * Authenticates a user, confirming the username and password are valid.
 145   *
 146   * @since 2.8.0
 147   *
 148   * @param WP_User|WP_Error|null $user     WP_User or WP_Error object from a previous callback. Default null.
 149   * @param string                $username Username for authentication.
 150   * @param string                $password Password for authentication.
 151   * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 152   */
 153  function wp_authenticate_username_password(
 154      $user,
 155      $username,
 156      #[\SensitiveParameter]
 157      $password
 158  ) {
 159      if ( $user instanceof WP_User ) {
 160          return $user;
 161      }
 162  
 163      if ( empty( $username ) || empty( $password ) ) {
 164          if ( is_wp_error( $user ) ) {
 165              return $user;
 166          }
 167  
 168          $error = new WP_Error();
 169  
 170          if ( empty( $username ) ) {
 171              $error->add( 'empty_username', __( '<strong>Error:</strong> The username field is empty.' ) );
 172          }
 173  
 174          if ( empty( $password ) ) {
 175              $error->add( 'empty_password', __( '<strong>Error:</strong> The password field is empty.' ) );
 176          }
 177  
 178          return $error;
 179      }
 180  
 181      $user = get_user_by( 'login', $username );
 182  
 183      if ( ! $user ) {
 184          return new WP_Error(
 185              'invalid_username',
 186              sprintf(
 187                  /* translators: %s: User name. */
 188                  __( '<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.' ),
 189                  esc_html( $username )
 190              )
 191          );
 192      }
 193  
 194      /**
 195       * Filters whether the given user can be authenticated with the provided password.
 196       *
 197       * @since 2.5.0
 198       *
 199       * @param WP_User|WP_Error $user     WP_User or WP_Error object if a previous
 200       *                                   callback failed authentication.
 201       * @param string           $password Password to check against the user.
 202       */
 203      $user = apply_filters( 'wp_authenticate_user', $user, $password );
 204      if ( is_wp_error( $user ) ) {
 205          return $user;
 206      }
 207  
 208      $valid = wp_check_password( $password, $user->user_pass, $user->ID );
 209  
 210      if ( ! $valid ) {
 211          return new WP_Error(
 212              'incorrect_password',
 213              sprintf(
 214                  /* translators: %s: User name. */
 215                  __( '<strong>Error:</strong> The password you entered for the username %s is incorrect.' ),
 216                  '<strong>' . esc_html( $username ) . '</strong>'
 217              ) .
 218              ' <a href="' . wp_lostpassword_url() . '">' .
 219              __( 'Lost your password?' ) .
 220              '</a>'
 221          );
 222      }
 223  
 224      if ( wp_password_needs_rehash( $user->user_pass, $user->ID ) ) {
 225          wp_set_password( $password, $user->ID );
 226      }
 227  
 228      return $user;
 229  }
 230  
 231  /**
 232   * Authenticates a user using the email and password.
 233   *
 234   * @since 4.5.0
 235   *
 236   * @param WP_User|WP_Error|null $user     WP_User or WP_Error object if a previous
 237   *                                        callback failed authentication.
 238   * @param string                $email    Email address for authentication.
 239   * @param string                $password Password for authentication.
 240   * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 241   */
 242  function wp_authenticate_email_password(
 243      $user,
 244      $email,
 245      #[\SensitiveParameter]
 246      $password
 247  ) {
 248      if ( $user instanceof WP_User ) {
 249          return $user;
 250      }
 251  
 252      if ( empty( $email ) || empty( $password ) ) {
 253          if ( is_wp_error( $user ) ) {
 254              return $user;
 255          }
 256  
 257          $error = new WP_Error();
 258  
 259          if ( empty( $email ) ) {
 260              // Uses 'empty_username' for back-compat with wp_signon().
 261              $error->add( 'empty_username', __( '<strong>Error:</strong> The email field is empty.' ) );
 262          }
 263  
 264          if ( empty( $password ) ) {
 265              $error->add( 'empty_password', __( '<strong>Error:</strong> The password field is empty.' ) );
 266          }
 267  
 268          return $error;
 269      }
 270  
 271      if ( ! is_email( $email ) ) {
 272          return $user;
 273      }
 274  
 275      $user = get_user_by( 'email', $email );
 276  
 277      if ( ! $user ) {
 278          return new WP_Error(
 279              'invalid_email',
 280              __( 'Unknown email address. Check again or try your username.' )
 281          );
 282      }
 283  
 284      /** This filter is documented in wp-includes/user.php */
 285      $user = apply_filters( 'wp_authenticate_user', $user, $password );
 286  
 287      if ( is_wp_error( $user ) ) {
 288          return $user;
 289      }
 290  
 291      $valid = wp_check_password( $password, $user->user_pass, $user->ID );
 292  
 293      if ( ! $valid ) {
 294          return new WP_Error(
 295              'incorrect_password',
 296              sprintf(
 297                  /* translators: %s: Email address. */
 298                  __( '<strong>Error:</strong> The password you entered for the email address %s is incorrect.' ),
 299                  '<strong>' . esc_html( $email ) . '</strong>'
 300              ) .
 301              ' <a href="' . wp_lostpassword_url() . '">' .
 302              __( 'Lost your password?' ) .
 303              '</a>'
 304          );
 305      }
 306  
 307      if ( wp_password_needs_rehash( $user->user_pass, $user->ID ) ) {
 308          wp_set_password( $password, $user->ID );
 309      }
 310  
 311      return $user;
 312  }
 313  
 314  /**
 315   * Authenticates the user using the WordPress auth cookie.
 316   *
 317   * @since 2.8.0
 318   *
 319   * @global string $auth_secure_cookie
 320   *
 321   * @param WP_User|WP_Error|null $user     WP_User or WP_Error object from a previous callback. Default null.
 322   * @param string                $username Username. If not empty, cancels the cookie authentication.
 323   * @param string                $password Password. If not empty, cancels the cookie authentication.
 324   * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 325   */
 326  function wp_authenticate_cookie(
 327      $user,
 328      $username,
 329      #[\SensitiveParameter]
 330      $password
 331  ) {
 332      global $auth_secure_cookie;
 333  
 334      if ( $user instanceof WP_User ) {
 335          return $user;
 336      }
 337  
 338      if ( empty( $username ) && empty( $password ) ) {
 339          $user_id = wp_validate_auth_cookie();
 340          if ( $user_id ) {
 341              return new WP_User( $user_id );
 342          }
 343  
 344          if ( $auth_secure_cookie ) {
 345              $auth_cookie = SECURE_AUTH_COOKIE;
 346          } else {
 347              $auth_cookie = AUTH_COOKIE;
 348          }
 349  
 350          if ( ! empty( $_COOKIE[ $auth_cookie ] ) ) {
 351              return new WP_Error( 'expired_session', __( 'Please log in again.' ) );
 352          }
 353  
 354          // If the cookie is not set, be silent.
 355      }
 356  
 357      return $user;
 358  }
 359  
 360  /**
 361   * Authenticates the user using an application password.
 362   *
 363   * @since 5.6.0
 364   *
 365   * @param WP_User|WP_Error|null $input_user WP_User or WP_Error object if a previous
 366   *                                          callback failed authentication.
 367   * @param string                $username   Username for authentication.
 368   * @param string                $password   Password for authentication.
 369   * @return WP_User|WP_Error|null WP_User on success, WP_Error on failure, null if
 370   *                               null is passed in and this isn't an API request.
 371   */
 372  function wp_authenticate_application_password(
 373      $input_user,
 374      $username,
 375      #[\SensitiveParameter]
 376      $password
 377  ) {
 378      if ( $input_user instanceof WP_User ) {
 379          return $input_user;
 380      }
 381  
 382      if ( ! WP_Application_Passwords::is_in_use() ) {
 383          return $input_user;
 384      }
 385  
 386      // The 'REST_REQUEST' check here may happen too early for the constant to be available.
 387      $is_api_request = ( ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) );
 388  
 389      /**
 390       * Filters whether this is an API request that Application Passwords can be used on.
 391       *
 392       * By default, Application Passwords is available for the REST API and XML-RPC.
 393       *
 394       * @since 5.6.0
 395       *
 396       * @param bool $is_api_request If this is an acceptable API request.
 397       */
 398      $is_api_request = apply_filters( 'application_password_is_api_request', $is_api_request );
 399  
 400      if ( ! $is_api_request ) {
 401          return $input_user;
 402      }
 403  
 404      $error = null;
 405      $user  = get_user_by( 'login', $username );
 406  
 407      if ( ! $user && is_email( $username ) ) {
 408          $user = get_user_by( 'email', $username );
 409      }
 410  
 411      // If the login name is invalid, short circuit.
 412      if ( ! $user ) {
 413          if ( is_email( $username ) ) {
 414              $error = new WP_Error(
 415                  'invalid_email',
 416                  __( '<strong>Error:</strong> Unknown email address. Check again or try your username.' )
 417              );
 418          } else {
 419              $error = new WP_Error(
 420                  'invalid_username',
 421                  __( '<strong>Error:</strong> Unknown username. Check again or try your email address.' )
 422              );
 423          }
 424      } elseif ( ! wp_is_application_passwords_available() ) {
 425          $error = new WP_Error(
 426              'application_passwords_disabled',
 427              __( 'Application passwords are not available.' )
 428          );
 429      } elseif ( ! wp_is_application_passwords_available_for_user( $user ) ) {
 430          $error = new WP_Error(
 431              'application_passwords_disabled_for_user',
 432              __( 'Application passwords are not available for your account. Please contact the site administrator for assistance.' )
 433          );
 434      }
 435  
 436      if ( $error ) {
 437          /**
 438           * Fires when an application password failed to authenticate the user.
 439           *
 440           * @since 5.6.0
 441           *
 442           * @param WP_Error $error The authentication error.
 443           */
 444          do_action( 'application_password_failed_authentication', $error );
 445  
 446          return $error;
 447      }
 448  
 449      /*
 450       * Strips out anything non-alphanumeric. This is so passwords can be used with
 451       * or without spaces to indicate the groupings for readability.
 452       *
 453       * Generated application passwords are exclusively alphanumeric.
 454       */
 455      $password = preg_replace( '/[^a-z\d]/i', '', $password );
 456  
 457      $hashed_passwords = WP_Application_Passwords::get_user_application_passwords( $user->ID );
 458  
 459      foreach ( $hashed_passwords as $key => $item ) {
 460          if ( ! WP_Application_Passwords::check_password( $password, $item['password'] ) ) {
 461              continue;
 462          }
 463  
 464          $error = new WP_Error();
 465  
 466          /**
 467           * Fires when an application password has been successfully checked as valid.
 468           *
 469           * This allows for plugins to add additional constraints to prevent an application password from being used.
 470           *
 471           * @since 5.6.0
 472           *
 473           * @param WP_Error $error    The error object.
 474           * @param WP_User  $user     The user authenticating.
 475           * @param array    $item     The details about the application password.
 476           * @param string   $password The raw supplied password.
 477           */
 478          do_action( 'wp_authenticate_application_password_errors', $error, $user, $item, $password );
 479  
 480          if ( $error->has_errors() ) {
 481              /** This action is documented in wp-includes/user.php */
 482              do_action( 'application_password_failed_authentication', $error );
 483  
 484              return $error;
 485          }
 486  
 487          WP_Application_Passwords::record_application_password_usage( $user->ID, $item['uuid'] );
 488  
 489          /**
 490           * Fires after an application password was used for authentication.
 491           *
 492           * @since 5.6.0
 493           *
 494           * @param WP_User $user The user who was authenticated.
 495           * @param array   $item The application password used.
 496           */
 497          do_action( 'application_password_did_authenticate', $user, $item );
 498  
 499          return $user;
 500      }
 501  
 502      $error = new WP_Error(
 503          'incorrect_password',
 504          __( 'The provided password is an invalid application password.' )
 505      );
 506  
 507      /** This action is documented in wp-includes/user.php */
 508      do_action( 'application_password_failed_authentication', $error );
 509  
 510      return $error;
 511  }
 512  
 513  /**
 514   * Validates the application password credentials passed via Basic Authentication.
 515   *
 516   * @since 5.6.0
 517   *
 518   * @param int|false $input_user User ID if one has been determined, false otherwise.
 519   * @return int|false The authenticated user ID if successful, false otherwise.
 520   */
 521  function wp_validate_application_password( $input_user ) {
 522      // Don't authenticate twice.
 523      if ( ! empty( $input_user ) ) {
 524          return $input_user;
 525      }
 526  
 527      if ( ! wp_is_application_passwords_available() ) {
 528          return $input_user;
 529      }
 530  
 531      // Both $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] must be set in order to attempt authentication.
 532      if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
 533          return $input_user;
 534      }
 535  
 536      $authenticated = wp_authenticate_application_password( null, $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] );
 537  
 538      if ( $authenticated instanceof WP_User ) {
 539          return $authenticated->ID;
 540      }
 541  
 542      // If it wasn't a user what got returned, just pass on what we had received originally.
 543      return $input_user;
 544  }
 545  
 546  /**
 547   * For Multisite blogs, checks if the authenticated user has been marked as a
 548   * spammer, or if the user's primary blog has been marked as spam.
 549   *
 550   * @since 3.7.0
 551   *
 552   * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
 553   * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
 554   */
 555  function wp_authenticate_spam_check( $user ) {
 556      if ( $user instanceof WP_User && is_multisite() ) {
 557          /**
 558           * Filters whether the user has been marked as a spammer.
 559           *
 560           * @since 3.7.0
 561           *
 562           * @param bool    $spammed Whether the user is considered a spammer.
 563           * @param WP_User $user    User to check against.
 564           */
 565          $spammed = apply_filters( 'check_is_user_spammed', is_user_spammy( $user ), $user );
 566  
 567          if ( $spammed ) {
 568              return new WP_Error( 'spammer_account', __( '<strong>Error:</strong> Your account has been marked as a spammer.' ) );
 569          }
 570      }
 571      return $user;
 572  }
 573  
 574  /**
 575   * Validates the logged-in cookie.
 576   *
 577   * Checks the logged-in cookie if the previous auth cookie could not be
 578   * validated and parsed.
 579   *
 580   * This is a callback for the {@see 'determine_current_user'} filter, rather than API.
 581   *
 582   * @since 3.9.0
 583   *
 584   * @param int|false $user_id The user ID (or false) as received from
 585   *                           the `determine_current_user` filter.
 586   * @return int|false User ID if validated, false otherwise. If a user ID from
 587   *                   an earlier filter callback is received, that value is returned.
 588   */
 589  function wp_validate_logged_in_cookie( $user_id ) {
 590      if ( $user_id ) {
 591          return $user_id;
 592      }
 593  
 594      if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
 595          return false;
 596      }
 597  
 598      return wp_validate_auth_cookie( $_COOKIE[ LOGGED_IN_COOKIE ], 'logged_in' );
 599  }
 600  
 601  /**
 602   * Gets the number of posts a user has written.
 603   *
 604   * @since 3.0.0
 605   * @since 4.1.0 Added `$post_type` argument.
 606   * @since 4.3.0 Added `$public_only` argument. Added the ability to pass an array
 607   *              of post types to `$post_type`.
 608   *
 609   * @global wpdb $wpdb WordPress database abstraction object.
 610   *
 611   * @param int          $userid      User ID.
 612   * @param array|string $post_type   Optional. Single post type or array of post types to count the number of posts for. Default 'post'.
 613   * @param bool         $public_only Optional. Whether to only return counts for public posts. Default false.
 614   * @return string Number of posts the user has written in this post type.
 615   */
 616  function count_user_posts( $userid, $post_type = 'post', $public_only = false ) {
 617      global $wpdb;
 618  
 619      $post_type = array_unique( (array) $post_type );
 620      sort( $post_type );
 621  
 622      $where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
 623      $query = "SELECT COUNT(*) FROM $wpdb->posts $where";
 624  
 625      $last_changed = wp_cache_get_last_changed( 'posts' );
 626      $cache_key    = 'count_user_posts:' . md5( $query );
 627      $count        = wp_cache_get_salted( $cache_key, 'post-queries', $last_changed );
 628      if ( false === $count ) {
 629          $count = $wpdb->get_var( $query );
 630          wp_cache_set_salted( $cache_key, $count, 'post-queries', $last_changed );
 631      }
 632  
 633      /**
 634       * Filters the number of posts a user has written.
 635       *
 636       * @since 2.7.0
 637       * @since 4.1.0 Added `$post_type` argument.
 638       * @since 4.3.1 Added `$public_only` argument.
 639       *
 640       * @param string       $count       The user's post count as a numeric string.
 641       * @param int          $userid      User ID.
 642       * @param string|array $post_type   Single post type or array of post types to count the number of posts for.
 643       * @param bool         $public_only Whether to limit counted posts to public posts.
 644       */
 645      return apply_filters( 'get_usernumposts', $count, $userid, $post_type, $public_only );
 646  }
 647  
 648  /**
 649   * Gets the number of posts written by a list of users.
 650   *
 651   * @since 3.0.0
 652   * @since 6.9.0 The results are now cached.
 653   *
 654   * @global wpdb $wpdb WordPress database abstraction object.
 655   *
 656   * @param int[]           $users       Array of user IDs.
 657   * @param string|string[] $post_type   Optional. Single post type or array of post types to check. Defaults to 'post'.
 658   * @param bool            $public_only Optional. Only return counts for public posts.  Defaults to false.
 659   * @return array<int, string> Amount of posts each user has written, as strings, keyed by user ID.
 660   */
 661  function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
 662      global $wpdb;
 663  
 664      if ( empty( $users ) || ! is_array( $users ) ) {
 665          return array();
 666      }
 667  
 668      /**
 669       * Filters whether to short-circuit performing the post counts.
 670       *
 671       * When filtering, return an array of posts counts as strings, keyed
 672       * by the user ID.
 673       *
 674       * @since 6.8.0
 675       *
 676       * @param string[]|null   $count       The post counts. Return a non-null value to short-circuit.
 677       * @param int[]           $users       Array of user IDs.
 678       * @param string|string[] $post_type   Single post type or array of post types to check.
 679       * @param bool            $public_only Whether to only return counts for public posts.
 680       */
 681      $pre = apply_filters( 'pre_count_many_users_posts', null, $users, $post_type, $public_only );
 682      if ( null !== $pre ) {
 683          return $pre;
 684      }
 685  
 686      // Cleanup the users array. Remove duplicates and sort for consistent ordering.
 687      $users = array_unique( array_filter( array_map( 'intval', $users ) ) );
 688      sort( $users );
 689  
 690      // Cleanup the post type argument. Remove duplicates and sort for consistent ordering.
 691      $post_type = array_unique( (array) $post_type );
 692      sort( $post_type );
 693  
 694      $userlist    = implode( ',', $users );
 695      $where       = get_posts_by_author_sql( $post_type, true, null, $public_only );
 696      $query       = "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author";
 697      $cache_key   = 'count_many_users_posts:' . md5( $query );
 698      $cache_salts = array( wp_cache_get_last_changed( 'posts' ), wp_cache_get_last_changed( 'users' ) );
 699      $count       = wp_cache_get_salted( $cache_key, 'post-queries', $cache_salts );
 700  
 701      if ( false === $count ) {
 702          $result = $wpdb->get_results( $query, ARRAY_N );
 703  
 704          $count = array_fill_keys( $users, 0 );
 705          foreach ( $result as $row ) {
 706              $count[ $row[0] ] = $row[1];
 707          }
 708  
 709          wp_cache_set_salted( $cache_key, $count, 'post-queries', $cache_salts, HOUR_IN_SECONDS );
 710      }
 711  
 712      return $count;
 713  }
 714  
 715  //
 716  // User option functions.
 717  //
 718  
 719  /**
 720   * Gets the current user's ID.
 721   *
 722   * @since MU (3.0.0)
 723   *
 724   * @return int The current user's ID, or 0 if no user is logged in.
 725   */
 726  function get_current_user_id() {
 727      if ( ! function_exists( 'wp_get_current_user' ) ) {
 728          return 0;
 729      }
 730      $user = wp_get_current_user();
 731      return (int) $user->ID;
 732  }
 733  
 734  /**
 735   * Retrieves user option that can be either per Site or per Network.
 736   *
 737   * If the user ID is not given, then the current user will be used instead. If
 738   * the user ID is given, then the user data will be retrieved. The filter for
 739   * the result, will also pass the original option name and finally the user data
 740   * object as the third parameter.
 741   *
 742   * The option will first check for the per site name and then the per Network name.
 743   *
 744   * @since 2.0.0
 745   *
 746   * @global wpdb $wpdb WordPress database abstraction object.
 747   *
 748   * @param string $option     User option name.
 749   * @param int    $user       Optional. User ID.
 750   * @param string $deprecated Use get_option() to check for an option in the options table.
 751   * @return mixed User option value on success, false on failure.
 752   *
 753   * @phpstan-param '' $deprecated
 754   */
 755  function get_user_option( $option, $user = 0, $deprecated = '' ) {
 756      global $wpdb;
 757  
 758      if ( ! empty( $deprecated ) ) {
 759          _deprecated_argument( __FUNCTION__, '3.0.0' );
 760      }
 761  
 762      if ( empty( $user ) ) {
 763          $user = get_current_user_id();
 764      }
 765  
 766      $user = get_userdata( $user );
 767      if ( ! $user ) {
 768          return false;
 769      }
 770  
 771      $prefix = $wpdb->get_blog_prefix();
 772      if ( $user->has_prop( $prefix . $option ) ) { // Blog-specific.
 773          $result = $user->get( $prefix . $option );
 774      } elseif ( $user->has_prop( $option ) ) { // User-specific and cross-blog.
 775          $result = $user->get( $option );
 776      } else {
 777          $result = false;
 778      }
 779  
 780      /**
 781       * Filters a specific user option value.
 782       *
 783       * The dynamic portion of the hook name, `$option`, refers to the user option name.
 784       *
 785       * @since 2.5.0
 786       *
 787       * @param mixed   $result Value for the user's option.
 788       * @param string  $option Name of the option being retrieved.
 789       * @param WP_User $user   WP_User object of the user whose option is being retrieved.
 790       */
 791      return apply_filters( "get_user_option_{$option}", $result, $option, $user );
 792  }
 793  
 794  /**
 795   * Updates user option with global blog capability.
 796   *
 797   * User options are just like user metadata except that they have support for
 798   * global blog options. If the 'is_global' parameter is false, which it is by default,
 799   * it will prepend the WordPress table prefix to the option name.
 800   *
 801   * Deletes the user option if $newvalue is empty.
 802   *
 803   * @since 2.0.0
 804   *
 805   * @global wpdb $wpdb WordPress database abstraction object.
 806   *
 807   * @param int    $user_id     User ID.
 808   * @param string $option_name User option name.
 809   * @param mixed  $newvalue    User option value.
 810   * @param bool   $is_global   Optional. Whether option name is global or blog specific.
 811   *                            Default false (blog specific).
 812   * @return int|bool User meta ID if the option didn't exist, true on successful update,
 813   *                  false on failure.
 814   */
 815  function update_user_option( $user_id, $option_name, $newvalue, $is_global = false ) {
 816      global $wpdb;
 817  
 818      if ( ! $is_global ) {
 819          $option_name = $wpdb->get_blog_prefix() . $option_name;
 820      }
 821  
 822      return update_user_meta( $user_id, $option_name, $newvalue );
 823  }
 824  
 825  /**
 826   * Deletes user option with global blog capability.
 827   *
 828   * User options are just like user metadata except that they have support for
 829   * global blog options. If the 'is_global' parameter is false, which it is by default,
 830   * it will prepend the WordPress table prefix to the option name.
 831   *
 832   * @since 3.0.0
 833   *
 834   * @global wpdb $wpdb WordPress database abstraction object.
 835   *
 836   * @param int    $user_id     User ID
 837   * @param string $option_name User option name.
 838   * @param bool   $is_global   Optional. Whether option name is global or blog specific.
 839   *                            Default false (blog specific).
 840   * @return bool True on success, false on failure.
 841   */
 842  function delete_user_option( $user_id, $option_name, $is_global = false ) {
 843      global $wpdb;
 844  
 845      if ( ! $is_global ) {
 846          $option_name = $wpdb->get_blog_prefix() . $option_name;
 847      }
 848  
 849      return delete_user_meta( $user_id, $option_name );
 850  }
 851  
 852  /**
 853   * Retrieves user info by user ID.
 854   *
 855   * @since 6.7.0
 856   *
 857   * @param int $user_id User ID.
 858   * @return WP_User|false WP_User object on success, false on failure.
 859   *
 860   * @phpstan-return ( $user_id is int<min, 0> ? false : WP_User|false )
 861   */
 862  function get_user( $user_id ) {
 863      return get_user_by( 'id', $user_id );
 864  }
 865  
 866  /**
 867   * Retrieves list of users matching criteria.
 868   *
 869   * @since 3.1.0
 870   *
 871   * @see WP_User_Query
 872   *
 873   * @param array $args Optional. Arguments to retrieve users. See WP_User_Query::prepare_query()
 874   *                    for more information on accepted arguments.
 875   * @return array List of users.
 876   *
 877   * @phpstan-return (
 878   *     $args is array{ fields: 'all'|'all_with_meta', ... } ? array<int, WP_User> : (
 879   *         $args is array{ fields: 'ID'|'id', ... } ? list<numeric-string> : (
 880   *             $args is array{ fields: non-empty-string|non-empty-array<array-key, string>, ... } ? array<int, mixed> : array<int, WP_User>
 881   *         )
 882   *     )
 883   * )
 884   */
 885  function get_users( $args = array() ) {
 886  
 887      $args                = wp_parse_args( $args );
 888      $args['count_total'] = false;
 889  
 890      $user_search = new WP_User_Query( $args );
 891  
 892      return (array) $user_search->get_results();
 893  }
 894  
 895  /**
 896   * Lists all the users of the site, with several options available.
 897   *
 898   * @since 5.9.0
 899   *
 900   * @param string|array $args {
 901   *     Optional. Array or string of default arguments.
 902   *
 903   *     @type string $orderby       How to sort the users. Accepts 'nicename', 'email', 'url', 'registered',
 904   *                                 'user_nicename', 'user_email', 'user_url', 'user_registered', 'name',
 905   *                                 'display_name', 'post_count', 'ID', 'meta_value', 'user_login'. Default 'name'.
 906   *     @type string $order         Sorting direction for $orderby. Accepts 'ASC', 'DESC'. Default 'ASC'.
 907   *     @type int    $number        Maximum users to return or display. Default empty (all users).
 908   *     @type bool   $exclude_admin Whether to exclude the 'admin' account, if it exists. Default true.
 909   *     @type bool   $show_fullname Whether to show the user's full name. Default false.
 910   *     @type string $feed          If not empty, show a link to the user's feed and use this text as the alt
 911   *                                 parameter of the link. Default empty.
 912   *     @type string $feed_image    If not empty, show a link to the user's feed and use this image URL as
 913   *                                 clickable anchor. Default empty.
 914   *     @type string $feed_type     The feed type to link to, such as 'rss2'. Defaults to default feed type.
 915   *     @type bool   $echo          Whether to output the result or instead return it. Default true.
 916   *     @type string $style         If 'list', each user is wrapped in an `<li>` element, otherwise the users
 917   *                                 will be separated by commas.
 918   *     @type bool   $html          Whether to list the items in HTML form or plaintext. Default true.
 919   *     @type string $exclude       An array, comma-, or space-separated list of user IDs to exclude. Default empty.
 920   *     @type string $include       An array, comma-, or space-separated list of user IDs to include. Default empty.
 921   * }
 922   * @return string|void The output if 'echo' is false, nothing otherwise.
 923   * @phpstan-return (
 924   *     $args is array{ echo: false|0|''|'0', ... }
 925   *         ? string
 926   *         : ( $args is ''|'0'|array ? void : string|null )
 927   * )
 928   */
 929  function wp_list_users( $args = array() ) {
 930      $defaults = array(
 931          'orderby'       => 'name',
 932          'order'         => 'ASC',
 933          'number'        => '',
 934          'exclude_admin' => true,
 935          'show_fullname' => false,
 936          'feed'          => '',
 937          'feed_image'    => '',
 938          'feed_type'     => '',
 939          'echo'          => true,
 940          'style'         => 'list',
 941          'html'          => true,
 942          'exclude'       => '',
 943          'include'       => '',
 944      );
 945  
 946      $parsed_args = wp_parse_args( $args, $defaults );
 947  
 948      $return = '';
 949  
 950      $query_args           = wp_array_slice_assoc( $parsed_args, array( 'orderby', 'order', 'number', 'exclude', 'include' ) );
 951      $query_args['fields'] = 'ids';
 952  
 953      /**
 954       * Filters the query arguments for the list of all users of the site.
 955       *
 956       * @since 6.1.0
 957       *
 958       * @param array $query_args  The query arguments for get_users().
 959       * @param array $parsed_args The arguments passed to wp_list_users() combined with the defaults.
 960       */
 961      $query_args = apply_filters( 'wp_list_users_args', $query_args, $parsed_args );
 962  
 963      $users = get_users( $query_args );
 964  
 965      foreach ( $users as $user_id ) {
 966          $user = get_userdata( $user_id );
 967  
 968          if ( $parsed_args['exclude_admin'] && 'admin' === $user->display_name ) {
 969              continue;
 970          }
 971  
 972          if ( $parsed_args['show_fullname'] && '' !== $user->first_name && '' !== $user->last_name ) {
 973              $name = sprintf(
 974                  /* translators: 1: User's first name, 2: Last name. */
 975                  _x( '%1$s %2$s', 'Display name based on first name and last name' ),
 976                  $user->first_name,
 977                  $user->last_name
 978              );
 979          } else {
 980              $name = $user->display_name;
 981          }
 982  
 983          if ( ! $parsed_args['html'] ) {
 984              $return .= $name . ', ';
 985  
 986              continue; // No need to go further to process HTML.
 987          }
 988  
 989          if ( 'list' === $parsed_args['style'] ) {
 990              $return .= '<li>';
 991          }
 992  
 993          $row = $name;
 994  
 995          if ( ! empty( $parsed_args['feed_image'] ) || ! empty( $parsed_args['feed'] ) ) {
 996              $row .= ' ';
 997              if ( empty( $parsed_args['feed_image'] ) ) {
 998                  $row .= '(';
 999              }
1000  
1001              $row .= '<a href="' . get_author_feed_link( $user->ID, $parsed_args['feed_type'] ) . '"';
1002  
1003              $alt = '';
1004              if ( ! empty( $parsed_args['feed'] ) ) {
1005                  $alt  = ' alt="' . esc_attr( $parsed_args['feed'] ) . '"';
1006                  $name = $parsed_args['feed'];
1007              }
1008  
1009              $row .= '>';
1010  
1011              if ( ! empty( $parsed_args['feed_image'] ) ) {
1012                  $row .= '<img src="' . esc_url( $parsed_args['feed_image'] ) . '" style="border: none;"' . $alt . ' />';
1013              } else {
1014                  $row .= $name;
1015              }
1016  
1017              $row .= '</a>';
1018  
1019              if ( empty( $parsed_args['feed_image'] ) ) {
1020                  $row .= ')';
1021              }
1022          }
1023  
1024          $return .= $row;
1025          $return .= ( 'list' === $parsed_args['style'] ) ? '</li>' : ', ';
1026      }
1027  
1028      $return = rtrim( $return, ', ' );
1029  
1030      if ( ! $parsed_args['echo'] ) {
1031          return $return;
1032      }
1033  
1034      echo $return;
1035  }
1036  
1037  /**
1038   * Gets the sites a user belongs to.
1039   *
1040   * @since 3.0.0
1041   * @since 4.7.0 Converted to use `get_sites()`.
1042   *
1043   * @global wpdb $wpdb WordPress database abstraction object.
1044   *
1045   * @param int  $user_id User ID
1046   * @param bool $all     Whether to retrieve all sites, or only sites that are not
1047   *                      marked as deleted, archived, or spam.
1048   * @return object[] A list of the user's sites. An empty array if the user doesn't exist
1049   *                  or belongs to no sites.
1050   */
1051  function get_blogs_of_user( $user_id, $all = false ) {
1052      global $wpdb;
1053  
1054      $user_id = (int) $user_id;
1055  
1056      // Logged out users can't have sites.
1057      if ( empty( $user_id ) ) {
1058          return array();
1059      }
1060  
1061      /**
1062       * Filters the list of a user's sites before it is populated.
1063       *
1064       * Returning a non-null value from the filter will effectively short circuit
1065       * get_blogs_of_user(), returning that value instead.
1066       *
1067       * @since 4.6.0
1068       *
1069       * @param null|object[] $sites   An array of site objects of which the user is a member.
1070       * @param int           $user_id User ID.
1071       * @param bool          $all     Whether the returned array should contain all sites, including
1072       *                               those marked 'deleted', 'archived', or 'spam'. Default false.
1073       */
1074      $sites = apply_filters( 'pre_get_blogs_of_user', null, $user_id, $all );
1075  
1076      if ( null !== $sites ) {
1077          return $sites;
1078      }
1079  
1080      $keys = get_user_meta( $user_id );
1081      if ( empty( $keys ) ) {
1082          return array();
1083      }
1084  
1085      if ( ! is_multisite() ) {
1086          $site_id                        = get_current_blog_id();
1087          $sites                          = array( $site_id => new stdClass() );
1088          $sites[ $site_id ]->userblog_id = $site_id;
1089          $sites[ $site_id ]->blogname    = get_option( 'blogname' );
1090          $sites[ $site_id ]->domain      = '';
1091          $sites[ $site_id ]->path        = '';
1092          $sites[ $site_id ]->site_id     = 1;
1093          $sites[ $site_id ]->siteurl     = get_option( 'siteurl' );
1094          $sites[ $site_id ]->archived    = 0;
1095          $sites[ $site_id ]->spam        = 0;
1096          $sites[ $site_id ]->deleted     = 0;
1097          return $sites;
1098      }
1099  
1100      $site_ids = array();
1101  
1102      if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
1103          $site_ids[] = 1;
1104          unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
1105      }
1106  
1107      $keys = array_keys( $keys );
1108  
1109      foreach ( $keys as $key ) {
1110          if ( ! str_ends_with( $key, 'capabilities' ) ) {
1111              continue;
1112          }
1113          if ( $wpdb->base_prefix && ! str_starts_with( $key, $wpdb->base_prefix ) ) {
1114              continue;
1115          }
1116          $site_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
1117          if ( ! is_numeric( $site_id ) ) {
1118              continue;
1119          }
1120  
1121          $site_ids[] = (int) $site_id;
1122      }
1123  
1124      $sites = array();
1125  
1126      if ( ! empty( $site_ids ) ) {
1127          $args = array(
1128              'number'   => '',
1129              'site__in' => $site_ids,
1130          );
1131          if ( ! $all ) {
1132              $args['archived'] = 0;
1133              $args['spam']     = 0;
1134              $args['deleted']  = 0;
1135          }
1136  
1137          $_sites = get_sites( $args );
1138  
1139          foreach ( $_sites as $site ) {
1140              $sites[ $site->id ] = (object) array(
1141                  'userblog_id' => $site->id,
1142                  'blogname'    => $site->blogname,
1143                  'domain'      => $site->domain,
1144                  'path'        => $site->path,
1145                  'site_id'     => $site->network_id,
1146                  'siteurl'     => $site->siteurl,
1147                  'archived'    => $site->archived,
1148                  'mature'      => $site->mature,
1149                  'spam'        => $site->spam,
1150                  'deleted'     => $site->deleted,
1151              );
1152          }
1153      }
1154  
1155      /**
1156       * Filters the list of sites a user belongs to.
1157       *
1158       * @since MU (3.0.0)
1159       *
1160       * @param object[] $sites   An array of site objects belonging to the user.
1161       * @param int      $user_id User ID.
1162       * @param bool     $all     Whether the returned sites array should contain all sites, including
1163       *                          those flagged for deletion, archived, or marked as spam.
1164       */
1165      return apply_filters( 'get_blogs_of_user', $sites, $user_id, $all );
1166  }
1167  
1168  /**
1169   * Finds out whether a user is a member of a given blog.
1170   *
1171   * @since MU (3.0.0)
1172   * @since 7.1.0 Introduced the {@see 'is_user_member_of_blog'} filter.
1173   *
1174   * @global wpdb $wpdb WordPress database abstraction object.
1175   *
1176   * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
1177   * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
1178   * @return bool
1179   */
1180  function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
1181      global $wpdb;
1182  
1183      $user_id = (int) $user_id;
1184      $blog_id = (int) $blog_id;
1185  
1186      if ( empty( $user_id ) ) {
1187          $user_id = get_current_user_id();
1188      }
1189  
1190      /*
1191       * Technically not needed, but does save calls to get_site() and get_user_meta()
1192       * in the event that the function is called when a user isn't logged in.
1193       */
1194      if ( empty( $user_id ) ) {
1195          return false;
1196      } else {
1197          $user = get_userdata( $user_id );
1198          if ( ! $user instanceof WP_User ) {
1199              return false;
1200          }
1201      }
1202  
1203      if ( ! is_multisite() ) {
1204          return true;
1205      }
1206  
1207      if ( empty( $blog_id ) ) {
1208          $blog_id = get_current_blog_id();
1209      }
1210  
1211      $blog = get_site( $blog_id );
1212  
1213      if ( ! $blog || ! isset( $blog->domain ) || $blog->archived || $blog->spam || $blog->deleted ) {
1214          return false;
1215      }
1216  
1217      if ( 1 === $blog_id ) {
1218          $capabilities_key = $wpdb->base_prefix . 'capabilities';
1219      } else {
1220          $capabilities_key = $wpdb->base_prefix . $blog_id . '_capabilities';
1221      }
1222  
1223      $has_cap   = get_user_meta( $user_id, $capabilities_key, true );
1224      $is_member = is_array( $has_cap );
1225  
1226      /**
1227       * Filters whether the user is a member of a given blog.
1228       *
1229       * This filter only runs when the user and blog have both been resolved
1230       * to valid records on a multisite installation; it is not invoked for
1231       * logged-out requests, unknown users, or archived/spammed/deleted sites.
1232       *
1233       * @since 7.1.0
1234       *
1235       * @param bool $is_member Whether the user is a member of the blog.
1236       * @param int  $user_id   The user ID being checked.
1237       * @param int  $blog_id   The blog ID being checked.
1238       */
1239      return (bool) apply_filters( 'is_user_member_of_blog', $is_member, $user_id, $blog_id );
1240  }
1241  
1242  /**
1243   * Adds meta data to a user.
1244   *
1245   * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input.
1246   *
1247   * @since 3.0.0
1248   *
1249   * @param int    $user_id    User ID.
1250   * @param string $meta_key   Metadata name.
1251   * @param mixed  $meta_value Metadata value. Arrays and objects are stored as serialized data and
1252   *                           will be returned as the same type when retrieved. Other data types will
1253   *                           be stored as strings in the database:
1254   *                           - false is stored and retrieved as an empty string ('')
1255   *                           - true is stored and retrieved as '1'
1256   *                           - numbers (both integer and float) are stored and retrieved as strings
1257   *                           Must be serializable if non-scalar.
1258   * @param bool   $unique     Optional. Whether the same key should not be added.
1259   *                           Default false.
1260   * @return int|false Meta ID on success, false on failure.
1261   */
1262  function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
1263      return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
1264  }
1265  
1266  /**
1267   * Removes metadata matching criteria from a user.
1268   *
1269   * You can match based on the key, or key and value. Removing based on key and
1270   * value, will keep from removing duplicate metadata with the same key. It also
1271   * allows removing all metadata matching key, if needed.
1272   *
1273   * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input.
1274   *
1275   * @since 3.0.0
1276   *
1277   * @link https://developer.wordpress.org/reference/functions/delete_user_meta/
1278   *
1279   * @param int    $user_id    User ID
1280   * @param string $meta_key   Metadata name.
1281   * @param mixed  $meta_value Optional. Metadata value. If provided,
1282   *                           rows will only be removed that match the value.
1283   *                           Must be serializable if non-scalar. Default empty.
1284   * @return bool True on success, false on failure.
1285   *
1286   * @phpstan-param positive-int $user_id
1287   */
1288  function delete_user_meta( $user_id, $meta_key, $meta_value = '' ) {
1289      return delete_metadata( 'user', $user_id, $meta_key, $meta_value );
1290  }
1291  
1292  /**
1293   * Retrieves user meta field for a user.
1294   *
1295   * @since 3.0.0
1296   *
1297   * @link https://developer.wordpress.org/reference/functions/get_user_meta/
1298   *
1299   * @param int    $user_id User ID.
1300   * @param string $key     Optional. The meta key to retrieve. By default,
1301   *                        returns data for all keys.
1302   * @param bool   $single  Optional. Whether to return a single value.
1303   *                        This parameter has no effect if `$key` is not specified.
1304   *                        Default false.
1305   * @return mixed An array of values if `$single` is false.
1306   *               The value of meta data field if `$single` is true.
1307   *               False for an invalid `$user_id` (non-numeric, zero, or negative value).
1308   *               An empty array if a valid but non-existing user ID is passed and `$single` is false.
1309   *               An empty string if a valid but non-existing user ID is passed and `$single` is true.
1310   *               Note: Non-serialized values are returned as strings:
1311   *               - false values are returned as empty strings ('')
1312   *               - true values are returned as '1'
1313   *               - numbers (both integer and float) are returned as strings
1314   *               Arrays and objects retain their original type.
1315   *               These conversions apply to stored values. A default value registered
1316   *               with {@see register_meta()} is never stored, so it is returned with
1317   *               the type it was registered with, which may be an integer, float, or
1318   *               boolean.
1319   *
1320   * @phpstan-return (
1321   *     $key is ''|'0'
1322   *         ? array<array-key, list<string>>|false
1323   *         : ( $single is true
1324   *             ? mixed
1325   *             : list<mixed>|false )
1326   * )
1327   */
1328  function get_user_meta( $user_id, $key = '', $single = false ) {
1329      return get_metadata( 'user', $user_id, $key, $single );
1330  }
1331  
1332  /**
1333   * Updates user meta field based on user ID.
1334   *
1335   * Use the $prev_value parameter to differentiate between meta fields with the
1336   * same key and user ID.
1337   *
1338   * If the meta field for the user does not exist, it will be added.
1339   *
1340   * For historical reasons both the meta key and the meta value are expected to be "slashed" (slashes escaped) on input.
1341   *
1342   * @since 3.0.0
1343   *
1344   * @link https://developer.wordpress.org/reference/functions/update_user_meta/
1345   *
1346   * @param int    $user_id    User ID.
1347   * @param string $meta_key   Metadata key.
1348   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
1349   * @param mixed  $prev_value Optional. Previous value to check before updating.
1350   *                           If specified, only update existing metadata entries with
1351   *                           this value. Otherwise, update all entries. Default empty.
1352   * @return int|bool Meta ID if the key didn't exist, true on successful update,
1353   *                  false on failure or if the value passed to the function
1354   *                  is the same as the one that is already in the database.
1355   */
1356  function update_user_meta( $user_id, $meta_key, $meta_value, $prev_value = '' ) {
1357      return update_metadata( 'user', $user_id, $meta_key, $meta_value, $prev_value );
1358  }
1359  
1360  /**
1361   * Counts number of users who have each of the user roles.
1362   *
1363   * Assumes there are neither duplicated nor orphaned capabilities meta_values.
1364   * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
1365   * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
1366   * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
1367   *
1368   * @since 3.0.0
1369   * @since 4.4.0 The number of users with no role is now included in the `none` element.
1370   * @since 4.9.0 The `$site_id` parameter was added to support multisite.
1371   *
1372   * @global wpdb $wpdb WordPress database abstraction object.
1373   *
1374   * @param string   $strategy Optional. The computational strategy to use when counting the users.
1375   *                           Accepts either 'time' or 'memory'. Default 'time'.
1376   * @param int|null $site_id  Optional. The site ID to count users for. Defaults to the current site.
1377   * @return array {
1378   *     User counts.
1379   *
1380   *     @type int   $total_users Total number of users on the site.
1381   *     @type int[] $avail_roles Array of user counts keyed by user role.
1382   * }
1383   */
1384  function count_users( $strategy = 'time', $site_id = null ) {
1385      global $wpdb;
1386  
1387      // Initialize.
1388      if ( ! $site_id ) {
1389          $site_id = get_current_blog_id();
1390      }
1391  
1392      /**
1393       * Filters the user count before queries are run.
1394       *
1395       * Return a non-null value to cause count_users() to return early.
1396       *
1397       * @since 5.1.0
1398       *
1399       * @param null|array $result   The value to return instead. Default null to continue with the query.
1400       * @param string     $strategy Optional. The computational strategy to use when counting the users.
1401       *                             Accepts either 'time' or 'memory'. Default 'time'.
1402       * @param int        $site_id  The site ID to count users for.
1403       */
1404      $pre = apply_filters( 'pre_count_users', null, $strategy, $site_id );
1405  
1406      if ( null !== $pre ) {
1407          return $pre;
1408      }
1409  
1410      $blog_prefix = $wpdb->get_blog_prefix( $site_id );
1411      $result      = array();
1412  
1413      if ( 'time' === $strategy ) {
1414          if ( is_multisite() && get_current_blog_id() !== $site_id ) {
1415              switch_to_blog( $site_id );
1416              $avail_roles = wp_roles()->get_names();
1417              restore_current_blog();
1418          } else {
1419              $avail_roles = wp_roles()->get_names();
1420          }
1421  
1422          // Build a CPU-intensive query that will return concise information.
1423          $select_count = array();
1424          foreach ( $avail_roles as $this_role => $name ) {
1425              $select_count[] = $wpdb->prepare( 'COUNT(NULLIF(`meta_value` LIKE %s, false))', '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%' );
1426          }
1427          $select_count[] = "COUNT(NULLIF(`meta_value` = 'a:0:{}', false))";
1428          $select_count   = implode( ', ', $select_count );
1429  
1430          // Add the meta_value index to the selection list, then run the query.
1431          $row = $wpdb->get_row(
1432              "
1433              SELECT {$select_count}, COUNT(*)
1434              FROM {$wpdb->usermeta}
1435              INNER JOIN {$wpdb->users} ON user_id = ID
1436              WHERE meta_key = '{$blog_prefix}capabilities'
1437          ",
1438              ARRAY_N
1439          );
1440  
1441          // Run the previous loop again to associate results with role names.
1442          $col         = 0;
1443          $role_counts = array();
1444          foreach ( $avail_roles as $this_role => $name ) {
1445              $count = (int) $row[ $col++ ];
1446              if ( $count > 0 ) {
1447                  $role_counts[ $this_role ] = $count;
1448              }
1449          }
1450  
1451          $role_counts['none'] = (int) $row[ $col++ ];
1452  
1453          // Get the meta_value index from the end of the result set.
1454          $total_users = (int) $row[ $col ];
1455  
1456          $result['total_users'] = $total_users;
1457          $result['avail_roles'] =& $role_counts;
1458      } else {
1459          $avail_roles = array(
1460              'none' => 0,
1461          );
1462  
1463          $users_of_blog = $wpdb->get_col(
1464              "
1465              SELECT meta_value
1466              FROM {$wpdb->usermeta}
1467              INNER JOIN {$wpdb->users} ON user_id = ID
1468              WHERE meta_key = '{$blog_prefix}capabilities'
1469          "
1470          );
1471  
1472          foreach ( $users_of_blog as $caps_meta ) {
1473              $b_roles = maybe_unserialize( $caps_meta );
1474              if ( ! is_array( $b_roles ) ) {
1475                  continue;
1476              }
1477              if ( empty( $b_roles ) ) {
1478                  ++$avail_roles['none'];
1479              }
1480              foreach ( $b_roles as $b_role => $val ) {
1481                  if ( isset( $avail_roles[ $b_role ] ) ) {
1482                      ++$avail_roles[ $b_role ];
1483                  } else {
1484                      $avail_roles[ $b_role ] = 1;
1485                  }
1486              }
1487          }
1488  
1489          $result['total_users'] = count( $users_of_blog );
1490          $result['avail_roles'] =& $avail_roles;
1491      }
1492  
1493      return $result;
1494  }
1495  
1496  /**
1497   * Returns the number of active users in your installation.
1498   *
1499   * Note that on a large site the count may be cached and only updated twice daily.
1500   *
1501   * @since MU (3.0.0)
1502   * @since 4.8.0 The `$network_id` parameter has been added.
1503   * @since 6.0.0 Moved to wp-includes/user.php.
1504   *
1505   * @param int|null $network_id ID of the network. Defaults to the current network.
1506   * @return int Number of active users on the network.
1507   */
1508  function get_user_count( $network_id = null ) {
1509      if ( ! is_multisite() && null !== $network_id ) {
1510          _doing_it_wrong(
1511              __FUNCTION__,
1512              sprintf(
1513                  /* translators: %s: $network_id */
1514                  __( 'Unable to pass %s if not using multisite.' ),
1515                  '<code>$network_id</code>'
1516              ),
1517              '6.0.0'
1518          );
1519      }
1520  
1521      return (int) get_network_option( $network_id, 'user_count', -1 );
1522  }
1523  
1524  /**
1525   * Updates the total count of users on the site if live user counting is enabled.
1526   *
1527   * @since 6.0.0
1528   *
1529   * @param int|null $network_id ID of the network. Defaults to the current network.
1530   * @return bool Whether the update was successful.
1531   */
1532  function wp_maybe_update_user_counts( $network_id = null ) {
1533      if ( ! is_multisite() && null !== $network_id ) {
1534          _doing_it_wrong(
1535              __FUNCTION__,
1536              sprintf(
1537                  /* translators: %s: $network_id */
1538                  __( 'Unable to pass %s if not using multisite.' ),
1539                  '<code>$network_id</code>'
1540              ),
1541              '6.0.0'
1542          );
1543      }
1544  
1545      $is_small_network = ! wp_is_large_user_count( $network_id );
1546      /** This filter is documented in wp-includes/ms-functions.php */
1547      if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'users' ) ) {
1548          return false;
1549      }
1550  
1551      return wp_update_user_counts( $network_id );
1552  }
1553  
1554  /**
1555   * Updates the total count of users on the site.
1556   *
1557   * @global wpdb $wpdb WordPress database abstraction object.
1558   * @since 6.0.0
1559   *
1560   * @param int|null $network_id ID of the network. Defaults to the current network.
1561   * @return bool Whether the update was successful.
1562   */
1563  function wp_update_user_counts( $network_id = null ) {
1564      global $wpdb;
1565  
1566      if ( ! is_multisite() && null !== $network_id ) {
1567          _doing_it_wrong(
1568              __FUNCTION__,
1569              sprintf(
1570                  /* translators: %s: $network_id */
1571                  __( 'Unable to pass %s if not using multisite.' ),
1572                  '<code>$network_id</code>'
1573              ),
1574              '6.0.0'
1575          );
1576      }
1577  
1578      $query = "SELECT COUNT(ID) as c FROM $wpdb->users";
1579      if ( is_multisite() ) {
1580          $query .= " WHERE spam = '0' AND deleted = '0'";
1581      }
1582  
1583      $count = $wpdb->get_var( $query );
1584  
1585      return update_network_option( $network_id, 'user_count', $count );
1586  }
1587  
1588  /**
1589   * Schedules a recurring recalculation of the total count of users.
1590   *
1591   * @since 6.0.0
1592   */
1593  function wp_schedule_update_user_counts() {
1594      if ( ! is_main_site() ) {
1595          return;
1596      }
1597  
1598      if ( ! wp_next_scheduled( 'wp_update_user_counts' ) && ! wp_installing() ) {
1599          wp_schedule_event( time(), 'twicedaily', 'wp_update_user_counts' );
1600      }
1601  }
1602  
1603  /**
1604   * Determines whether the site has a large number of users.
1605   *
1606   * The default criteria for a large site is more than 10,000 users.
1607   *
1608   * @since 6.0.0
1609   *
1610   * @param int|null $network_id ID of the network. Defaults to the current network.
1611   * @return bool Whether the site has a large number of users.
1612   */
1613  function wp_is_large_user_count( $network_id = null ) {
1614      if ( ! is_multisite() && null !== $network_id ) {
1615          _doing_it_wrong(
1616              __FUNCTION__,
1617              sprintf(
1618                  /* translators: %s: $network_id */
1619                  __( 'Unable to pass %s if not using multisite.' ),
1620                  '<code>$network_id</code>'
1621              ),
1622              '6.0.0'
1623          );
1624      }
1625  
1626      $count = get_user_count( $network_id );
1627  
1628      /**
1629       * Filters whether the site is considered large, based on its number of users.
1630       *
1631       * @since 6.0.0
1632       *
1633       * @param bool     $is_large_user_count Whether the site has a large number of users.
1634       * @param int      $count               The total number of users.
1635       * @param int|null $network_id          ID of the network. `null` represents the current network.
1636       */
1637      return apply_filters( 'wp_is_large_user_count', $count > 10000, $count, $network_id );
1638  }
1639  
1640  //
1641  // Private helper functions.
1642  //
1643  
1644  /**
1645   * Sets up global user vars.
1646   *
1647   * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
1648   *
1649   * @since 2.0.4
1650   *
1651   * @global string  $user_login    The user username for logging in
1652   * @global WP_User $userdata      User data.
1653   * @global int     $user_level    The level of the user
1654   * @global int     $user_ID       The ID of the user
1655   * @global string  $user_email    The email address of the user
1656   * @global string  $user_url      The url in the user's profile
1657   * @global string  $user_identity The display name of the user
1658   *
1659   * @param int $for_user_id Optional. User ID to set up global data. Default 0.
1660   */
1661  function setup_userdata( $for_user_id = 0 ) {
1662      global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
1663  
1664      if ( ! $for_user_id ) {
1665          $for_user_id = get_current_user_id();
1666      }
1667      $user = get_userdata( $for_user_id );
1668  
1669      if ( ! $user ) {
1670          $user_ID       = 0;
1671          $user_level    = 0;
1672          $userdata      = null;
1673          $user_login    = '';
1674          $user_email    = '';
1675          $user_url      = '';
1676          $user_identity = '';
1677          return;
1678      }
1679  
1680      $user_ID       = (int) $user->ID;
1681      $user_level    = (int) $user->user_level;
1682      $userdata      = $user;
1683      $user_login    = $user->user_login;
1684      $user_email    = $user->user_email;
1685      $user_url      = $user->user_url;
1686      $user_identity = $user->display_name;
1687  }
1688  
1689  /**
1690   * Creates dropdown HTML content of users.
1691   *
1692   * The content can either be displayed, which it is by default, or retrieved by
1693   * setting the 'echo' argument to false. The 'include' and 'exclude' arguments
1694   * are optional; if they are not specified, all users will be displayed. Only one
1695   * can be used in a single call, either 'include' or 'exclude', but not both.
1696   *
1697   * @since 2.3.0
1698   * @since 4.5.0 Added the 'display_name_with_login' value for 'show'.
1699   * @since 4.7.0 Added the 'role', 'role__in', and 'role__not_in' parameters.
1700   * @since 5.9.0 Added the 'capability', 'capability__in', and 'capability__not_in' parameters.
1701   *              Deprecated the 'who' parameter.
1702   *
1703   * @param array|string $args {
1704   *     Optional. Array or string of arguments to generate a drop-down of users.
1705   *     See WP_User_Query::prepare_query() for additional available arguments.
1706   *
1707   *     @type string          $show_option_all         Text to show as the drop-down default (all).
1708   *                                                    Default empty.
1709   *     @type string          $show_option_none        Text to show as the drop-down default when no
1710   *                                                    users were found. Default empty.
1711   *     @type int|string      $option_none_value       Value to use for `$show_option_none` when no users
1712   *                                                    were found. Default -1.
1713   *     @type string          $hide_if_only_one_author Whether to skip generating the drop-down
1714   *                                                    if only one user was found. Default empty.
1715   *     @type string          $orderby                 Field to order found users by. Accepts user fields.
1716   *                                                    Default 'display_name'.
1717   *     @type string          $order                   Whether to order users in ascending or descending
1718   *                                                    order. Accepts 'ASC' (ascending) or 'DESC' (descending).
1719   *                                                    Default 'ASC'.
1720   *     @type int[]|string    $include                 Array or comma-separated list of user IDs to include.
1721   *                                                    Default empty.
1722   *     @type int[]|string    $exclude                 Array or comma-separated list of user IDs to exclude.
1723   *                                                    Default empty.
1724   *     @type bool|int        $multi                   Whether to skip the ID attribute on the 'select' element.
1725   *                                                    Accepts 1|true or 0|false. Default 0|false.
1726   *     @type string          $show                    User data to display. If the selected item is empty
1727   *                                                    then the 'user_login' will be displayed in parentheses.
1728   *                                                    Accepts any user field, or 'display_name_with_login' to show
1729   *                                                    the display name with user_login in parentheses.
1730   *                                                    Default 'display_name'.
1731   *     @type int|bool        $echo                    Whether to echo or return the drop-down. Accepts 1|true (echo)
1732   *                                                    or 0|false (return). Default 1|true.
1733   *     @type int             $selected                Which user ID should be selected. Default 0.
1734   *     @type bool            $include_selected        Whether to always include the selected user ID in the drop-
1735   *                                                    down. Default false.
1736   *     @type string          $name                    Name attribute of select element. Default 'user'.
1737   *     @type string          $id                      ID attribute of the select element. Default is the value of `$name`.
1738   *     @type string          $class                   Class attribute of the select element. Default empty.
1739   *     @type int             $blog_id                 ID of blog (Multisite only). Default is ID of the current blog.
1740   *     @type string          $who                     Deprecated, use `$capability` instead.
1741   *                                                    Which type of users to query. Accepts only an empty string or
1742   *                                                    'authors'. Default empty (all users).
1743   *     @type string|string[] $role                    An array or a comma-separated list of role names that users
1744   *                                                    must match to be included in results. Note that this is
1745   *                                                    an inclusive list: users must match *each* role. Default empty.
1746   *     @type string[]        $role__in                An array of role names. Matched users must have at least one
1747   *                                                    of these roles. Default empty array.
1748   *     @type string[]        $role__not_in            An array of role names to exclude. Users matching one or more
1749   *                                                    of these roles will not be included in results. Default empty array.
1750   *     @type string|string[] $capability              An array or a comma-separated list of capability names that users
1751   *                                                    must match to be included in results. Note that this is
1752   *                                                    an inclusive list: users must match *each* capability.
1753   *                                                    Does NOT work for capabilities not in the database or filtered
1754   *                                                    via {@see 'map_meta_cap'}. Default empty.
1755   *     @type string[]        $capability__in          An array of capability names. Matched users must have at least one
1756   *                                                    of these capabilities.
1757   *                                                    Does NOT work for capabilities not in the database or filtered
1758   *                                                    via {@see 'map_meta_cap'}. Default empty array.
1759   *     @type string[]        $capability__not_in      An array of capability names to exclude. Users matching one or more
1760   *                                                    of these capabilities will not be included in results.
1761   *                                                    Does NOT work for capabilities not in the database or filtered
1762   *                                                    via {@see 'map_meta_cap'}. Default empty array.
1763   * }
1764   * @return string HTML dropdown list of users.
1765   */
1766  function wp_dropdown_users( $args = '' ) {
1767      $defaults = array(
1768          'show_option_all'         => '',
1769          'show_option_none'        => '',
1770          'hide_if_only_one_author' => '',
1771          'orderby'                 => 'display_name',
1772          'order'                   => 'ASC',
1773          'include'                 => '',
1774          'exclude'                 => '',
1775          'multi'                   => 0,
1776          'show'                    => 'display_name',
1777          'echo'                    => 1,
1778          'selected'                => 0,
1779          'name'                    => 'user',
1780          'class'                   => '',
1781          'id'                      => '',
1782          'blog_id'                 => get_current_blog_id(),
1783          'who'                     => '',
1784          'include_selected'        => false,
1785          'option_none_value'       => -1,
1786          'role'                    => '',
1787          'role__in'                => array(),
1788          'role__not_in'            => array(),
1789          'capability'              => '',
1790          'capability__in'          => array(),
1791          'capability__not_in'      => array(),
1792      );
1793  
1794      $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
1795  
1796      $parsed_args = wp_parse_args( $args, $defaults );
1797  
1798      $query_args = wp_array_slice_assoc(
1799          $parsed_args,
1800          array(
1801              'blog_id',
1802              'include',
1803              'exclude',
1804              'orderby',
1805              'order',
1806              'who',
1807              'role',
1808              'role__in',
1809              'role__not_in',
1810              'capability',
1811              'capability__in',
1812              'capability__not_in',
1813          )
1814      );
1815  
1816      $fields = array( 'ID', 'user_login' );
1817  
1818      $show = ! empty( $parsed_args['show'] ) ? $parsed_args['show'] : 'display_name';
1819      if ( 'display_name_with_login' === $show ) {
1820          $fields[] = 'display_name';
1821      } else {
1822          $fields[] = $show;
1823      }
1824  
1825      $query_args['fields'] = $fields;
1826  
1827      $show_option_all   = $parsed_args['show_option_all'];
1828      $show_option_none  = $parsed_args['show_option_none'];
1829      $option_none_value = $parsed_args['option_none_value'];
1830  
1831      /**
1832       * Filters the query arguments for the list of users in the dropdown.
1833       *
1834       * @since 4.4.0
1835       *
1836       * @param array $query_args  The query arguments for get_users().
1837       * @param array $parsed_args The arguments passed to wp_dropdown_users() combined with the defaults.
1838       */
1839      $query_args = apply_filters( 'wp_dropdown_users_args', $query_args, $parsed_args );
1840  
1841      $users = get_users( $query_args );
1842  
1843      $output = '';
1844      if ( ! empty( $users ) && ( empty( $parsed_args['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
1845          $name = esc_attr( $parsed_args['name'] );
1846          if ( $parsed_args['multi'] && ! $parsed_args['id'] ) {
1847              $id = '';
1848          } else {
1849              $id = $parsed_args['id'] ? " id='" . esc_attr( $parsed_args['id'] ) . "'" : " id='$name'";
1850          }
1851          $output = "<select name='{$name}'{$id} class='" . $parsed_args['class'] . "'>\n";
1852  
1853          if ( $show_option_all ) {
1854              $output .= "\t<option value='0'>$show_option_all</option>\n";
1855          }
1856  
1857          if ( $show_option_none ) {
1858              $_selected = selected( $option_none_value, $parsed_args['selected'], false );
1859              $output   .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
1860          }
1861  
1862          if ( $parsed_args['include_selected'] && ( $parsed_args['selected'] > 0 ) ) {
1863              $found_selected          = false;
1864              $parsed_args['selected'] = (int) $parsed_args['selected'];
1865  
1866              foreach ( (array) $users as $user ) {
1867                  $user->ID = (int) $user->ID;
1868                  if ( $user->ID === $parsed_args['selected'] ) {
1869                      $found_selected = true;
1870                  }
1871              }
1872  
1873              if ( ! $found_selected ) {
1874                  $selected_user = get_userdata( $parsed_args['selected'] );
1875                  if ( $selected_user ) {
1876                      $users[] = $selected_user;
1877                  }
1878              }
1879          }
1880  
1881          foreach ( (array) $users as $user ) {
1882              if ( 'display_name_with_login' === $show ) {
1883                  /* translators: 1: User's display name, 2: User login. */
1884                  $display = sprintf( _x( '%1$s (%2$s)', 'user dropdown' ), $user->display_name, $user->user_login );
1885              } elseif ( ! empty( $user->$show ) ) {
1886                  $display = $user->$show;
1887              } else {
1888                  $display = '(' . $user->user_login . ')';
1889              }
1890  
1891              $_selected = selected( $user->ID, $parsed_args['selected'], false );
1892              $output   .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
1893          }
1894  
1895          $output .= '</select>';
1896      }
1897  
1898      /**
1899       * Filters the wp_dropdown_users() HTML output.
1900       *
1901       * @since 2.3.0
1902       *
1903       * @param string $output HTML output generated by wp_dropdown_users().
1904       */
1905      $html = apply_filters( 'wp_dropdown_users', $output );
1906  
1907      if ( $parsed_args['echo'] ) {
1908          echo $html;
1909      }
1910      return $html;
1911  }
1912  
1913  /**
1914   * Sanitizes user field based on context.
1915   *
1916   * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1917   * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1918   * when calling filters.
1919   *
1920   * @since 2.3.0
1921   *
1922   * @param string $field   The user Object field name.
1923   * @param mixed  $value   The user Object value.
1924   * @param int    $user_id User ID.
1925   * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
1926   *                        'attribute' and 'js'.
1927   * @return mixed Sanitized value.
1928   */
1929  function sanitize_user_field( $field, $value, $user_id, $context ) {
1930      $int_fields = array( 'ID' );
1931      if ( in_array( $field, $int_fields, true ) ) {
1932          $value = (int) $value;
1933      }
1934  
1935      if ( 'raw' === $context ) {
1936          return $value;
1937      }
1938  
1939      if ( ! is_string( $value ) && ! is_numeric( $value ) ) {
1940          return $value;
1941      }
1942  
1943      $prefixed = str_contains( $field, 'user_' );
1944  
1945      if ( 'edit' === $context ) {
1946          if ( $prefixed ) {
1947  
1948              /** This filter is documented in wp-includes/post.php */
1949              $value = apply_filters( "edit_{$field}", $value, $user_id );
1950          } else {
1951  
1952              /**
1953               * Filters a user field value in the 'edit' context.
1954               *
1955               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1956               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1957               *
1958               * @since 2.9.0
1959               *
1960               * @param mixed $value   Value of the prefixed user field.
1961               * @param int   $user_id User ID.
1962               */
1963              $value = apply_filters( "edit_user_{$field}", $value, $user_id );
1964          }
1965  
1966          if ( 'description' === $field ) {
1967              $value = esc_html( $value ); // textarea_escaped?
1968          } else {
1969              $value = esc_attr( $value );
1970          }
1971      } elseif ( 'db' === $context ) {
1972          if ( $prefixed ) {
1973              /** This filter is documented in wp-includes/post.php */
1974              $value = apply_filters( "pre_{$field}", $value );
1975          } else {
1976  
1977              /**
1978               * Filters the value of a user field in the 'db' context.
1979               *
1980               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1981               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1982               *
1983               * @since 2.9.0
1984               *
1985               * @param mixed $value Value of the prefixed user field.
1986               */
1987              $value = apply_filters( "pre_user_{$field}", $value );
1988          }
1989      } else {
1990          // Use display filters by default.
1991          if ( $prefixed ) {
1992  
1993              /** This filter is documented in wp-includes/post.php */
1994              $value = apply_filters( "{$field}", $value, $user_id, $context );
1995          } else {
1996  
1997              /**
1998               * Filters the value of a user field in a standard context.
1999               *
2000               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
2001               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
2002               *
2003               * @since 2.9.0
2004               *
2005               * @param mixed  $value   The user object value to sanitize.
2006               * @param int    $user_id User ID.
2007               * @param string $context The context to filter within.
2008               */
2009              $value = apply_filters( "user_{$field}", $value, $user_id, $context );
2010          }
2011      }
2012  
2013      if ( 'user_url' === $field ) {
2014          $value = esc_url( $value );
2015      }
2016  
2017      if ( 'attribute' === $context ) {
2018          $value = esc_attr( $value );
2019      } elseif ( 'js' === $context ) {
2020          $value = esc_js( $value );
2021      }
2022  
2023      // Restore the type for integer fields after esc_attr().
2024      if ( in_array( $field, $int_fields, true ) ) {
2025          $value = (int) $value;
2026      }
2027  
2028      return $value;
2029  }
2030  
2031  /**
2032   * Updates all user caches.
2033   *
2034   * @since 3.0.0
2035   *
2036   * @param object|WP_User $user User object or database row to be cached
2037   * @return void|false Void on success, false on failure.
2038   */
2039  function update_user_caches( $user ) {
2040      if ( $user instanceof WP_User ) {
2041          if ( ! $user->exists() ) {
2042              return false;
2043          }
2044  
2045          $user = $user->data;
2046      }
2047  
2048      wp_cache_add( $user->ID, $user, 'users' );
2049      wp_cache_add( $user->user_login, $user->ID, 'userlogins' );
2050      wp_cache_add( $user->user_nicename, $user->ID, 'userslugs' );
2051  
2052      if ( ! empty( $user->user_email ) ) {
2053          wp_cache_add( $user->user_email, $user->ID, 'useremail' );
2054      }
2055  }
2056  
2057  /**
2058   * Cleans all user caches.
2059   *
2060   * @since 3.0.0
2061   * @since 4.4.0 'clean_user_cache' action was added.
2062   * @since 6.2.0 User metadata caches are now cleared.
2063   *
2064   * @param WP_User|int $user User object or ID to be cleaned from the cache
2065   */
2066  function clean_user_cache( $user ) {
2067      if ( is_numeric( $user ) ) {
2068          $user = new WP_User( $user );
2069      }
2070  
2071      if ( ! $user->exists() ) {
2072          return;
2073      }
2074  
2075      wp_cache_delete( $user->ID, 'users' );
2076      wp_cache_delete( $user->user_login, 'userlogins' );
2077      wp_cache_delete( $user->user_nicename, 'userslugs' );
2078  
2079      if ( ! empty( $user->user_email ) ) {
2080          wp_cache_delete( $user->user_email, 'useremail' );
2081      }
2082  
2083      wp_cache_delete( $user->ID, 'user_meta' );
2084      wp_cache_set_users_last_changed();
2085  
2086      /**
2087       * Fires immediately after the given user's cache is cleaned.
2088       *
2089       * @since 4.4.0
2090       *
2091       * @param int     $user_id User ID.
2092       * @param WP_User $user    User object.
2093       */
2094      do_action( 'clean_user_cache', $user->ID, $user );
2095  }
2096  
2097  /**
2098   * Determines whether the given username exists.
2099   *
2100   * For more information on this and similar theme functions, check out
2101   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
2102   * Conditional Tags} article in the Theme Developer Handbook.
2103   *
2104   * @since 2.0.0
2105   *
2106   * @param string $username The username to check for existence.
2107   * @return int|false The user ID on success, false on failure.
2108   */
2109  function username_exists( $username ) {
2110      $user = get_user_by( 'login', $username );
2111      if ( $user ) {
2112          $user_id = $user->ID;
2113      } else {
2114          $user_id = false;
2115      }
2116  
2117      /**
2118       * Filters whether the given username exists.
2119       *
2120       * @since 4.9.0
2121       *
2122       * @param int|false $user_id  The user ID associated with the username,
2123       *                            or false if the username does not exist.
2124       * @param string    $username The username to check for existence.
2125       */
2126      return apply_filters( 'username_exists', $user_id, $username );
2127  }
2128  
2129  /**
2130   * Determines whether the given email exists.
2131   *
2132   * For more information on this and similar theme functions, check out
2133   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
2134   * Conditional Tags} article in the Theme Developer Handbook.
2135   *
2136   * @since 2.1.0
2137   *
2138   * @param string $email The email to check for existence.
2139   * @return int|false The user ID on success, false on failure.
2140   */
2141  function email_exists( $email ) {
2142      $user = get_user_by( 'email', $email );
2143      if ( $user ) {
2144          $user_id = $user->ID;
2145      } else {
2146          $user_id = false;
2147      }
2148  
2149      /**
2150       * Filters whether the given email exists.
2151       *
2152       * @since 5.6.0
2153       *
2154       * @param int|false $user_id The user ID associated with the email,
2155       *                           or false if the email does not exist.
2156       * @param string    $email   The email to check for existence.
2157       */
2158      return apply_filters( 'email_exists', $user_id, $email );
2159  }
2160  
2161  /**
2162   * Checks whether a username is valid.
2163   *
2164   * @since 2.0.1
2165   * @since 4.4.0 Empty sanitized usernames are now considered invalid.
2166   *
2167   * @param string $username Username.
2168   * @return bool Whether username given is valid.
2169   */
2170  function validate_username( $username ) {
2171      $sanitized = sanitize_user( $username, true );
2172      $valid     = ( $sanitized === $username && ! empty( $sanitized ) );
2173  
2174      /**
2175       * Filters whether the provided username is valid.
2176       *
2177       * @since 2.0.1
2178       *
2179       * @param bool   $valid    Whether given username is valid.
2180       * @param string $username Username to check.
2181       */
2182      return apply_filters( 'validate_username', $valid, $username );
2183  }
2184  
2185  /**
2186   * Inserts a user into the database.
2187   *
2188   * Most of the `$userdata` array fields have filters associated with the values. Exceptions are
2189   * 'ID', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl',
2190   * 'user_registered', 'user_activation_key', 'spam', and 'role'. The filters have the prefix
2191   * 'pre_user_' followed by the field name. An example using 'description' would have the filter
2192   * called 'pre_user_description' that can be hooked into.
2193   *
2194   * @since 2.0.0
2195   * @since 3.6.0 The `aim`, `jabber`, and `yim` fields were removed as default user contact
2196   *              methods for new installations. See wp_get_user_contact_methods().
2197   * @since 4.7.0 The `locale` field can be passed to `$userdata`.
2198   * @since 5.3.0 The `user_activation_key` field can be passed to `$userdata`.
2199   * @since 5.3.0 The `spam` field can be passed to `$userdata` (Multisite only).
2200   * @since 5.9.0 The `meta_input` field can be passed to `$userdata` to allow addition of user meta data.
2201   *
2202   * @global wpdb $wpdb WordPress database abstraction object.
2203   *
2204   * @param array|object|WP_User $userdata {
2205   *     An array, object, or WP_User object of user data arguments.
2206   *
2207   *     @type int    $ID                   User ID. If supplied, the user will be updated.
2208   *     @type string $user_pass            The plain-text user password for new users.
2209   *                                        Hashed password for existing users.
2210   *     @type string $user_login           The user's login username.
2211   *     @type string $user_nicename        The URL-friendly user name.
2212   *     @type string $user_url             The user URL.
2213   *     @type string $user_email           The user email address.
2214   *     @type string $display_name         The user's display name.
2215   *                                        Default is the user's username.
2216   *     @type string $nickname             The user's nickname.
2217   *                                        Default is the user's username.
2218   *     @type string $first_name           The user's first name. For new users, will be used
2219   *                                        to build the first part of the user's display name
2220   *                                        if `$display_name` is not specified.
2221   *     @type string $last_name            The user's last name. For new users, will be used
2222   *                                        to build the second part of the user's display name
2223   *                                        if `$display_name` is not specified.
2224   *     @type string $description          The user's biographical description.
2225   *     @type string $rich_editing         Whether to enable the rich-editor for the user.
2226   *                                        Accepts 'true' or 'false' as a string literal,
2227   *                                        not boolean. Default 'true'.
2228   *     @type string $syntax_highlighting  Whether to enable the rich code editor for the user.
2229   *                                        Accepts 'true' or 'false' as a string literal,
2230   *                                        not boolean. Default 'true'.
2231   *     @type string $comment_shortcuts    Whether to enable comment moderation keyboard
2232   *                                        shortcuts for the user. Accepts 'true' or 'false'
2233   *                                        as a string literal, not boolean. Default 'false'.
2234   *     @type string $admin_color          Admin color scheme for the user. Default 'modern'.
2235   *     @type bool   $use_ssl              Whether the user should always access the admin over
2236   *                                        https. Default false.
2237   *     @type string $user_registered      Date the user registered in UTC. Format is 'Y-m-d H:i:s'.
2238   *     @type string $user_activation_key  Password reset key. Default empty.
2239   *     @type bool   $spam                 Multisite only. Whether the user is marked as spam.
2240   *                                        Default false.
2241   *     @type string $show_admin_bar_front Whether to display the Admin Bar for the user
2242   *                                        on the site's front end. Accepts 'true' or 'false'
2243   *                                        as a string literal, not boolean. Default 'true'.
2244   *     @type string $role                 User's role.
2245   *     @type string $locale               User's locale. Default empty.
2246   *     @type array  $meta_input           Array of custom user meta values keyed by meta key.
2247   *                                        Default empty.
2248   * }
2249   * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
2250   *                      be created.
2251   */
2252  function wp_insert_user( $userdata ) {
2253      global $wpdb;
2254  
2255      if ( $userdata instanceof stdClass ) {
2256          $userdata = get_object_vars( $userdata );
2257      } elseif ( $userdata instanceof WP_User ) {
2258          $userdata = $userdata->to_array();
2259      } elseif ( $userdata instanceof Traversable ) {
2260          $userdata = iterator_to_array( $userdata );
2261      } elseif ( $userdata instanceof ArrayAccess ) {
2262          $userdata_obj = $userdata;
2263          $userdata     = array();
2264          foreach (
2265              array(
2266                  'ID',
2267                  'user_pass',
2268                  'user_login',
2269                  'user_nicename',
2270                  'user_url',
2271                  'user_email',
2272                  'display_name',
2273                  'nickname',
2274                  'first_name',
2275                  'last_name',
2276                  'description',
2277                  'rich_editing',
2278                  'syntax_highlighting',
2279                  'infinite_scrolling',
2280                  'comment_shortcuts',
2281                  'admin_color',
2282                  'use_ssl',
2283                  'user_registered',
2284                  'user_activation_key',
2285                  'spam',
2286                  'show_admin_bar_front',
2287                  'role',
2288                  'locale',
2289                  'meta_input',
2290              ) as $key
2291          ) {
2292              if ( isset( $userdata_obj[ $key ] ) ) {
2293                  $userdata[ $key ] = $userdata_obj[ $key ];
2294              }
2295          }
2296      } else {
2297          $userdata = (array) $userdata;
2298      }
2299  
2300      // Are we updating or creating?
2301      if ( ! empty( $userdata['ID'] ) ) {
2302          $user_id       = (int) $userdata['ID'];
2303          $update        = true;
2304          $old_user_data = get_userdata( $user_id );
2305  
2306          if ( ! $old_user_data ) {
2307              return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
2308          }
2309  
2310          // Slash current user email to compare it later with slashed new user email.
2311          $old_user_data->user_email = wp_slash( $old_user_data->user_email );
2312  
2313          // Hashed in wp_update_user(), plaintext if called directly.
2314          $user_pass = ! empty( $userdata['user_pass'] ) ? $userdata['user_pass'] : $old_user_data->user_pass;
2315      } else {
2316          $update = false;
2317  
2318          if ( empty( $userdata['user_pass'] ) ) {
2319              wp_trigger_error(
2320                  __FUNCTION__,
2321                  __( 'The user_pass field is required when creating a new user. The user will need to reset their password before logging in.' ),
2322                  E_USER_WARNING
2323              );
2324  
2325              // Set the password as an empty string to force the password reset flow.
2326              $userdata['user_pass'] = '';
2327          }
2328  
2329          // Hash the password.
2330          $user_pass = wp_hash_password( $userdata['user_pass'] );
2331      }
2332  
2333      $sanitized_user_login = sanitize_user( $userdata['user_login'] ?? '', true );
2334  
2335      /**
2336       * Filters a username after it has been sanitized.
2337       *
2338       * This filter is called before the user is created or updated.
2339       *
2340       * @since 2.0.3
2341       *
2342       * @param string $sanitized_user_login Username after it has been sanitized.
2343       */
2344      $pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
2345  
2346      // Remove any non-printable chars from the login string to see if we have ended up with an empty username.
2347      $user_login = trim( $pre_user_login );
2348  
2349      // user_login must be between 0 and 60 characters.
2350      if ( empty( $user_login ) ) {
2351          return new WP_Error( 'empty_user_login', __( 'Cannot create a user with an empty login name.' ) );
2352      } elseif ( mb_strlen( $user_login ) > 60 ) {
2353          return new WP_Error( 'user_login_too_long', __( 'Username may not be longer than 60 characters.' ) );
2354      }
2355  
2356      if ( ! $update && username_exists( $user_login ) ) {
2357          return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
2358      }
2359  
2360      /**
2361       * Filters the list of disallowed usernames.
2362       *
2363       * @since 4.4.0
2364       *
2365       * @param array $usernames Array of disallowed usernames.
2366       */
2367      $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
2368  
2369      if ( in_array( strtolower( $user_login ), array_map( 'strtolower', $illegal_logins ), true ) ) {
2370          return new WP_Error( 'invalid_username', __( 'Sorry, that username is not allowed.' ) );
2371      }
2372  
2373      /*
2374       * If a nicename is provided, remove unsafe user characters before using it.
2375       * Otherwise build a nicename from the user_login.
2376       */
2377      if ( ! empty( $userdata['user_nicename'] ) ) {
2378          $user_nicename = sanitize_user( $userdata['user_nicename'], true );
2379      } else {
2380          $user_nicename = mb_substr( $user_login, 0, 50 );
2381      }
2382  
2383      $user_nicename = sanitize_title( $user_nicename );
2384  
2385      /**
2386       * Filters a user's nicename before the user is created or updated.
2387       *
2388       * @since 2.0.3
2389       *
2390       * @param string $user_nicename The user's nicename.
2391       */
2392      $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
2393  
2394      // Check if the sanitized nicename is empty.
2395      if ( empty( $user_nicename ) ) {
2396          return new WP_Error( 'empty_user_nicename', __( 'Cannot create a user with an empty nicename.' ) );
2397      } elseif ( mb_strlen( $user_nicename ) > 50 ) {
2398          return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
2399      }
2400  
2401      $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 ) );
2402  
2403      if ( $user_nicename_check ) {
2404          $suffix = 2;
2405          while ( $user_nicename_check ) {
2406              // user_nicename allows 50 chars. Subtract one for a hyphen, plus the length of the suffix.
2407              $base_length         = 49 - mb_strlen( $suffix );
2408              $alt_user_nicename   = mb_substr( $user_nicename, 0, $base_length ) . "-$suffix";
2409              $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 ) );
2410              ++$suffix;
2411          }
2412          $user_nicename = $alt_user_nicename;
2413      }
2414  
2415      $raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];
2416  
2417      /**
2418       * Filters a user's email before the user is created or updated.
2419       *
2420       * @since 2.0.3
2421       *
2422       * @param string $raw_user_email The user's email.
2423       */
2424      $user_email = apply_filters( 'pre_user_email', $raw_user_email );
2425  
2426      /*
2427       * If there is no update, just check for `email_exists`. If there is an update,
2428       * check if current email and new email are the same, and check `email_exists`
2429       * accordingly.
2430       */
2431      if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) )
2432          && ! defined( 'WP_IMPORTING' )
2433          && email_exists( $user_email )
2434      ) {
2435          return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
2436      }
2437  
2438      $raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
2439  
2440      /**
2441       * Filters a user's URL before the user is created or updated.
2442       *
2443       * @since 2.0.3
2444       *
2445       * @param string $raw_user_url The user's URL.
2446       */
2447      $user_url = apply_filters( 'pre_user_url', $raw_user_url );
2448  
2449      if ( mb_strlen( $user_url ) > 100 ) {
2450          return new WP_Error( 'user_url_too_long', __( 'User URL may not be longer than 100 characters.' ) );
2451      }
2452  
2453      $user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];
2454  
2455      $user_activation_key = empty( $userdata['user_activation_key'] ) ? '' : $userdata['user_activation_key'];
2456  
2457      if ( ! empty( $userdata['spam'] ) && ! is_multisite() ) {
2458          return new WP_Error( 'no_spam', __( 'Sorry, marking a user as spam is only supported on Multisite.' ) );
2459      }
2460  
2461      $spam = empty( $userdata['spam'] ) ? 0 : (bool) $userdata['spam'];
2462  
2463      // Store values to save in user meta.
2464      $meta = array();
2465  
2466      $nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];
2467  
2468      /**
2469       * Filters a user's nickname before the user is created or updated.
2470       *
2471       * @since 2.0.3
2472       *
2473       * @param string $nickname The user's nickname.
2474       */
2475      $meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );
2476  
2477      $first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];
2478  
2479      /**
2480       * Filters a user's first name before the user is created or updated.
2481       *
2482       * @since 2.0.3
2483       *
2484       * @param string $first_name The user's first name.
2485       */
2486      $meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );
2487  
2488      $last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];
2489  
2490      /**
2491       * Filters a user's last name before the user is created or updated.
2492       *
2493       * @since 2.0.3
2494       *
2495       * @param string $last_name The user's last name.
2496       */
2497      $meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );
2498  
2499      if ( empty( $userdata['display_name'] ) ) {
2500          if ( $update ) {
2501              $display_name = $user_login;
2502          } elseif ( $meta['first_name'] && $meta['last_name'] ) {
2503              $display_name = sprintf(
2504                  /* translators: 1: User's first name, 2: Last name. */
2505                  _x( '%1$s %2$s', 'Display name based on first name and last name' ),
2506                  $meta['first_name'],
2507                  $meta['last_name']
2508              );
2509          } elseif ( $meta['first_name'] ) {
2510              $display_name = $meta['first_name'];
2511          } elseif ( $meta['last_name'] ) {
2512              $display_name = $meta['last_name'];
2513          } else {
2514              $display_name = $user_login;
2515          }
2516      } else {
2517          $display_name = $userdata['display_name'];
2518      }
2519  
2520      /**
2521       * Filters a user's display name before the user is created or updated.
2522       *
2523       * @since 2.0.3
2524       *
2525       * @param string $display_name The user's display name.
2526       */
2527      $display_name = apply_filters( 'pre_user_display_name', $display_name );
2528  
2529      $description = empty( $userdata['description'] ) ? '' : $userdata['description'];
2530  
2531      /**
2532       * Filters a user's description before the user is created or updated.
2533       *
2534       * @since 2.0.3
2535       *
2536       * @param string $description The user's description.
2537       */
2538      $meta['description'] = apply_filters( 'pre_user_description', $description );
2539  
2540      $meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];
2541  
2542      $meta['syntax_highlighting'] = empty( $userdata['syntax_highlighting'] ) ? 'true' : $userdata['syntax_highlighting'];
2543  
2544      $meta['infinite_scrolling'] = empty( $userdata['infinite_scrolling'] ) ? 'true' : $userdata['infinite_scrolling'];
2545  
2546      $meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';
2547  
2548      $admin_color         = empty( $userdata['admin_color'] ) ? 'modern' : $userdata['admin_color'];
2549      $meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );
2550  
2551      $meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? '0' : '1';
2552  
2553      $meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];
2554  
2555      $meta['locale'] = $userdata['locale'] ?? '';
2556  
2557      $compacted = compact( 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'display_name' );
2558      $data      = wp_unslash( $compacted );
2559  
2560      if ( ! $update ) {
2561          $data = $data + compact( 'user_login' );
2562      }
2563  
2564      if ( is_multisite() ) {
2565          $data = $data + compact( 'spam' );
2566      }
2567  
2568      /**
2569       * Filters user data before the record is created or updated.
2570       *
2571       * It only includes data in the users table, not any user metadata.
2572       *
2573       * @since 4.9.0
2574       * @since 5.8.0 The `$userdata` parameter was added.
2575       * @since 6.8.0 The user's password is now hashed using bcrypt by default instead of phpass.
2576       *
2577       * @param array    $data {
2578       *     Values and keys for the user.
2579       *
2580       *     @type string $user_login      The user's login. Only included if $update == false
2581       *     @type string $user_pass       The user's password.
2582       *     @type string $user_email      The user's email.
2583       *     @type string $user_url        The user's url.
2584       *     @type string $user_nicename   The user's nice name. Defaults to a URL-safe version of user's login.
2585       *     @type string $display_name    The user's display name.
2586       *     @type string $user_registered MySQL timestamp describing the moment when the user registered. Defaults to
2587       *                                   the current UTC timestamp.
2588       * }
2589       * @param bool     $update   Whether the user is being updated rather than created.
2590       * @param int|null $user_id  ID of the user to be updated, or NULL if the user is being created.
2591       * @param array    $userdata The raw array of data passed to wp_insert_user().
2592       */
2593      $data = apply_filters( 'wp_pre_insert_user_data', $data, $update, ( $update ? $user_id : null ), $userdata );
2594  
2595      if ( empty( $data ) || ! is_array( $data ) ) {
2596          return new WP_Error( 'empty_data', __( 'Not enough data to create this user.' ) );
2597      }
2598  
2599      if ( $update ) {
2600          if ( $user_email !== $old_user_data->user_email || $user_pass !== $old_user_data->user_pass ) {
2601              $data['user_activation_key'] = '';
2602          }
2603          $wpdb->update( $wpdb->users, $data, array( 'ID' => $user_id ) );
2604      } else {
2605          $wpdb->insert( $wpdb->users, $data );
2606          $user_id = (int) $wpdb->insert_id;
2607      }
2608  
2609      $user = new WP_User( $user_id );
2610  
2611      if ( ! $update ) {
2612          /** This action is documented in wp-includes/pluggable.php */
2613          do_action( 'wp_set_password', $userdata['user_pass'], $user_id, $user );
2614      }
2615  
2616      /**
2617       * Filters a user's meta values and keys immediately after the user is created or updated
2618       * and before any user meta is inserted or updated.
2619       *
2620       * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`.
2621       *
2622       * For custom meta fields, see the {@see 'insert_custom_user_meta'} filter.
2623       *
2624       * @since 4.4.0
2625       * @since 5.8.0 The `$userdata` parameter was added.
2626       *
2627       * @param array   $meta {
2628       *     Default meta values and keys for the user.
2629       *
2630       *     @type string   $nickname             The user's nickname. Default is the user's username.
2631       *     @type string   $first_name           The user's first name.
2632       *     @type string   $last_name            The user's last name.
2633       *     @type string   $description          The user's description.
2634       *     @type string   $rich_editing         Whether to enable the rich-editor for the user. Default 'true'.
2635       *     @type string   $syntax_highlighting  Whether to enable the rich code editor for the user. Default 'true'.
2636       *     @type string   $comment_shortcuts    Whether to enable keyboard shortcuts for the user. Default 'false'.
2637       *     @type string   $admin_color          The color scheme for a user's admin screen. Default 'modern'.
2638       *     @type int|bool $use_ssl              Whether to force SSL on the user's admin area. 0|false if SSL
2639       *                                          is not forced.
2640       *     @type string   $show_admin_bar_front Whether to show the admin bar on the front end for the user.
2641       *                                          Default 'true'.
2642       *     @type string   $locale               User's locale. Default empty.
2643       * }
2644       * @param WP_User $user     User object.
2645       * @param bool    $update   Whether the user is being updated rather than created.
2646       * @param array   $userdata The raw array of data passed to wp_insert_user().
2647       */
2648      $meta = apply_filters( 'insert_user_meta', $meta, $user, $update, $userdata );
2649  
2650      $custom_meta = array();
2651      if ( array_key_exists( 'meta_input', $userdata ) && is_array( $userdata['meta_input'] ) && ! empty( $userdata['meta_input'] ) ) {
2652          $custom_meta = $userdata['meta_input'];
2653      }
2654  
2655      /**
2656       * Filters a user's custom meta values and keys immediately after the user is created or updated
2657       * and before any user meta is inserted or updated.
2658       *
2659       * For non-custom meta fields, see the {@see 'insert_user_meta'} filter.
2660       *
2661       * @since 5.9.0
2662       *
2663       * @param array   $custom_meta Array of custom user meta values keyed by meta key.
2664       * @param WP_User $user        User object.
2665       * @param bool    $update      Whether the user is being updated rather than created.
2666       * @param array   $userdata    The raw array of data passed to wp_insert_user().
2667       */
2668      $custom_meta = apply_filters( 'insert_custom_user_meta', $custom_meta, $user, $update, $userdata );
2669  
2670      $meta = array_merge( $meta, $custom_meta );
2671  
2672      if ( $update ) {
2673          // Update user meta.
2674          foreach ( $meta as $key => $value ) {
2675              update_user_meta( $user_id, $key, $value );
2676          }
2677      } else {
2678          // Add user meta.
2679          foreach ( $meta as $key => $value ) {
2680              add_user_meta( $user_id, $key, $value );
2681          }
2682      }
2683  
2684      foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
2685          if ( isset( $userdata[ $key ] ) ) {
2686              update_user_meta( $user_id, $key, $userdata[ $key ] );
2687          }
2688      }
2689  
2690      if ( isset( $userdata['role'] ) ) {
2691          $user->set_role( $userdata['role'] );
2692      } elseif ( ! $update ) {
2693          $user->set_role( get_option( 'default_role' ) );
2694      }
2695  
2696      clean_user_cache( $user_id );
2697  
2698      if ( $update ) {
2699          /**
2700           * Fires immediately after an existing user is updated.
2701           *
2702           * @since 2.0.0
2703           * @since 5.8.0 The `$userdata` parameter was added.
2704           *
2705           * @param int     $user_id       User ID.
2706           * @param WP_User $old_user_data Object containing user's data prior to update.
2707           * @param array   $userdata      The raw array of data passed to wp_insert_user().
2708           */
2709          do_action( 'profile_update', $user_id, $old_user_data, $userdata );
2710  
2711          if ( isset( $userdata['spam'] ) && $userdata['spam'] !== $old_user_data->spam ) {
2712              if ( '1' === $userdata['spam'] ) {
2713                  /**
2714                   * Fires after the user is marked as a SPAM user.
2715                   *
2716                   * @since 3.0.0
2717                   *
2718                   * @param int $user_id ID of the user marked as SPAM.
2719                   */
2720                  do_action( 'make_spam_user', $user_id );
2721              } else {
2722                  /**
2723                   * Fires after the user is marked as a HAM user. Opposite of SPAM.
2724                   *
2725                   * @since 3.0.0
2726                   *
2727                   * @param int $user_id ID of the user marked as HAM.
2728                   */
2729                  do_action( 'make_ham_user', $user_id );
2730              }
2731          }
2732      } else {
2733          /**
2734           * Fires immediately after a new user is registered.
2735           *
2736           * @since 1.5.0
2737           * @since 5.8.0 The `$userdata` parameter was added.
2738           *
2739           * @param int   $user_id  User ID.
2740           * @param array $userdata The raw array of data passed to wp_insert_user().
2741           */
2742          do_action( 'user_register', $user_id, $userdata );
2743      }
2744  
2745      return $user_id;
2746  }
2747  
2748  /**
2749   * Updates a user in the database.
2750   *
2751   * It is possible to update a user's password by specifying the 'user_pass'
2752   * value in the $userdata parameter array.
2753   *
2754   * If current user's password is being updated, then the cookies will be
2755   * cleared.
2756   *
2757   * @since 2.0.0
2758   *
2759   * @see wp_insert_user() For what fields can be set in $userdata.
2760   *
2761   * @param array|object|WP_User $userdata An array of user data or a user object of type stdClass or WP_User.
2762   * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
2763   */
2764  function wp_update_user( $userdata ) {
2765      if ( $userdata instanceof stdClass ) {
2766          $userdata = get_object_vars( $userdata );
2767      } elseif ( $userdata instanceof WP_User ) {
2768          $userdata = $userdata->to_array();
2769      }
2770  
2771      $userdata_raw = $userdata;
2772  
2773      $user_id = (int) ( $userdata['ID'] ?? 0 );
2774      if ( ! $user_id ) {
2775          return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
2776      }
2777  
2778      // First, get all of the original fields.
2779      $user_obj = get_userdata( $user_id );
2780      if ( ! $user_obj ) {
2781          return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
2782      }
2783  
2784      $user = $user_obj->to_array();
2785  
2786      // Add additional custom fields.
2787      foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
2788          $user[ $key ] = get_user_meta( $user_id, $key, true );
2789      }
2790  
2791      // Escape data pulled from DB.
2792      $user = add_magic_quotes( $user );
2793  
2794      if ( ! empty( $userdata['user_pass'] ) && $userdata['user_pass'] !== $user_obj->user_pass ) {
2795          // If password is changing, hash it now.
2796          $plaintext_pass        = $userdata['user_pass'];
2797          $userdata['user_pass'] = wp_hash_password( $userdata['user_pass'] );
2798  
2799          /** This action is documented in wp-includes/pluggable.php */
2800          do_action( 'wp_set_password', $plaintext_pass, $user_id, $user_obj );
2801  
2802          /**
2803           * Filters whether to send the password change email.
2804           *
2805           * @since 4.3.0
2806           *
2807           * @see wp_insert_user() For `$user` and `$userdata` fields.
2808           *
2809           * @param bool  $send     Whether to send the email.
2810           * @param array $user     The original user array.
2811           * @param array $userdata The updated user array.
2812           */
2813          $send_password_change_email = apply_filters( 'send_password_change_email', true, $user, $userdata );
2814      }
2815  
2816      if ( isset( $userdata['user_email'] ) && $user['user_email'] !== $userdata['user_email'] ) {
2817          /**
2818           * Filters whether to send the email change email.
2819           *
2820           * @since 4.3.0
2821           *
2822           * @see wp_insert_user() For `$user` and `$userdata` fields.
2823           *
2824           * @param bool  $send     Whether to send the email.
2825           * @param array $user     The original user array.
2826           * @param array $userdata The updated user array.
2827           */
2828          $send_email_change_email = apply_filters( 'send_email_change_email', true, $user, $userdata );
2829      }
2830  
2831      clean_user_cache( $user_obj );
2832  
2833      // Merge old and new fields with new fields overwriting old ones.
2834      $userdata = array_merge( $user, $userdata );
2835      $user_id  = wp_insert_user( $userdata );
2836  
2837      if ( is_wp_error( $user_id ) ) {
2838          return $user_id;
2839      }
2840  
2841      $blog_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
2842  
2843      $switched_locale = false;
2844      if ( ! empty( $send_password_change_email ) || ! empty( $send_email_change_email ) ) {
2845          $switched_locale = switch_to_user_locale( $user_id );
2846      }
2847  
2848      if ( ! empty( $send_password_change_email ) ) {
2849          /* translators: Do not translate USERNAME, ADMIN_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
2850          $pass_change_text = __(
2851              'Hi ###USERNAME###,
2852  
2853  This notice confirms that your password was changed on ###SITENAME###.
2854  
2855  If you did not change your password, please contact the Site Administrator at
2856  ###ADMIN_EMAIL###
2857  
2858  This email has been sent to ###EMAIL###
2859  
2860  Regards,
2861  All at ###SITENAME###
2862  ###SITEURL###'
2863          );
2864  
2865          $pass_change_email = array(
2866              'to'      => $user['user_email'],
2867              /* translators: Password change notification email subject. %s: Site title. */
2868              'subject' => __( '[%s] Password Changed' ),
2869              'message' => $pass_change_text,
2870              'headers' => '',
2871          );
2872  
2873          /**
2874           * Filters the contents of the email sent when the user's password is changed.
2875           *
2876           * @since 4.3.0
2877           *
2878           * @param array $pass_change_email {
2879           *     Used to build wp_mail().
2880           *
2881           *     @type string $to      The intended recipients. Add emails in a comma separated string.
2882           *     @type string $subject The subject of the email.
2883           *     @type string $message The content of the email.
2884           *         The following strings have a special meaning and will get replaced dynamically:
2885           *          - `###USERNAME###`    The current user's username.
2886           *          - `###ADMIN_EMAIL###` The admin email in case this was unexpected.
2887           *          - `###EMAIL###`       The user's email address.
2888           *          - `###SITENAME###`    The name of the site.
2889           *          - `###SITEURL###`     The URL to the site.
2890           *     @type string $headers Headers. Add headers in a newline (\r\n) separated string.
2891           * }
2892           * @param array $user     The original user array.
2893           * @param array $userdata The updated user array.
2894           */
2895          $pass_change_email = apply_filters( 'password_change_email', $pass_change_email, $user, $userdata );
2896  
2897          $pass_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $pass_change_email['message'] );
2898          $pass_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $pass_change_email['message'] );
2899          $pass_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $pass_change_email['message'] );
2900          $pass_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $pass_change_email['message'] );
2901          $pass_change_email['message'] = str_replace( '###SITEURL###', home_url(), $pass_change_email['message'] );
2902  
2903          wp_mail( $pass_change_email['to'], sprintf( $pass_change_email['subject'], $blog_name ), $pass_change_email['message'], $pass_change_email['headers'] );
2904      }
2905  
2906      if ( ! empty( $send_email_change_email ) ) {
2907          /* translators: Do not translate USERNAME, ADMIN_EMAIL, NEW_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
2908          $email_change_text = __(
2909              'Hi ###USERNAME###,
2910  
2911  This notice confirms that your email address on ###SITENAME### was changed to ###NEW_EMAIL###.
2912  
2913  If you did not change your email, please contact the Site Administrator at
2914  ###ADMIN_EMAIL###
2915  
2916  This email has been sent to ###EMAIL###
2917  
2918  Regards,
2919  All at ###SITENAME###
2920  ###SITEURL###'
2921          );
2922  
2923          $email_change_email = array(
2924              'to'      => $user['user_email'],
2925              /* translators: Email change notification email subject. %s: Site title. */
2926              'subject' => __( '[%s] Email Changed' ),
2927              'message' => $email_change_text,
2928              'headers' => '',
2929          );
2930  
2931          /**
2932           * Filters the contents of the email sent when the user's email is changed.
2933           *
2934           * @since 4.3.0
2935           *
2936           * @param array $email_change_email {
2937           *     Used to build wp_mail().
2938           *
2939           *     @type string $to      The intended recipients.
2940           *     @type string $subject The subject of the email.
2941           *     @type string $message The content of the email.
2942           *         The following strings have a special meaning and will get replaced dynamically:
2943           *          - `###USERNAME###`    The current user's username.
2944           *          - `###ADMIN_EMAIL###` The admin email in case this was unexpected.
2945           *          - `###NEW_EMAIL###`   The new email address.
2946           *          - `###EMAIL###`       The old email address.
2947           *          - `###SITENAME###`    The name of the site.
2948           *          - `###SITEURL###`     The URL to the site.
2949           *     @type string $headers Headers.
2950           * }
2951           * @param array $user     The original user array.
2952           * @param array $userdata The updated user array.
2953           */
2954          $email_change_email = apply_filters( 'email_change_email', $email_change_email, $user, $userdata );
2955  
2956          $email_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $email_change_email['message'] );
2957          $email_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $email_change_email['message'] );
2958          $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $userdata['user_email'], $email_change_email['message'] );
2959          $email_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $email_change_email['message'] );
2960          $email_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $email_change_email['message'] );
2961          $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
2962  
2963          wp_mail( $email_change_email['to'], sprintf( $email_change_email['subject'], $blog_name ), $email_change_email['message'], $email_change_email['headers'] );
2964      }
2965  
2966      if ( $switched_locale ) {
2967          restore_previous_locale();
2968      }
2969  
2970      // Update the cookies if the password changed.
2971      $current_user = wp_get_current_user();
2972      if ( $current_user->ID === $user_id ) {
2973          if ( isset( $plaintext_pass ) ) {
2974              /*
2975               * Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
2976               * If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
2977               */
2978              $logged_in_cookie = wp_parse_auth_cookie( '', 'logged_in' );
2979              /** This filter is documented in wp-includes/pluggable.php */
2980              $default_cookie_life = apply_filters( 'auth_cookie_expiration', ( 2 * DAY_IN_SECONDS ), $user_id, false );
2981  
2982              wp_clear_auth_cookie();
2983  
2984              $remember = false;
2985              $token    = '';
2986  
2987              if ( false !== $logged_in_cookie ) {
2988                  $token = $logged_in_cookie['token'];
2989              }
2990  
2991              if ( false !== $logged_in_cookie && ( (int) $logged_in_cookie['expiration'] - time() ) > $default_cookie_life ) {
2992                  $remember = true;
2993              }
2994  
2995              wp_set_auth_cookie( $user_id, $remember, '', $token );
2996          }
2997      }
2998  
2999      /**
3000       * Fires after the user has been updated and emails have been sent.
3001       *
3002       * @since 6.3.0
3003       *
3004       * @param int   $user_id      The ID of the user that was just updated.
3005       * @param array $userdata     The array of user data that was updated.
3006       * @param array $userdata_raw The unedited array of user data that was updated.
3007       */
3008      do_action( 'wp_update_user', $user_id, $userdata, $userdata_raw );
3009  
3010      return $user_id;
3011  }
3012  
3013  /**
3014   * Provides a simpler way of inserting a user into the database.
3015   *
3016   * Creates a new user with just the username, password, and email. For more
3017   * complex user creation use wp_insert_user() to specify more information.
3018   *
3019   * @since 2.0.0
3020   *
3021   * @see wp_insert_user() More complete way to create a new user.
3022   *
3023   * @param string $username The user's username.
3024   * @param string $password The user's password.
3025   * @param string $email    Optional. The user's email. Default empty.
3026   * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
3027   *                      be created.
3028   */
3029  function wp_create_user(
3030      $username,
3031      #[\SensitiveParameter]
3032      $password,
3033      $email = ''
3034  ) {
3035      $user_login = wp_slash( $username );
3036      $user_email = wp_slash( $email );
3037      $user_pass  = $password;
3038  
3039      $userdata = compact( 'user_login', 'user_email', 'user_pass' );
3040      return wp_insert_user( $userdata );
3041  }
3042  
3043  /**
3044   * Returns a list of meta keys to be (maybe) populated in wp_update_user().
3045   *
3046   * The list of keys returned via this function are dependent on the presence
3047   * of those keys in the user meta data to be set.
3048   *
3049   * @since 3.3.0
3050   * @access private
3051   *
3052   * @param WP_User $user WP_User instance.
3053   * @return string[] List of user keys to be populated in wp_update_user().
3054   */
3055  function _get_additional_user_keys( $user ) {
3056      $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'syntax_highlighting', 'infinite_scrolling', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front', 'locale' );
3057      return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
3058  }
3059  
3060  /**
3061   * Sets up the user contact methods.
3062   *
3063   * Default contact methods were removed for new installations in WordPress 3.6
3064   * and completely removed from the codebase in WordPress 6.9.
3065   *
3066   * Use the {@see 'user_contactmethods'} filter to add or remove contact methods.
3067   *
3068   * @since 3.7.0
3069   * @since 6.9.0 Removed references to `aim`, `jabber`, and `yim` contact methods.
3070   *
3071   * @param WP_User|null $user Optional. WP_User object.
3072   * @return string[] Array of contact method labels keyed by contact method.
3073   */
3074  function wp_get_user_contact_methods( $user = null ) {
3075      $methods = array();
3076  
3077      /**
3078       * Filters the user contact methods.
3079       *
3080       * @since 2.9.0
3081       *
3082       * @param string[]     $methods Array of contact method labels keyed by contact method.
3083       * @param WP_User|null $user    WP_User object or null if none was provided.
3084       */
3085      return apply_filters( 'user_contactmethods', $methods, $user );
3086  }
3087  
3088  /**
3089   * The old private function for setting up user contact methods.
3090   *
3091   * Use wp_get_user_contact_methods() instead.
3092   *
3093   * @since 2.9.0
3094   * @access private
3095   *
3096   * @param WP_User|null $user Optional. WP_User object. Default null.
3097   * @return string[] Array of contact method labels keyed by contact method.
3098   */
3099  function _wp_get_user_contactmethods( $user = null ) {
3100      return wp_get_user_contact_methods( $user );
3101  }
3102  
3103  /**
3104   * Gets the text suggesting how to create strong passwords.
3105   *
3106   * @since 4.1.0
3107   *
3108   * @return string The password hint text.
3109   */
3110  function wp_get_password_hint() {
3111      $hint = __( 'Hint: The password should be at least twelve characters long. To make it stronger, use upper and lower case letters, numbers, and symbols like ! " ? $ % ^ &amp; ).' );
3112  
3113      /**
3114       * Filters the text describing the site's password complexity policy.
3115       *
3116       * @since 4.1.0
3117       *
3118       * @param string $hint The password hint text.
3119       */
3120      return apply_filters( 'password_hint', $hint );
3121  }
3122  
3123  /**
3124   * Creates, stores, then returns a password reset key for user.
3125   *
3126   * @since 4.4.0
3127   *
3128   * @param WP_User $user User to retrieve password reset key for.
3129   * @return string|WP_Error Password reset key on success. WP_Error on error.
3130   */
3131  function get_password_reset_key( $user ) {
3132      if ( ! ( $user instanceof WP_User ) ) {
3133          return new WP_Error( 'invalidcombo', __( '<strong>Error:</strong> There is no account with that username or email address.' ) );
3134      }
3135  
3136      /**
3137       * Fires before a new password is retrieved.
3138       *
3139       * Use the {@see 'retrieve_password'} hook instead.
3140       *
3141       * @since 1.5.0
3142       * @deprecated 1.5.1 Misspelled. Use {@see 'retrieve_password'} hook instead.
3143       *
3144       * @param string $user_login The user login name.
3145       */
3146      do_action_deprecated( 'retreive_password', array( $user->user_login ), '1.5.1', 'retrieve_password' );
3147  
3148      /**
3149       * Fires before a new password is retrieved.
3150       *
3151       * @since 1.5.1
3152       *
3153       * @param string $user_login The user login name.
3154       */
3155      do_action( 'retrieve_password', $user->user_login );
3156  
3157      $password_reset_allowed = wp_is_password_reset_allowed_for_user( $user );
3158      if ( ! $password_reset_allowed ) {
3159          return new WP_Error( 'no_password_reset', __( 'Password reset is not allowed for this user' ) );
3160      } elseif ( is_wp_error( $password_reset_allowed ) ) {
3161          return $password_reset_allowed;
3162      }
3163  
3164      // Generate something random for a password reset key.
3165      $key = wp_generate_password( 20, false );
3166  
3167      /**
3168       * Fires when a password reset key is generated.
3169       *
3170       * @since 2.5.0
3171       *
3172       * @param string $user_login The username for the user.
3173       * @param string $key        The generated password reset key.
3174       */
3175      do_action( 'retrieve_password_key', $user->user_login, $key );
3176  
3177      $hashed = time() . ':' . wp_fast_hash( $key );
3178  
3179      $key_saved = wp_update_user(
3180          array(
3181              'ID'                  => $user->ID,
3182              'user_activation_key' => $hashed,
3183          )
3184      );
3185  
3186      if ( is_wp_error( $key_saved ) ) {
3187          return $key_saved;
3188      }
3189  
3190      return $key;
3191  }
3192  
3193  /**
3194   * Retrieves a user row based on password reset key and login.
3195   *
3196   * A key is considered 'expired' if it exactly matches the value of the
3197   * user_activation_key field, rather than being matched after going through the
3198   * hashing process. This field is now hashed; old values are no longer accepted
3199   * but have a different WP_Error code so good user feedback can be provided.
3200   *
3201   * @since 3.1.0
3202   *
3203   * @param string $key       The password reset key.
3204   * @param string $login     The user login.
3205   * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
3206   */
3207  function check_password_reset_key(
3208      #[\SensitiveParameter]
3209      $key,
3210      $login
3211  ) {
3212      $key = preg_replace( '/[^a-z0-9]/i', '', $key );
3213  
3214      if ( empty( $key ) || ! is_string( $key ) ) {
3215          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3216      }
3217  
3218      if ( empty( $login ) || ! is_string( $login ) ) {
3219          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3220      }
3221  
3222      $user = get_user_by( 'login', $login );
3223  
3224      if ( ! $user ) {
3225          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3226      }
3227  
3228      /**
3229       * Filters the expiration time of password reset keys.
3230       *
3231       * @since 4.3.0
3232       *
3233       * @param int $expiration The expiration time in seconds.
3234       */
3235      $expiration_duration = apply_filters( 'password_reset_expiration', DAY_IN_SECONDS );
3236  
3237      if ( str_contains( $user->user_activation_key, ':' ) ) {
3238          list( $pass_request_time, $pass_key ) = explode( ':', $user->user_activation_key, 2 );
3239          $expiration_time                      = $pass_request_time + $expiration_duration;
3240      } else {
3241          $pass_key        = $user->user_activation_key;
3242          $expiration_time = false;
3243      }
3244  
3245      if ( ! $pass_key ) {
3246          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3247      }
3248  
3249      $hash_is_correct = wp_verify_fast_hash( $key, $pass_key );
3250  
3251      if ( $hash_is_correct && $expiration_time && time() < $expiration_time ) {
3252          return $user;
3253      } elseif ( $hash_is_correct && $expiration_time ) {
3254          // Key has an expiration time that's passed.
3255          return new WP_Error( 'expired_key', __( 'Invalid key.' ) );
3256      }
3257  
3258      if ( hash_equals( $user->user_activation_key, $key ) || ( $hash_is_correct && ! $expiration_time ) ) {
3259          $return  = new WP_Error( 'expired_key', __( 'Invalid key.' ) );
3260          $user_id = $user->ID;
3261  
3262          /**
3263           * Filters the return value of check_password_reset_key() when an
3264           * old-style key or an expired key is used.
3265           *
3266           * Prior to 3.7, plain-text keys were stored in the database.
3267           *
3268           * @since 3.7.0
3269           * @since 4.3.0 Previously key hashes were stored without an expiration time.
3270           *
3271           * @param WP_Error $return  A WP_Error object denoting an expired key.
3272           *                          Return a WP_User object to validate the key.
3273           * @param int      $user_id The matched user ID.
3274           */
3275          return apply_filters( 'password_reset_key_expired', $return, $user_id );
3276      }
3277  
3278      return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3279  }
3280  
3281  /**
3282   * Handles sending a password retrieval email to a user.
3283   *
3284   * @since 2.5.0
3285   * @since 5.7.0 Added `$user_login` parameter.
3286   *
3287   * @global wpdb $wpdb WordPress database abstraction object.
3288   *
3289   * @param string $user_login Optional. Username to send a password retrieval email for.
3290   *                           Defaults to `$_POST['user_login']` if not set.
3291   * @return true|WP_Error True when finished, WP_Error object on error.
3292   */
3293  function retrieve_password( $user_login = '' ) {
3294      $errors    = new WP_Error();
3295      $user_data = false;
3296  
3297      // Use the passed $user_login if available, otherwise use $_POST['user_login'].
3298      if ( ! $user_login && ! empty( $_POST['user_login'] ) && is_string( $_POST['user_login'] ) ) {
3299          $user_login = $_POST['user_login'];
3300      }
3301  
3302      $user_login = trim( wp_unslash( $user_login ) );
3303  
3304      if ( empty( $user_login ) ) {
3305          $errors->add( 'empty_username', __( '<strong>Error:</strong> Please enter a username or email address.' ) );
3306      } elseif ( strpos( $user_login, '@' ) ) {
3307          $user_data = get_user_by( 'email', $user_login );
3308  
3309          if ( empty( $user_data ) ) {
3310              $user_data = get_user_by( 'login', $user_login );
3311          }
3312  
3313          if ( empty( $user_data ) ) {
3314              $errors->add( 'invalid_email', __( '<strong>Error:</strong> There is no account with that username or email address.' ) );
3315          }
3316      } else {
3317          $user_data = get_user_by( 'login', $user_login );
3318      }
3319  
3320      /**
3321       * Filters the user data during a password reset request.
3322       *
3323       * Allows, for example, custom validation using data other than username or email address.
3324       *
3325       * @since 5.7.0
3326       *
3327       * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
3328       * @param WP_Error      $errors    A WP_Error object containing any errors generated
3329       *                                 by using invalid credentials.
3330       */
3331      $user_data = apply_filters( 'lostpassword_user_data', $user_data, $errors );
3332  
3333      /**
3334       * Fires before errors are returned from a password reset request.
3335       *
3336       * @since 2.1.0
3337       * @since 4.4.0 Added the `$errors` parameter.
3338       * @since 5.4.0 Added the `$user_data` parameter.
3339       *
3340       * @param WP_Error      $errors    A WP_Error object containing any errors generated
3341       *                                 by using invalid credentials.
3342       * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
3343       */
3344      do_action( 'lostpassword_post', $errors, $user_data );
3345  
3346      /**
3347       * Filters the errors encountered on a password reset request.
3348       *
3349       * The filtered WP_Error object may, for example, contain errors for an invalid
3350       * username or email address. A WP_Error object should always be returned,
3351       * but may or may not contain errors.
3352       *
3353       * If any errors are present in $errors, this will abort the password reset request.
3354       *
3355       * @since 5.5.0
3356       *
3357       * @param WP_Error      $errors    A WP_Error object containing any errors generated
3358       *                                 by using invalid credentials.
3359       * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
3360       */
3361      $errors = apply_filters( 'lostpassword_errors', $errors, $user_data );
3362  
3363      if ( $errors->has_errors() ) {
3364          return $errors;
3365      }
3366  
3367      if ( ! $user_data ) {
3368          $errors->add( 'invalidcombo', __( '<strong>Error:</strong> There is no account with that username or email address.' ) );
3369          return $errors;
3370      }
3371  
3372      /**
3373       * Filters whether to send the retrieve password email.
3374       *
3375       * Return false to disable sending the email.
3376       *
3377       * @since 6.0.0
3378       *
3379       * @param bool    $send       Whether to send the email.
3380       * @param string  $user_login The username for the user.
3381       * @param WP_User $user_data  WP_User object.
3382       */
3383      if ( ! apply_filters( 'send_retrieve_password_email', true, $user_login, $user_data ) ) {
3384          return true;
3385      }
3386  
3387      // Redefining user_login ensures we return the right case in the email.
3388      $user_login = $user_data->user_login;
3389      $user_email = $user_data->user_email;
3390      $key        = get_password_reset_key( $user_data );
3391  
3392      if ( is_wp_error( $key ) ) {
3393          return $key;
3394      }
3395  
3396      // Localize password reset message content for user.
3397      $locale = get_user_locale( $user_data );
3398  
3399      $switched_locale = switch_to_user_locale( $user_data->ID );
3400  
3401      if ( is_multisite() ) {
3402          $site_name = get_network()->site_name;
3403      } else {
3404          /*
3405           * The blogname option is escaped with esc_html on the way into the database
3406           * in sanitize_option. We want to reverse this for the plain text arena of emails.
3407           */
3408          $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
3409      }
3410  
3411      $message = __( 'Someone has requested a password reset for the following account:' ) . "\r\n\r\n";
3412      /* translators: %s: Site name. */
3413      $message .= sprintf( __( 'Site Name: %s' ), $site_name ) . "\r\n\r\n";
3414      /* translators: %s: User login. */
3415      $message .= sprintf( __( 'Username: %s' ), $user_login ) . "\r\n\r\n";
3416      $message .= __( 'If this was a mistake, ignore this email and nothing will happen.' ) . "\r\n\r\n";
3417      $message .= __( 'To reset your password, visit the following address:' ) . "\r\n\r\n";
3418  
3419      /*
3420       * Since some user login names end in a period, this could produce ambiguous URLs that
3421       * end in a period. To avoid the ambiguity, ensure that the login is not the last query
3422       * arg in the URL. If moving it to the end, a trailing period will need to be escaped.
3423       *
3424       * @see https://core.trac.wordpress.org/tickets/42957
3425       */
3426      $message .= network_site_url( 'wp-login.php?login=' . rawurlencode( $user_login ) . "&key=$key&action=rp", 'login' ) . '&wp_lang=' . $locale . "\r\n\r\n";
3427  
3428      if ( ! is_user_logged_in() ) {
3429          $requester_ip = $_SERVER['REMOTE_ADDR'];
3430          if ( $requester_ip ) {
3431              $message .= sprintf(
3432                  /* translators: %s: IP address of password reset requester. */
3433                  __( 'This password reset request originated from the IP address %s.' ),
3434                  $requester_ip
3435              ) . "\r\n";
3436          }
3437      }
3438  
3439      /* translators: Password reset notification email subject. %s: Site title. */
3440      $title = sprintf( __( '[%s] Password Reset' ), $site_name );
3441  
3442      /**
3443       * Filters the subject of the password reset email.
3444       *
3445       * @since 2.8.0
3446       * @since 4.4.0 Added the `$user_login` and `$user_data` parameters.
3447       *
3448       * @param string  $title      Email subject.
3449       * @param string  $user_login The username for the user.
3450       * @param WP_User $user_data  WP_User object.
3451       */
3452      $title = apply_filters( 'retrieve_password_title', $title, $user_login, $user_data );
3453  
3454      /**
3455       * Filters the message body of the password reset mail.
3456       *
3457       * If the filtered message is empty, the password reset email will not be sent.
3458       *
3459       * @since 2.8.0
3460       * @since 4.1.0 Added `$user_login` and `$user_data` parameters.
3461       *
3462       * @param string  $message    Email message.
3463       * @param string  $key        The activation key.
3464       * @param string  $user_login The username for the user.
3465       * @param WP_User $user_data  WP_User object.
3466       */
3467      $message = apply_filters( 'retrieve_password_message', $message, $key, $user_login, $user_data );
3468  
3469      // Short-circuit on falsey $message value for backwards compatibility.
3470      if ( ! $message ) {
3471          return true;
3472      }
3473  
3474      /*
3475       * Wrap the single notification email arguments in an array
3476       * to pass them to the retrieve_password_notification_email filter.
3477       */
3478      $defaults = array(
3479          'to'      => $user_email,
3480          'subject' => $title,
3481          'message' => $message,
3482          'headers' => '',
3483      );
3484  
3485      /**
3486       * Filters the contents of the reset password notification email sent to the user.
3487       *
3488       * @since 6.0.0
3489       *
3490       * @param array   $defaults {
3491       *     The default notification email arguments. Used to build wp_mail().
3492       *
3493       *     @type string $to      The intended recipient - user email address.
3494       *     @type string $subject The subject of the email.
3495       *     @type string $message The body of the email.
3496       *     @type string $headers The headers of the email.
3497       * }
3498       * @param string  $key        The activation key.
3499       * @param string  $user_login The username for the user.
3500       * @param WP_User $user_data  WP_User object.
3501       */
3502      $notification_email = apply_filters( 'retrieve_password_notification_email', $defaults, $key, $user_login, $user_data );
3503  
3504      if ( $switched_locale ) {
3505          restore_previous_locale();
3506      }
3507  
3508      if ( is_array( $notification_email ) ) {
3509          // Force key order and merge defaults in case any value is missing in the filtered array.
3510          $notification_email = array_merge( $defaults, $notification_email );
3511      } else {
3512          $notification_email = $defaults;
3513      }
3514  
3515      list( $to, $subject, $message, $headers ) = array_values( $notification_email );
3516  
3517      $subject = wp_specialchars_decode( $subject );
3518  
3519      if ( ! wp_mail( $to, $subject, $message, $headers ) ) {
3520          $errors->add(
3521              'retrieve_password_email_failure',
3522              sprintf(
3523                  /* translators: %s: Documentation URL. */
3524                  __( '<strong>Error:</strong> The email could not be sent. Your site may not be correctly configured to send emails. <a href="%s">Get support for resetting your password</a>.' ),
3525                  esc_url( __( 'https://wordpress.org/documentation/article/reset-your-password/' ) )
3526              )
3527          );
3528          return $errors;
3529      }
3530  
3531      return true;
3532  }
3533  
3534  /**
3535   * Handles resetting the user's password.
3536   *
3537   * @since 2.5.0
3538   *
3539   * @param WP_User $user     The user
3540   * @param string  $new_pass New password for the user in plaintext
3541   */
3542  function reset_password(
3543      $user,
3544      #[\SensitiveParameter]
3545      $new_pass
3546  ) {
3547      /**
3548       * Fires before the user's password is reset.
3549       *
3550       * @since 1.5.0
3551       *
3552       * @param WP_User $user     The user.
3553       * @param string  $new_pass New user password.
3554       */
3555      do_action( 'password_reset', $user, $new_pass );
3556  
3557      wp_set_password( $new_pass, $user->ID );
3558      update_user_meta( $user->ID, 'default_password_nag', false );
3559  
3560      /**
3561       * Fires after the user's password is reset.
3562       *
3563       * @since 4.4.0
3564       *
3565       * @param WP_User $user     The user.
3566       * @param string  $new_pass New user password.
3567       */
3568      do_action( 'after_password_reset', $user, $new_pass );
3569  }
3570  
3571  /**
3572   * Handles registering a new user.
3573   *
3574   * @since 2.5.0
3575   *
3576   * @param string $user_login User's username for logging in
3577   * @param string $user_email User's email address to send password and add
3578   * @return int|WP_Error Either user's ID or error on failure.
3579   */
3580  function register_new_user( $user_login, $user_email ) {
3581      $errors = new WP_Error();
3582  
3583      $sanitized_user_login = sanitize_user( $user_login );
3584      /**
3585       * Filters the email address of a user being registered.
3586       *
3587       * @since 2.1.0
3588       *
3589       * @param string $user_email The email address of the new user.
3590       */
3591      $user_email = apply_filters( 'user_registration_email', $user_email );
3592  
3593      // Check the username.
3594      if ( '' === $sanitized_user_login ) {
3595          $errors->add( 'empty_username', __( '<strong>Error:</strong> Please enter a username.' ) );
3596      } elseif ( ! validate_username( $user_login ) ) {
3597          $errors->add( 'invalid_username', __( '<strong>Error:</strong> This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
3598          $sanitized_user_login = '';
3599      } elseif ( username_exists( $sanitized_user_login ) ) {
3600          $errors->add( 'username_exists', __( '<strong>Error:</strong> This username is already registered. Please choose another one.' ) );
3601      } else {
3602          /** This filter is documented in wp-includes/user.php */
3603          $illegal_user_logins = (array) apply_filters( 'illegal_user_logins', array() );
3604          if ( in_array( strtolower( $sanitized_user_login ), array_map( 'strtolower', $illegal_user_logins ), true ) ) {
3605              $errors->add( 'invalid_username', __( '<strong>Error:</strong> Sorry, that username is not allowed.' ) );
3606          }
3607      }
3608  
3609      // Check the email address.
3610      if ( '' === $user_email ) {
3611          $errors->add( 'empty_email', __( '<strong>Error:</strong> Please type your email address.' ) );
3612      } elseif ( ! is_email( $user_email ) ) {
3613          $errors->add( 'invalid_email', __( '<strong>Error:</strong> The email address is not correct.' ) );
3614          $user_email = '';
3615      } elseif ( email_exists( $user_email ) ) {
3616          $errors->add(
3617              'email_exists',
3618              sprintf(
3619                  /* translators: %s: Link to the login page. */
3620                  __( '<strong>Error:</strong> This email address is already registered. <a href="%s">Log in</a> with this address or choose another one.' ),
3621                  esc_url( wp_login_url() )
3622              )
3623          );
3624      }
3625  
3626      /**
3627       * Fires when submitting registration form data, before the user is created.
3628       *
3629       * @since 2.1.0
3630       *
3631       * @param string   $sanitized_user_login The submitted username after being sanitized.
3632       * @param string   $user_email           The submitted email.
3633       * @param WP_Error $errors               Contains any errors with submitted username and email,
3634       *                                       e.g., an empty field, an invalid username or email,
3635       *                                       or an existing username or email.
3636       */
3637      do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
3638  
3639      /**
3640       * Filters the errors encountered when a new user is being registered.
3641       *
3642       * The filtered WP_Error object may, for example, contain errors for an invalid
3643       * or existing username or email address. A WP_Error object should always be returned,
3644       * but may or may not contain errors.
3645       *
3646       * If any errors are present in $errors, this will abort the user's registration.
3647       *
3648       * @since 2.1.0
3649       *
3650       * @param WP_Error $errors               A WP_Error object containing any errors encountered
3651       *                                       during registration.
3652       * @param string   $sanitized_user_login User's username after it has been sanitized.
3653       * @param string   $user_email           User's email.
3654       */
3655      $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
3656  
3657      if ( $errors->has_errors() ) {
3658          return $errors;
3659      }
3660  
3661      $user_pass = wp_generate_password( 12, false );
3662      $user_id   = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
3663      if ( ! $user_id || is_wp_error( $user_id ) ) {
3664          $errors->add(
3665              'registerfail',
3666              sprintf(
3667                  /* translators: %s: Admin email address. */
3668                  __( '<strong>Error:</strong> Could not register you&hellip; please contact the <a href="mailto:%s">site admin</a>!' ),
3669                  esc_attr( get_option( 'admin_email' ) )
3670              )
3671          );
3672          return $errors;
3673      }
3674  
3675      update_user_meta( $user_id, 'default_password_nag', true ); // Set up the password change nag.
3676  
3677      if ( ! empty( $_COOKIE['wp_lang'] ) ) {
3678          $wp_lang = sanitize_text_field( $_COOKIE['wp_lang'] );
3679          if ( in_array( $wp_lang, get_available_languages(), true ) ) {
3680              update_user_meta( $user_id, 'locale', $wp_lang ); // Set user locale if defined on registration.
3681          }
3682      }
3683  
3684      /**
3685       * Fires after a new user registration has been recorded.
3686       *
3687       * @since 4.4.0
3688       *
3689       * @param int $user_id ID of the newly registered user.
3690       */
3691      do_action( 'register_new_user', $user_id );
3692  
3693      return $user_id;
3694  }
3695  
3696  /**
3697   * Initiates email notifications related to the creation of new users.
3698   *
3699   * Notifications are sent both to the site admin and to the newly created user.
3700   *
3701   * @since 4.4.0
3702   * @since 4.6.0 Converted the `$notify` parameter to accept 'user' for sending
3703   *              notifications only to the user created.
3704   *
3705   * @param int    $user_id ID of the newly created user.
3706   * @param string $notify  Optional. Type of notification that should happen. Accepts 'admin'
3707   *                        or an empty string (admin only), 'user', or 'both' (admin and user).
3708   *                        Default 'both'.
3709   */
3710  function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {
3711      wp_new_user_notification( $user_id, null, $notify );
3712  }
3713  
3714  /**
3715   * Retrieves the current session token from the logged_in cookie.
3716   *
3717   * @since 4.0.0
3718   *
3719   * @return string Token.
3720   */
3721  function wp_get_session_token() {
3722      $cookie = wp_parse_auth_cookie( '', 'logged_in' );
3723      return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
3724  }
3725  
3726  /**
3727   * Retrieves a list of sessions for the current user.
3728   *
3729   * @since 4.0.0
3730   *
3731   * @return array Array of sessions.
3732   */
3733  function wp_get_all_sessions() {
3734      $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3735      return $manager->get_all();
3736  }
3737  
3738  /**
3739   * Removes the current session token from the database.
3740   *
3741   * @since 4.0.0
3742   */
3743  function wp_destroy_current_session() {
3744      $token = wp_get_session_token();
3745      if ( $token ) {
3746          $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3747          $manager->destroy( $token );
3748      }
3749  }
3750  
3751  /**
3752   * Removes all but the current session token for the current user for the database.
3753   *
3754   * @since 4.0.0
3755   */
3756  function wp_destroy_other_sessions() {
3757      $token = wp_get_session_token();
3758      if ( $token ) {
3759          $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3760          $manager->destroy_others( $token );
3761      }
3762  }
3763  
3764  /**
3765   * Removes all session tokens for the current user from the database.
3766   *
3767   * @since 4.0.0
3768   */
3769  function wp_destroy_all_sessions() {
3770      $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3771      $manager->destroy_all();
3772  }
3773  
3774  /**
3775   * Gets the user IDs of all users with no role on this site.
3776   *
3777   * @since 4.4.0
3778   * @since 4.9.0 The `$site_id` parameter was added to support multisite.
3779   *
3780   * @global wpdb $wpdb WordPress database abstraction object.
3781   *
3782   * @param int|null $site_id Optional. The site ID to get users with no role for. Defaults to the current site.
3783   * @return string[] Array of user IDs as strings.
3784   */
3785  function wp_get_users_with_no_role( $site_id = null ) {
3786      global $wpdb;
3787  
3788      if ( ! $site_id ) {
3789          $site_id = get_current_blog_id();
3790      }
3791  
3792      $prefix = $wpdb->get_blog_prefix( $site_id );
3793  
3794      if ( is_multisite() && get_current_blog_id() !== $site_id ) {
3795          switch_to_blog( $site_id );
3796          $role_names = wp_roles()->get_names();
3797          restore_current_blog();
3798      } else {
3799          $role_names = wp_roles()->get_names();
3800      }
3801  
3802      $regex = implode( '|', array_keys( $role_names ) );
3803      $regex = preg_replace( '/[^a-zA-Z_\|-]/', '', $regex );
3804      $users = $wpdb->get_col(
3805          $wpdb->prepare(
3806              "SELECT user_id
3807              FROM $wpdb->usermeta
3808              WHERE meta_key = '{$prefix}capabilities'
3809              AND meta_value NOT REGEXP %s",
3810              $regex
3811          )
3812      );
3813  
3814      return $users;
3815  }
3816  
3817  /**
3818   * Retrieves the current user object.
3819   *
3820   * Will set the current user, if the current user is not set. The current user
3821   * will be set to the logged-in person. If no user is logged-in, then it will
3822   * set the current user to 0, which is invalid and won't have any permissions.
3823   *
3824   * This function is used by the pluggable functions wp_get_current_user() and
3825   * get_currentuserinfo(), the latter of which is deprecated but used for backward
3826   * compatibility.
3827   *
3828   * @since 4.5.0
3829   * @access private
3830   *
3831   * @see wp_get_current_user()
3832   * @global WP_User $current_user Checks if the current user is set.
3833   *
3834   * @return WP_User Current WP_User instance.
3835   */
3836  function _wp_get_current_user() {
3837      global $current_user;
3838  
3839      if ( ! empty( $current_user ) ) {
3840          if ( $current_user instanceof WP_User ) {
3841              return $current_user;
3842          }
3843  
3844          // Upgrade stdClass to WP_User.
3845          if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
3846              $cur_id       = $current_user->ID;
3847              $current_user = null;
3848              wp_set_current_user( $cur_id );
3849              return $current_user;
3850          }
3851  
3852          // $current_user has a junk value. Force to WP_User with ID 0.
3853          $current_user = null;
3854          wp_set_current_user( 0 );
3855          return $current_user;
3856      }
3857  
3858      if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
3859          wp_set_current_user( 0 );
3860          return $current_user;
3861      }
3862  
3863      /**
3864       * Filters the current user.
3865       *
3866       * The default filters use this to determine the current user from the
3867       * request's cookies, if available.
3868       *
3869       * Returning a value of false will effectively short-circuit setting
3870       * the current user.
3871       *
3872       * @since 3.9.0
3873       *
3874       * @param int|false $user_id User ID if one has been determined, false otherwise.
3875       */
3876      $user_id = apply_filters( 'determine_current_user', false );
3877      if ( ! $user_id ) {
3878          wp_set_current_user( 0 );
3879          return $current_user;
3880      }
3881  
3882      wp_set_current_user( $user_id );
3883  
3884      return $current_user;
3885  }
3886  
3887  /**
3888   * Sends a confirmation request email when a change of user email address is attempted.
3889   *
3890   * @since 3.0.0
3891   * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
3892   * @since 7.0.3 Added the `$user_id` parameter, which is sent with the `personal_options_update` action.
3893   *
3894   * @global WP_Error $errors WP_Error object.
3895   *
3896   * @param int $user_id Optional. The ID of the user whose email is being changed. Defaults to `$_POST['user_id']` if set, otherwise 0.
3897   */
3898  function send_confirmation_on_profile_email( $user_id = 0 ) {
3899      global $errors;
3900  
3901      // Maintain backward compatibility for those relying on a check based on $_POST['user_id'].
3902      if ( ! $user_id && isset( $_POST['user_id'] ) ) {
3903          $user_id = absint( $_POST['user_id'] );
3904      }
3905  
3906      $current_user = wp_get_current_user();
3907      if ( ! is_object( $errors ) ) {
3908          $errors = new WP_Error();
3909      }
3910  
3911      if ( 0 === $current_user->ID || $current_user->ID !== (int) $user_id ) {
3912          return false;
3913      }
3914  
3915      if ( $current_user->user_email !== $_POST['email'] ) {
3916          if ( ! is_email( $_POST['email'] ) ) {
3917              $errors->add(
3918                  'user_email',
3919                  __( '<strong>Error:</strong> The email address is not correct.' ),
3920                  array(
3921                      'form-field' => 'email',
3922                  )
3923              );
3924  
3925              $_POST['email'] = addslashes( $current_user->user_email );
3926              return;
3927          }
3928  
3929          if ( email_exists( $_POST['email'] ) ) {
3930              $errors->add(
3931                  'user_email',
3932                  __( '<strong>Error:</strong> The email address is already used.' ),
3933                  array(
3934                      'form-field' => 'email',
3935                  )
3936              );
3937              delete_user_meta( $current_user->ID, '_new_email' );
3938  
3939              $_POST['email'] = addslashes( $current_user->user_email );
3940              return;
3941          }
3942  
3943          $hash           = md5( $_POST['email'] . time() . wp_rand() );
3944          $new_user_email = array(
3945              'hash'     => $hash,
3946              'newemail' => $_POST['email'],
3947          );
3948          update_user_meta( $current_user->ID, '_new_email', $new_user_email );
3949  
3950          $sitename = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
3951  
3952          /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */
3953          $email_text = __(
3954              'Howdy ###USERNAME###,
3955  
3956  You recently requested to have the email address on your account changed.
3957  
3958  If this is correct, please click on the following link to change it:
3959  ###ADMIN_URL###
3960  
3961  You can safely ignore and delete this email if you do not want to
3962  take this action.
3963  
3964  This email has been sent to ###EMAIL###
3965  
3966  Regards,
3967  All at ###SITENAME###
3968  ###SITEURL###'
3969          );
3970  
3971          /**
3972           * Filters the text of the email sent when a change of user email address is attempted.
3973           *
3974           * The following strings have a special meaning and will get replaced dynamically:
3975           *
3976           *  - `###USERNAME###`  The current user's username.
3977           *  - `###ADMIN_URL###` The link to click on to confirm the email change.
3978           *  - `###EMAIL###`     The new email.
3979           *  - `###SITENAME###`  The name of the site.
3980           *  - `###SITEURL###`   The URL to the site.
3981           *
3982           * @since MU (3.0.0)
3983           * @since 4.9.0 This filter is no longer Multisite specific.
3984           *
3985           * @param string $email_text     Text in the email.
3986           * @param array  $new_user_email {
3987           *     Data relating to the new user email address.
3988           *
3989           *     @type string $hash     The secure hash used in the confirmation link URL.
3990           *     @type string $newemail The proposed new email address.
3991           * }
3992           */
3993          $content = apply_filters( 'new_user_email_content', $email_text, $new_user_email );
3994  
3995          $content = str_replace( '###USERNAME###', $current_user->user_login, $content );
3996          $content = str_replace( '###ADMIN_URL###', esc_url( self_admin_url( 'profile.php?newuseremail=' . $hash ) ), $content );
3997          $content = str_replace( '###EMAIL###', $_POST['email'], $content );
3998          $content = str_replace( '###SITENAME###', $sitename, $content );
3999          $content = str_replace( '###SITEURL###', home_url(), $content );
4000  
4001          /* translators: New email address notification email subject. %s: Site title. */
4002          wp_mail( $_POST['email'], sprintf( __( '[%s] Email Change Request' ), $sitename ), $content );
4003  
4004          $_POST['email'] = $current_user->user_email;
4005      }
4006  }
4007  
4008  /**
4009   * Adds an admin notice alerting the user to check for confirmation request email
4010   * after email address change.
4011   *
4012   * @since 3.0.0
4013   * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
4014   * @since 7.2.0 The notice is displayed whenever an email change is pending, not only after updating
4015   *              the profile, and includes a link to cancel the request. The function is no longer
4016   *              hooked to the `admin_notices`, `user_admin_notices`, and `network_admin_notices`
4017   *              actions, and is instead called directly from wp-admin/user-edit.php.
4018   *
4019   * @global string $pagenow The filename of the current screen.
4020   */
4021  function new_user_email_admin_notice() {
4022      global $pagenow;
4023  
4024      if ( 'profile.php' === $pagenow ) {
4025          $current_user_id = get_current_user_id();
4026          $email           = get_user_meta( $current_user_id, '_new_email', true );
4027          if ( $email ) {
4028              $message = sprintf(
4029                  /* translators: %s: New email address. */
4030                  __( 'Your email address has not been updated yet. Please check your inbox at %s for a confirmation email.' ),
4031                  '<code>' . esc_html( $email['newemail'] ) . '</code>'
4032              );
4033              $message .= sprintf(
4034                  ' <a href="%1$s">%2$s</a>',
4035                  esc_url( wp_nonce_url( self_admin_url( 'profile.php?dismiss=' . $current_user_id . '_new_email' ), 'dismiss-' . $current_user_id . '_new_email' ) ),
4036                  _x( 'Cancel request', 'user email change' )
4037              );
4038              wp_admin_notice( $message, array( 'type' => 'info' ) );
4039          }
4040      }
4041  }
4042  
4043  /**
4044   * Gets all personal data request types.
4045   *
4046   * @since 4.9.6
4047   * @access private
4048   *
4049   * @return string[] List of core privacy action types.
4050   */
4051  function _wp_privacy_action_request_types() {
4052      return array(
4053          'export_personal_data',
4054          'remove_personal_data',
4055      );
4056  }
4057  
4058  /**
4059   * Registers the personal data exporter for users.
4060   *
4061   * @since 4.9.6
4062   *
4063   * @param array[] $exporters An array of personal data exporters.
4064   * @return array[] An array of personal data exporters.
4065   */
4066  function wp_register_user_personal_data_exporter( $exporters ) {
4067      $exporters['wordpress-user'] = array(
4068          'exporter_friendly_name' => __( 'WordPress User' ),
4069          'callback'               => 'wp_user_personal_data_exporter',
4070      );
4071  
4072      return $exporters;
4073  }
4074  
4075  /**
4076   * Finds and exports personal data associated with an email address from the user and user_meta table.
4077   *
4078   * @since 4.9.6
4079   * @since 5.4.0 Added 'Community Events Location' group to the export data.
4080   * @since 5.4.0 Added 'Session Tokens' group to the export data.
4081   *
4082   * @param string $email_address  The user's email address.
4083   * @return array {
4084   *     An array of personal data.
4085   *
4086   *     @type array[] $data An array of personal data arrays.
4087   *     @type bool    $done Whether the exporter is finished.
4088   * }
4089   */
4090  function wp_user_personal_data_exporter( $email_address ) {
4091      $email_address = trim( $email_address );
4092  
4093      $data_to_export = array();
4094  
4095      $user = get_user_by( 'email', $email_address );
4096  
4097      if ( ! $user ) {
4098          return array(
4099              'data' => array(),
4100              'done' => true,
4101          );
4102      }
4103  
4104      $user_meta = get_user_meta( $user->ID );
4105  
4106      $user_props_to_export = array(
4107          'ID'              => __( 'User ID' ),
4108          'user_login'      => __( 'User Login Name' ),
4109          'user_nicename'   => __( 'User Nice Name' ),
4110          'user_email'      => __( 'User Email' ),
4111          'user_url'        => __( 'User URL' ),
4112          'user_registered' => __( 'User Registration Date' ),
4113          'display_name'    => __( 'User Display Name' ),
4114          'nickname'        => __( 'User Nickname' ),
4115          'first_name'      => __( 'User First Name' ),
4116          'last_name'       => __( 'User Last Name' ),
4117          'description'     => __( 'User Description' ),
4118      );
4119  
4120      $user_data_to_export = array();
4121  
4122      foreach ( $user_props_to_export as $key => $name ) {
4123          $value = '';
4124  
4125          switch ( $key ) {
4126              case 'ID':
4127              case 'user_login':
4128              case 'user_nicename':
4129              case 'user_email':
4130              case 'user_url':
4131              case 'user_registered':
4132              case 'display_name':
4133                  $value = $user->data->$key;
4134                  break;
4135              case 'nickname':
4136              case 'first_name':
4137              case 'last_name':
4138              case 'description':
4139                  $value = $user_meta[ $key ][0];
4140                  break;
4141          }
4142  
4143          if ( ! empty( $value ) ) {
4144              $user_data_to_export[] = array(
4145                  'name'  => $name,
4146                  'value' => $value,
4147              );
4148          }
4149      }
4150  
4151      // Get the list of reserved names.
4152      $reserved_names = array_values( $user_props_to_export );
4153  
4154      /**
4155       * Filters the user's profile data for the privacy exporter.
4156       *
4157       * @since 5.4.0
4158       *
4159       * @param array    $additional_user_profile_data {
4160       *     An array of name-value pairs of additional user data items. Default empty array.
4161       *
4162       *     @type string $name  The user-facing name of an item name-value pair,e.g. 'IP Address'.
4163       *     @type string $value The user-facing value of an item data pair, e.g. '50.60.70.0'.
4164       * }
4165       * @param WP_User  $user           The user whose data is being exported.
4166       * @param string[] $reserved_names An array of reserved names. Any item in `$additional_user_data`
4167       *                                 that uses one of these for its `name` will not be included in the export.
4168       */
4169      $_extra_data = apply_filters( 'wp_privacy_additional_user_profile_data', array(), $user, $reserved_names );
4170  
4171      if ( is_array( $_extra_data ) && ! empty( $_extra_data ) ) {
4172          // Remove items that use reserved names.
4173          $extra_data = array_filter(
4174              $_extra_data,
4175              static function ( $item ) use ( $reserved_names ) {
4176                  return ! in_array( $item['name'], $reserved_names, true );
4177              }
4178          );
4179  
4180          if ( count( $extra_data ) !== count( $_extra_data ) ) {
4181              _doing_it_wrong(
4182                  __FUNCTION__,
4183                  sprintf(
4184                      /* translators: %s: wp_privacy_additional_user_profile_data */
4185                      __( 'Filter %s returned items with reserved names.' ),
4186                      '<code>wp_privacy_additional_user_profile_data</code>'
4187                  ),
4188                  '5.4.0'
4189              );
4190          }
4191  
4192          if ( ! empty( $extra_data ) ) {
4193              $user_data_to_export = array_merge( $user_data_to_export, $extra_data );
4194          }
4195      }
4196  
4197      $data_to_export[] = array(
4198          'group_id'          => 'user',
4199          'group_label'       => __( 'User' ),
4200          'group_description' => __( 'User&#8217;s profile data.' ),
4201          'item_id'           => "user-{$user->ID}",
4202          'data'              => $user_data_to_export,
4203      );
4204  
4205      if ( isset( $user_meta['community-events-location'] ) ) {
4206          $location = maybe_unserialize( $user_meta['community-events-location'][0] );
4207  
4208          $location_props_to_export = array(
4209              'description' => __( 'City' ),
4210              'country'     => __( 'Country' ),
4211              'latitude'    => __( 'Latitude' ),
4212              'longitude'   => __( 'Longitude' ),
4213              'ip'          => __( 'IP' ),
4214          );
4215  
4216          $location_data_to_export = array();
4217  
4218          foreach ( $location_props_to_export as $key => $name ) {
4219              if ( ! empty( $location[ $key ] ) ) {
4220                  $location_data_to_export[] = array(
4221                      'name'  => $name,
4222                      'value' => $location[ $key ],
4223                  );
4224              }
4225          }
4226  
4227          $data_to_export[] = array(
4228              'group_id'          => 'community-events-location',
4229              'group_label'       => __( 'Community Events Location' ),
4230              'group_description' => __( 'User&#8217;s location data used for the Community Events in the WordPress Events and News dashboard widget.' ),
4231              'item_id'           => "community-events-location-{$user->ID}",
4232              'data'              => $location_data_to_export,
4233          );
4234      }
4235  
4236      if ( isset( $user_meta['session_tokens'] ) ) {
4237          $session_tokens = maybe_unserialize( $user_meta['session_tokens'][0] );
4238  
4239          $session_tokens_props_to_export = array(
4240              'expiration' => __( 'Expiration' ),
4241              'ip'         => __( 'IP' ),
4242              'ua'         => __( 'User Agent' ),
4243              'login'      => __( 'Last Login' ),
4244          );
4245  
4246          foreach ( $session_tokens as $token_key => $session_token ) {
4247              $session_tokens_data_to_export = array();
4248  
4249              foreach ( $session_tokens_props_to_export as $key => $name ) {
4250                  if ( ! empty( $session_token[ $key ] ) ) {
4251                      $value = $session_token[ $key ];
4252                      if ( in_array( $key, array( 'expiration', 'login' ), true ) ) {
4253                          $value = date_i18n( 'F d, Y H:i A', $value );
4254                      }
4255                      $session_tokens_data_to_export[] = array(
4256                          'name'  => $name,
4257                          'value' => $value,
4258                      );
4259                  }
4260              }
4261  
4262              $data_to_export[] = array(
4263                  'group_id'          => 'session-tokens',
4264                  'group_label'       => __( 'Session Tokens' ),
4265                  'group_description' => __( 'User&#8217;s Session Tokens data.' ),
4266                  'item_id'           => "session-tokens-{$user->ID}-{$token_key}",
4267                  'data'              => $session_tokens_data_to_export,
4268              );
4269          }
4270      }
4271  
4272      return array(
4273          'data' => $data_to_export,
4274          'done' => true,
4275      );
4276  }
4277  
4278  /**
4279   * Updates log when privacy request is confirmed.
4280   *
4281   * @since 4.9.6
4282   * @access private
4283   *
4284   * @param int $request_id ID of the request.
4285   */
4286  function _wp_privacy_account_request_confirmed( $request_id ) {
4287      $request = wp_get_user_request( $request_id );
4288  
4289      if ( ! $request ) {
4290          return;
4291      }
4292  
4293      if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
4294          return;
4295      }
4296  
4297      update_post_meta( $request_id, '_wp_user_request_confirmed_timestamp', time() );
4298      wp_update_post(
4299          array(
4300              'ID'          => $request_id,
4301              'post_status' => 'request-confirmed',
4302          )
4303      );
4304  }
4305  
4306  /**
4307   * Notifies the site administrator via email when a request is confirmed.
4308   *
4309   * Without this, the admin would have to manually check the site to see if any
4310   * action was needed on their part yet.
4311   *
4312   * @since 4.9.6
4313   *
4314   * @param int $request_id The ID of the request.
4315   */
4316  function _wp_privacy_send_request_confirmation_notification( $request_id ) {
4317      $request = wp_get_user_request( $request_id );
4318  
4319      if ( ! ( $request instanceof WP_User_Request ) || 'request-confirmed' !== $request->status ) {
4320          return;
4321      }
4322  
4323      $already_notified = (bool) get_post_meta( $request_id, '_wp_admin_notified', true );
4324  
4325      if ( $already_notified ) {
4326          return;
4327      }
4328  
4329      if ( 'export_personal_data' === $request->action_name ) {
4330          $manage_url = admin_url( 'export-personal-data.php' );
4331      } elseif ( 'remove_personal_data' === $request->action_name ) {
4332          $manage_url = admin_url( 'erase-personal-data.php' );
4333      }
4334      $action_description = wp_user_request_action_description( $request->action_name );
4335  
4336      /**
4337       * Filters the recipient of the data request confirmation notification.
4338       *
4339       * In a Multisite environment, this will default to the email address of the
4340       * network admin because, by default, single site admins do not have the
4341       * capabilities required to process requests. Some networks may wish to
4342       * delegate those capabilities to a single-site admin, or a dedicated person
4343       * responsible for managing privacy requests.
4344       *
4345       * @since 4.9.6
4346       *
4347       * @param string          $admin_email The email address of the notification recipient.
4348       * @param WP_User_Request $request     The request that is initiating the notification.
4349       */
4350      $admin_email = apply_filters( 'user_request_confirmed_email_to', get_site_option( 'admin_email' ), $request );
4351  
4352      $email_data = array(
4353          'request'     => $request,
4354          'user_email'  => $request->email,
4355          'description' => $action_description,
4356          'manage_url'  => $manage_url,
4357          'sitename'    => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
4358          'siteurl'     => home_url(),
4359          'admin_email' => $admin_email,
4360      );
4361  
4362      $subject = sprintf(
4363          /* translators: Privacy data request confirmed notification email subject. 1: Site title, 2: Name of the confirmed action. */
4364          __( '[%1$s] Action Confirmed: %2$s' ),
4365          $email_data['sitename'],
4366          $action_description
4367      );
4368  
4369      /**
4370       * Filters the subject of the user request confirmation email.
4371       *
4372       * @since 4.9.8
4373       *
4374       * @param string $subject    The email subject.
4375       * @param string $sitename   The name of the site.
4376       * @param array  $email_data {
4377       *     Data relating to the account action email.
4378       *
4379       *     @type WP_User_Request $request     User request object.
4380       *     @type string          $user_email  The email address confirming a request.
4381       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4382       *     @type string          $manage_url  The link to click manage privacy requests of this type.
4383       *     @type string          $sitename    The site name sending the mail.
4384       *     @type string          $siteurl     The site URL sending the mail.
4385       *     @type string          $admin_email The administrator email receiving the mail.
4386       * }
4387       */
4388      $subject = apply_filters( 'user_request_confirmed_email_subject', $subject, $email_data['sitename'], $email_data );
4389  
4390      /* translators: Do not translate SITENAME, USER_EMAIL, DESCRIPTION, MANAGE_URL, SITEURL; those are placeholders. */
4391      $content = __(
4392          'Howdy,
4393  
4394  A user data privacy request has been confirmed on ###SITENAME###:
4395  
4396  User: ###USER_EMAIL###
4397  Request: ###DESCRIPTION###
4398  
4399  You can view and manage these data privacy requests here:
4400  
4401  ###MANAGE_URL###
4402  
4403  Regards,
4404  All at ###SITENAME###
4405  ###SITEURL###'
4406      );
4407  
4408      /**
4409       * Filters the body of the user request confirmation email.
4410       *
4411       * The email is sent to an administrator when a user request is confirmed.
4412       *
4413       * The following strings have a special meaning and will get replaced dynamically:
4414       *
4415       *  - `###SITENAME###`    The name of the site.
4416       *  - `###USER_EMAIL###`  The user email for the request.
4417       *  - `###DESCRIPTION###` Description of the action being performed so the user knows what the email is for.
4418       *  - `###MANAGE_URL###`  The URL to manage requests.
4419       *  - `###SITEURL###`     The URL to the site.
4420       *
4421       * @since 4.9.6
4422       * @deprecated 5.8.0 Use {@see 'user_request_confirmed_email_content'} instead.
4423       *                   For user erasure fulfillment email content
4424       *                   use {@see 'user_erasure_fulfillment_email_content'} instead.
4425       *
4426       * @param string $content    The email content.
4427       * @param array  $email_data {
4428       *     Data relating to the account action email.
4429       *
4430       *     @type WP_User_Request $request     User request object.
4431       *     @type string          $user_email  The email address confirming a request.
4432       *     @type string          $description Description of the action being performed
4433       *                                        so the user knows what the email is for.
4434       *     @type string          $manage_url  The link to click manage privacy requests of this type.
4435       *     @type string          $sitename    The site name sending the mail.
4436       *     @type string          $siteurl     The site URL sending the mail.
4437       *     @type string          $admin_email The administrator email receiving the mail.
4438       * }
4439       */
4440      $content = apply_filters_deprecated(
4441          'user_confirmed_action_email_content',
4442          array( $content, $email_data ),
4443          '5.8.0',
4444          sprintf(
4445              /* translators: 1 & 2: Deprecation replacement options. */
4446              __( '%1$s or %2$s' ),
4447              'user_request_confirmed_email_content',
4448              'user_erasure_fulfillment_email_content'
4449          )
4450      );
4451  
4452      /**
4453       * Filters the body of the user request confirmation email.
4454       *
4455       * The email is sent to an administrator when a user request is confirmed.
4456       * The following strings have a special meaning and will get replaced dynamically:
4457       *
4458       *  - `###SITENAME###`    The name of the site.
4459       *  - `###USER_EMAIL###`  The user email for the request.
4460       *  - `###DESCRIPTION###` Description of the action being performed so the user knows what the email is for.
4461       *  - `###MANAGE_URL###`  The URL to manage requests.
4462       *  - `###SITEURL###`     The URL to the site.
4463       *
4464       * @since 5.8.0
4465       *
4466       * @param string $content    The email content.
4467       * @param array  $email_data {
4468       *     Data relating to the account action email.
4469       *
4470       *     @type WP_User_Request $request     User request object.
4471       *     @type string          $user_email  The email address confirming a request.
4472       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4473       *     @type string          $manage_url  The link to click manage privacy requests of this type.
4474       *     @type string          $sitename    The site name sending the mail.
4475       *     @type string          $siteurl     The site URL sending the mail.
4476       *     @type string          $admin_email The administrator email receiving the mail.
4477       * }
4478       */
4479      $content = apply_filters( 'user_request_confirmed_email_content', $content, $email_data );
4480  
4481      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
4482      $content = str_replace( '###USER_EMAIL###', $email_data['user_email'], $content );
4483      $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
4484      $content = str_replace( '###MANAGE_URL###', sanitize_url( $email_data['manage_url'] ), $content );
4485      $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content );
4486  
4487      $headers = '';
4488  
4489      /**
4490       * Filters the headers of the user request confirmation email.
4491       *
4492       * @since 5.4.0
4493       *
4494       * @param string|array $headers    The email headers.
4495       * @param string       $subject    The email subject.
4496       * @param string       $content    The email content.
4497       * @param int          $request_id The request ID.
4498       * @param array        $email_data {
4499       *     Data relating to the account action email.
4500       *
4501       *     @type WP_User_Request $request     User request object.
4502       *     @type string          $user_email  The email address confirming a request.
4503       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4504       *     @type string          $manage_url  The link to click manage privacy requests of this type.
4505       *     @type string          $sitename    The site name sending the mail.
4506       *     @type string          $siteurl     The site URL sending the mail.
4507       *     @type string          $admin_email The administrator email receiving the mail.
4508       * }
4509       */
4510      $headers = apply_filters( 'user_request_confirmed_email_headers', $headers, $subject, $content, $request_id, $email_data );
4511  
4512      $email_sent = wp_mail( $email_data['admin_email'], $subject, $content, $headers );
4513  
4514      if ( $email_sent ) {
4515          update_post_meta( $request_id, '_wp_admin_notified', true );
4516      }
4517  }
4518  
4519  /**
4520   * Notifies the user when their erasure request is fulfilled.
4521   *
4522   * Without this, the user would never know if their data was actually erased.
4523   *
4524   * @since 4.9.6
4525   *
4526   * @param int $request_id The privacy request post ID associated with this request.
4527   */
4528  function _wp_privacy_send_erasure_fulfillment_notification( $request_id ) {
4529      $request = wp_get_user_request( $request_id );
4530  
4531      if ( ! ( $request instanceof WP_User_Request ) || 'request-completed' !== $request->status ) {
4532          return;
4533      }
4534  
4535      $already_notified = (bool) get_post_meta( $request_id, '_wp_user_notified', true );
4536  
4537      if ( $already_notified ) {
4538          return;
4539      }
4540  
4541      // Localize message content for user; fallback to site default for visitors.
4542      if ( ! empty( $request->user_id ) ) {
4543          $switched_locale = switch_to_user_locale( $request->user_id );
4544      } else {
4545          $switched_locale = switch_to_locale( get_locale() );
4546      }
4547  
4548      /**
4549       * Filters the recipient of the data erasure fulfillment notification.
4550       *
4551       * @since 4.9.6
4552       *
4553       * @param string          $user_email The email address of the notification recipient.
4554       * @param WP_User_Request $request    The request that is initiating the notification.
4555       */
4556      $user_email = apply_filters( 'user_erasure_fulfillment_email_to', $request->email, $request );
4557  
4558      $email_data = array(
4559          'request'            => $request,
4560          'message_recipient'  => $user_email,
4561          'privacy_policy_url' => get_privacy_policy_url(),
4562          'sitename'           => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
4563          'siteurl'            => home_url(),
4564      );
4565  
4566      $subject = sprintf(
4567          /* translators: Erasure request fulfilled notification email subject. %s: Site title. */
4568          __( '[%s] Erasure Request Fulfilled' ),
4569          $email_data['sitename']
4570      );
4571  
4572      /**
4573       * Filters the subject of the email sent when an erasure request is completed.
4574       *
4575       * @since 4.9.8
4576       * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_subject'} instead.
4577       *
4578       * @param string $subject    The email subject.
4579       * @param string $sitename   The name of the site.
4580       * @param array  $email_data {
4581       *     Data relating to the account action email.
4582       *
4583       *     @type WP_User_Request $request            User request object.
4584       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4585       *                                               to the value of `$request->email`, but can be changed
4586       *                                               by the `user_erasure_fulfillment_email_to` filter.
4587       *     @type string          $privacy_policy_url Privacy policy URL.
4588       *     @type string          $sitename           The site name sending the mail.
4589       *     @type string          $siteurl            The site URL sending the mail.
4590       * }
4591       */
4592      $subject = apply_filters_deprecated(
4593          'user_erasure_complete_email_subject',
4594          array( $subject, $email_data['sitename'], $email_data ),
4595          '5.8.0',
4596          'user_erasure_fulfillment_email_subject'
4597      );
4598  
4599      /**
4600       * Filters the subject of the email sent when an erasure request is completed.
4601       *
4602       * @since 5.8.0
4603       *
4604       * @param string $subject    The email subject.
4605       * @param string $sitename   The name of the site.
4606       * @param array  $email_data {
4607       *     Data relating to the account action email.
4608       *
4609       *     @type WP_User_Request $request            User request object.
4610       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4611       *                                               to the value of `$request->email`, but can be changed
4612       *                                               by the `user_erasure_fulfillment_email_to` filter.
4613       *     @type string          $privacy_policy_url Privacy policy URL.
4614       *     @type string          $sitename           The site name sending the mail.
4615       *     @type string          $siteurl            The site URL sending the mail.
4616       * }
4617       */
4618      $subject = apply_filters( 'user_erasure_fulfillment_email_subject', $subject, $email_data['sitename'], $email_data );
4619  
4620      /* translators: Do not translate SITENAME, SITEURL; those are placeholders. */
4621      $content = __(
4622          'Howdy,
4623  
4624  Your request to erase your personal data on ###SITENAME### has been completed.
4625  
4626  If you have any follow-up questions or concerns, please contact the site administrator.
4627  
4628  Regards,
4629  All at ###SITENAME###
4630  ###SITEURL###'
4631      );
4632  
4633      if ( ! empty( $email_data['privacy_policy_url'] ) ) {
4634          /* translators: Do not translate SITENAME, SITEURL, PRIVACY_POLICY_URL; those are placeholders. */
4635          $content = __(
4636              'Howdy,
4637  
4638  Your request to erase your personal data on ###SITENAME### has been completed.
4639  
4640  If you have any follow-up questions or concerns, please contact the site administrator.
4641  
4642  For more information, you can also read our privacy policy: ###PRIVACY_POLICY_URL###
4643  
4644  Regards,
4645  All at ###SITENAME###
4646  ###SITEURL###'
4647          );
4648      }
4649  
4650      /**
4651       * Filters the body of the data erasure fulfillment notification.
4652       *
4653       * The email is sent to a user when their data erasure request is fulfilled
4654       * by an administrator.
4655       *
4656       * The following strings have a special meaning and will get replaced dynamically:
4657       *
4658       *  - `###SITENAME###`           The name of the site.
4659       *  - `###PRIVACY_POLICY_URL###` Privacy policy page URL.
4660       *  - `###SITEURL###`            The URL to the site.
4661       *
4662       * @since 4.9.6
4663       * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_content'} instead.
4664       *                   For user request confirmation email content
4665       *                   use {@see 'user_request_confirmed_email_content'} instead.
4666       *
4667       * @param string $content The email content.
4668       * @param array  $email_data {
4669       *     Data relating to the account action email.
4670       *
4671       *     @type WP_User_Request $request            User request object.
4672       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4673       *                                               to the value of `$request->email`, but can be changed
4674       *                                               by the `user_erasure_fulfillment_email_to` filter.
4675       *     @type string          $privacy_policy_url Privacy policy URL.
4676       *     @type string          $sitename           The site name sending the mail.
4677       *     @type string          $siteurl            The site URL sending the mail.
4678       * }
4679       */
4680      $content = apply_filters_deprecated(
4681          'user_confirmed_action_email_content',
4682          array( $content, $email_data ),
4683          '5.8.0',
4684          sprintf(
4685              /* translators: 1 & 2: Deprecation replacement options. */
4686              __( '%1$s or %2$s' ),
4687              'user_erasure_fulfillment_email_content',
4688              'user_request_confirmed_email_content'
4689          )
4690      );
4691  
4692      /**
4693       * Filters the body of the data erasure fulfillment notification.
4694       *
4695       * The email is sent to a user when their data erasure request is fulfilled
4696       * by an administrator.
4697       *
4698       * The following strings have a special meaning and will get replaced dynamically:
4699       *
4700       *  - `###SITENAME###`           The name of the site.
4701       *  - `###PRIVACY_POLICY_URL###` Privacy policy page URL.
4702       *  - `###SITEURL###`            The URL to the site.
4703       *
4704       * @since 5.8.0
4705       *
4706       * @param string $content The email content.
4707       * @param array  $email_data {
4708       *     Data relating to the account action email.
4709       *
4710       *     @type WP_User_Request $request            User request object.
4711       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4712       *                                               to the value of `$request->email`, but can be changed
4713       *                                               by the `user_erasure_fulfillment_email_to` filter.
4714       *     @type string          $privacy_policy_url Privacy policy URL.
4715       *     @type string          $sitename           The site name sending the mail.
4716       *     @type string          $siteurl            The site URL sending the mail.
4717       * }
4718       */
4719      $content = apply_filters( 'user_erasure_fulfillment_email_content', $content, $email_data );
4720  
4721      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
4722      $content = str_replace( '###PRIVACY_POLICY_URL###', $email_data['privacy_policy_url'], $content );
4723      $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content );
4724  
4725      $headers = '';
4726  
4727      /**
4728       * Filters the headers of the data erasure fulfillment notification.
4729       *
4730       * @since 5.4.0
4731       * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_headers'} instead.
4732       *
4733       * @param string|array $headers    The email headers.
4734       * @param string       $subject    The email subject.
4735       * @param string       $content    The email content.
4736       * @param int          $request_id The request ID.
4737       * @param array        $email_data {
4738       *     Data relating to the account action email.
4739       *
4740       *     @type WP_User_Request $request            User request object.
4741       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4742       *                                               to the value of `$request->email`, but can be changed
4743       *                                               by the `user_erasure_fulfillment_email_to` filter.
4744       *     @type string          $privacy_policy_url Privacy policy URL.
4745       *     @type string          $sitename           The site name sending the mail.
4746       *     @type string          $siteurl            The site URL sending the mail.
4747       * }
4748       */
4749      $headers = apply_filters_deprecated(
4750          'user_erasure_complete_email_headers',
4751          array( $headers, $subject, $content, $request_id, $email_data ),
4752          '5.8.0',
4753          'user_erasure_fulfillment_email_headers'
4754      );
4755  
4756      /**
4757       * Filters the headers of the data erasure fulfillment notification.
4758       *
4759       * @since 5.8.0
4760       *
4761       * @param string|array $headers    The email headers.
4762       * @param string       $subject    The email subject.
4763       * @param string       $content    The email content.
4764       * @param int          $request_id The request ID.
4765       * @param array        $email_data {
4766       *     Data relating to the account action email.
4767       *
4768       *     @type WP_User_Request $request            User request object.
4769       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4770       *                                               to the value of `$request->email`, but can be changed
4771       *                                               by the `user_erasure_fulfillment_email_to` filter.
4772       *     @type string          $privacy_policy_url Privacy policy URL.
4773       *     @type string          $sitename           The site name sending the mail.
4774       *     @type string          $siteurl            The site URL sending the mail.
4775       * }
4776       */
4777      $headers = apply_filters( 'user_erasure_fulfillment_email_headers', $headers, $subject, $content, $request_id, $email_data );
4778  
4779      $email_sent = wp_mail( $user_email, $subject, $content, $headers );
4780  
4781      if ( $switched_locale ) {
4782          restore_previous_locale();
4783      }
4784  
4785      if ( $email_sent ) {
4786          update_post_meta( $request_id, '_wp_user_notified', true );
4787      }
4788  }
4789  
4790  /**
4791   * Returns request confirmation message HTML.
4792   *
4793   * @since 4.9.6
4794   * @access private
4795   *
4796   * @param int $request_id The request ID being confirmed.
4797   * @return string The confirmation message.
4798   */
4799  function _wp_privacy_account_request_confirmed_message( $request_id ) {
4800      $request = wp_get_user_request( $request_id );
4801  
4802      $message  = '<p class="success">' . __( 'Action has been confirmed.' ) . '</p>';
4803      $message .= '<p>' . __( 'The site administrator has been notified and will fulfill your request as soon as possible.' ) . '</p>';
4804  
4805      if ( $request && in_array( $request->action_name, _wp_privacy_action_request_types(), true ) ) {
4806          if ( 'export_personal_data' === $request->action_name ) {
4807              $message  = '<p class="success">' . __( 'Thanks for confirming your export request.' ) . '</p>';
4808              $message .= '<p>' . __( 'The site administrator has been notified. You will receive a link to download your export via email when they fulfill your request.' ) . '</p>';
4809          } elseif ( 'remove_personal_data' === $request->action_name ) {
4810              $message  = '<p class="success">' . __( 'Thanks for confirming your erasure request.' ) . '</p>';
4811              $message .= '<p>' . __( 'The site administrator has been notified. You will receive an email confirmation when they erase your data.' ) . '</p>';
4812          }
4813      }
4814  
4815      /**
4816       * Filters the message displayed to a user when they confirm a data request.
4817       *
4818       * @since 4.9.6
4819       *
4820       * @param string $message    The message to the user.
4821       * @param int    $request_id The ID of the request being confirmed.
4822       */
4823      $message = apply_filters( 'user_request_action_confirmed_message', $message, $request_id );
4824  
4825      return $message;
4826  }
4827  
4828  /**
4829   * Creates and logs a user request to perform a specific action.
4830   *
4831   * Requests are stored inside a post type named `user_request` since they can apply to both
4832   * users on the site, or guests without a user account.
4833   *
4834   * @since 4.9.6
4835   * @since 5.7.0 Added the `$status` parameter.
4836   *
4837   * @param string $email_address           User email address. This can be the address of a registered
4838   *                                        or non-registered user.
4839   * @param string $action_name             Name of the action that is being confirmed. Required.
4840   * @param array  $request_data            Misc data you want to send with the verification request and pass
4841   *                                        to the actions once the request is confirmed.
4842   * @param string $status                  Optional request status (pending or confirmed). Default 'pending'.
4843   * @return int|WP_Error                   Returns the request ID if successful, or a WP_Error object on failure.
4844   */
4845  function wp_create_user_request( $email_address = '', $action_name = '', $request_data = array(), $status = 'pending' ) {
4846      $email_address = sanitize_email( $email_address );
4847      $action_name   = sanitize_key( $action_name );
4848  
4849      if ( ! is_email( $email_address ) ) {
4850          return new WP_Error( 'invalid_email', __( 'Invalid email address.' ) );
4851      }
4852  
4853      if ( ! in_array( $action_name, _wp_privacy_action_request_types(), true ) ) {
4854          return new WP_Error( 'invalid_action', __( 'Invalid action name.' ) );
4855      }
4856  
4857      if ( ! in_array( $status, array( 'pending', 'confirmed' ), true ) ) {
4858          return new WP_Error( 'invalid_status', __( 'Invalid request status.' ) );
4859      }
4860  
4861      $user    = get_user_by( 'email', $email_address );
4862      $user_id = $user && ! is_wp_error( $user ) ? $user->ID : 0;
4863  
4864      // Check for duplicates.
4865      $requests_query = new WP_Query(
4866          array(
4867              'post_type'     => 'user_request',
4868              'post_name__in' => array( $action_name ), // Action name stored in post_name column.
4869              'title'         => $email_address,        // Email address stored in post_title column.
4870              'post_status'   => array(
4871                  'request-pending',
4872                  'request-confirmed',
4873              ),
4874              'fields'        => 'ids',
4875          )
4876      );
4877  
4878      if ( $requests_query->found_posts ) {
4879          return new WP_Error( 'duplicate_request', __( 'An incomplete personal data request for this email address already exists.' ) );
4880      }
4881  
4882      $request_id = wp_insert_post(
4883          array(
4884              'post_author'   => $user_id,
4885              'post_name'     => $action_name,
4886              'post_title'    => $email_address,
4887              'post_content'  => wp_json_encode( $request_data ),
4888              'post_status'   => 'request-' . $status,
4889              'post_type'     => 'user_request',
4890              'post_date'     => current_time( 'mysql', false ),
4891              'post_date_gmt' => current_time( 'mysql', true ),
4892          ),
4893          true
4894      );
4895  
4896      return $request_id;
4897  }
4898  
4899  /**
4900   * Gets action description from the name and return a string.
4901   *
4902   * @since 4.9.6
4903   *
4904   * @param string $action_name Action name of the request.
4905   * @return string Human readable action name.
4906   */
4907  function wp_user_request_action_description( $action_name ) {
4908      switch ( $action_name ) {
4909          case 'export_personal_data':
4910              $description = __( 'Export Personal Data' );
4911              break;
4912          case 'remove_personal_data':
4913              $description = __( 'Erase Personal Data' );
4914              break;
4915          default:
4916              /* translators: %s: Action name. */
4917              $description = sprintf( __( 'Confirm the "%s" action' ), $action_name );
4918              break;
4919      }
4920  
4921      /**
4922       * Filters the user action description.
4923       *
4924       * @since 4.9.6
4925       *
4926       * @param string $description The default description.
4927       * @param string $action_name The name of the request.
4928       */
4929      return apply_filters( 'user_request_action_description', $description, $action_name );
4930  }
4931  
4932  /**
4933   * Send a confirmation request email to confirm an action.
4934   *
4935   * If the request is not already pending, it will be updated.
4936   *
4937   * @since 4.9.6
4938   *
4939   * @param int $request_id ID of the request created via wp_create_user_request().
4940   * @return true|WP_Error True on success, `WP_Error` on failure.
4941   */
4942  function wp_send_user_request( $request_id ) {
4943      $request_id = absint( $request_id );
4944      $request    = wp_get_user_request( $request_id );
4945  
4946      if ( ! $request ) {
4947          return new WP_Error( 'invalid_request', __( 'Invalid personal data request.' ) );
4948      }
4949  
4950      // Localize message content for user; fallback to site default for visitors.
4951      if ( ! empty( $request->user_id ) ) {
4952          $switched_locale = switch_to_user_locale( $request->user_id );
4953      } else {
4954          $switched_locale = switch_to_locale( get_locale() );
4955      }
4956  
4957      /*
4958       * Generate the new user request key first, as it is used by both the $request
4959       * object and the confirm_url array.
4960       * See https://core.trac.wordpress.org/ticket/44940
4961       */
4962      $request->confirm_key = wp_generate_user_request_key( $request_id );
4963  
4964      $email_data = array(
4965          'request'     => $request,
4966          'email'       => $request->email,
4967          'description' => wp_user_request_action_description( $request->action_name ),
4968          'confirm_url' => add_query_arg(
4969              array(
4970                  'action'      => 'confirmaction',
4971                  'request_id'  => $request_id,
4972                  'confirm_key' => $request->confirm_key,
4973              ),
4974              wp_login_url()
4975          ),
4976          'sitename'    => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
4977          'siteurl'     => home_url(),
4978      );
4979  
4980      /* translators: Confirm privacy data request notification email subject. 1: Site title, 2: Name of the action. */
4981      $subject = sprintf( __( '[%1$s] Confirm Action: %2$s' ), $email_data['sitename'], $email_data['description'] );
4982  
4983      /**
4984       * Filters the subject of the email sent when an account action is attempted.
4985       *
4986       * @since 4.9.6
4987       *
4988       * @param string $subject    The email subject.
4989       * @param string $sitename   The name of the site.
4990       * @param array  $email_data {
4991       *     Data relating to the account action email.
4992       *
4993       *     @type WP_User_Request $request     User request object.
4994       *     @type string          $email       The email address this is being sent to.
4995       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4996       *     @type string          $confirm_url The link to click on to confirm the account action.
4997       *     @type string          $sitename    The site name sending the mail.
4998       *     @type string          $siteurl     The site URL sending the mail.
4999       * }
5000       */
5001      $subject = apply_filters( 'user_request_action_email_subject', $subject, $email_data['sitename'], $email_data );
5002  
5003      /* translators: Do not translate DESCRIPTION, CONFIRM_URL, SITENAME, SITEURL: those are placeholders. */
5004      $content = __(
5005          'Howdy,
5006  
5007  A request has been made to perform the following action on your account:
5008  
5009       ###DESCRIPTION###
5010  
5011  To confirm this, please click on the following link:
5012  ###CONFIRM_URL###
5013  
5014  You can safely ignore and delete this email if you do not want to
5015  take this action.
5016  
5017  Regards,
5018  All at ###SITENAME###
5019  ###SITEURL###'
5020      );
5021  
5022      /**
5023       * Filters the text of the email sent when an account action is attempted.
5024       *
5025       * The following strings have a special meaning and will get replaced dynamically:
5026       *
5027       *  - `###DESCRIPTION###` Description of the action being performed so the user knows what the email is for.
5028       *  - `###CONFIRM_URL###` The link to click on to confirm the account action.
5029       *  - `###SITENAME###`    The name of the site.
5030       *  - `###SITEURL###`     The URL to the site.
5031       *
5032       * @since 4.9.6
5033       *
5034       * @param string $content Text in the email.
5035       * @param array  $email_data {
5036       *     Data relating to the account action email.
5037       *
5038       *     @type WP_User_Request $request     User request object.
5039       *     @type string          $email       The email address this is being sent to.
5040       *     @type string          $description Description of the action being performed so the user knows what the email is for.
5041       *     @type string          $confirm_url The link to click on to confirm the account action.
5042       *     @type string          $sitename    The site name sending the mail.
5043       *     @type string          $siteurl     The site URL sending the mail.
5044       * }
5045       */
5046      $content = apply_filters( 'user_request_action_email_content', $content, $email_data );
5047  
5048      $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
5049      $content = str_replace( '###CONFIRM_URL###', sanitize_url( $email_data['confirm_url'] ), $content );
5050      $content = str_replace( '###EMAIL###', $email_data['email'], $content );
5051      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
5052      $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content );
5053  
5054      $headers = '';
5055  
5056      /**
5057       * Filters the headers of the email sent when an account action is attempted.
5058       *
5059       * @since 5.4.0
5060       *
5061       * @param string|array $headers    The email headers.
5062       * @param string       $subject    The email subject.
5063       * @param string       $content    The email content.
5064       * @param int          $request_id The request ID.
5065       * @param array        $email_data {
5066       *     Data relating to the account action email.
5067       *
5068       *     @type WP_User_Request $request     User request object.
5069       *     @type string          $email       The email address this is being sent to.
5070       *     @type string          $description Description of the action being performed so the user knows what the email is for.
5071       *     @type string          $confirm_url The link to click on to confirm the account action.
5072       *     @type string          $sitename    The site name sending the mail.
5073       *     @type string          $siteurl     The site URL sending the mail.
5074       * }
5075       */
5076      $headers = apply_filters( 'user_request_action_email_headers', $headers, $subject, $content, $request_id, $email_data );
5077  
5078      $email_sent = wp_mail( $email_data['email'], $subject, $content, $headers );
5079  
5080      if ( $switched_locale ) {
5081          restore_previous_locale();
5082      }
5083  
5084      if ( ! $email_sent ) {
5085          return new WP_Error( 'privacy_email_error', __( 'Unable to send personal data export confirmation email.' ) );
5086      }
5087  
5088      return true;
5089  }
5090  
5091  /**
5092   * Returns a confirmation key for a user action and stores the hashed version for future comparison.
5093   *
5094   * @since 4.9.6
5095   *
5096   * @param int $request_id Request ID.
5097   * @return string Confirmation key.
5098   */
5099  function wp_generate_user_request_key( $request_id ) {
5100      // Generate something random for a confirmation key.
5101      $key = wp_generate_password( 20, false );
5102  
5103      // Save the key, hashed.
5104      wp_update_post(
5105          array(
5106              'ID'            => $request_id,
5107              'post_status'   => 'request-pending',
5108              'post_password' => wp_fast_hash( $key ),
5109          )
5110      );
5111  
5112      return $key;
5113  }
5114  
5115  /**
5116   * Validates a user request by comparing the key with the request's key.
5117   *
5118   * @since 4.9.6
5119   *
5120   * @param int    $request_id ID of the request being confirmed.
5121   * @param string $key        Provided key to validate.
5122   * @return true|WP_Error True on success, WP_Error on failure.
5123   */
5124  function wp_validate_user_request_key(
5125      $request_id,
5126      #[\SensitiveParameter]
5127      $key
5128  ) {
5129      $request_id       = absint( $request_id );
5130      $request          = wp_get_user_request( $request_id );
5131      $saved_key        = $request->confirm_key;
5132      $key_request_time = $request->modified_timestamp;
5133  
5134      if ( ! $request || ! $saved_key || ! $key_request_time ) {
5135          return new WP_Error( 'invalid_request', __( 'Invalid personal data request.' ) );
5136      }
5137  
5138      if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
5139          return new WP_Error( 'expired_request', __( 'This personal data request has expired.' ) );
5140      }
5141  
5142      if ( empty( $key ) ) {
5143          return new WP_Error( 'missing_key', __( 'The confirmation key is missing from this personal data request.' ) );
5144      }
5145  
5146      /**
5147       * Filters the expiration time of confirm keys.
5148       *
5149       * @since 4.9.6
5150       *
5151       * @param int $expiration The expiration time in seconds.
5152       */
5153      $expiration_duration = (int) apply_filters( 'user_request_key_expiration', DAY_IN_SECONDS );
5154      $expiration_time     = $key_request_time + $expiration_duration;
5155  
5156      if ( ! wp_verify_fast_hash( $key, $saved_key ) ) {
5157          return new WP_Error( 'invalid_key', __( 'The confirmation key is invalid for this personal data request.' ) );
5158      }
5159  
5160      if ( ! $expiration_time || time() > $expiration_time ) {
5161          return new WP_Error( 'expired_key', __( 'The confirmation key has expired for this personal data request.' ) );
5162      }
5163  
5164      return true;
5165  }
5166  
5167  /**
5168   * Returns the user request object for the specified request ID.
5169   *
5170   * @since 5.4.0
5171   *
5172   * @param int $request_id The ID of the user request.
5173   * @return WP_User_Request|false
5174   */
5175  function wp_get_user_request( $request_id ) {
5176      $request_id = absint( $request_id );
5177      $post       = get_post( $request_id );
5178  
5179      if ( ! $post || 'user_request' !== $post->post_type ) {
5180          return false;
5181      }
5182  
5183      return new WP_User_Request( $post );
5184  }
5185  
5186  /**
5187   * Checks if Application Passwords is supported.
5188   *
5189   * Application Passwords is supported only by sites using SSL or local environments
5190   * but may be made available using the {@see 'wp_is_application_passwords_available'} filter.
5191   *
5192   * @since 5.9.0
5193   *
5194   * @return bool
5195   */
5196  function wp_is_application_passwords_supported() {
5197      return is_ssl() || 'local' === wp_get_environment_type();
5198  }
5199  
5200  /**
5201   * Checks if Application Passwords is globally available.
5202   *
5203   * By default, Application Passwords is available to all sites using SSL or to local environments.
5204   * Use the {@see 'wp_is_application_passwords_available'} filter to adjust its availability.
5205   *
5206   * @since 5.6.0
5207   *
5208   * @return bool
5209   */
5210  function wp_is_application_passwords_available() {
5211      /**
5212       * Filters whether Application Passwords is available.
5213       *
5214       * @since 5.6.0
5215       *
5216       * @param bool $available True if available, false otherwise.
5217       */
5218      return apply_filters( 'wp_is_application_passwords_available', wp_is_application_passwords_supported() );
5219  }
5220  
5221  /**
5222   * Checks if Application Passwords is available for a specific user.
5223   *
5224   * By default all users can use Application Passwords. Use {@see 'wp_is_application_passwords_available_for_user'}
5225   * to restrict availability to certain users.
5226   *
5227   * @since 5.6.0
5228   *
5229   * @param int|WP_User $user The user to check.
5230   * @return bool
5231   */
5232  function wp_is_application_passwords_available_for_user( $user ) {
5233      if ( ! wp_is_application_passwords_available() ) {
5234          return false;
5235      }
5236  
5237      if ( ! is_object( $user ) ) {
5238          $user = get_userdata( $user );
5239      }
5240  
5241      if ( ! $user || ! $user->exists() ) {
5242          return false;
5243      }
5244  
5245      /**
5246       * Filters whether Application Passwords is available for a specific user.
5247       *
5248       * @since 5.6.0
5249       *
5250       * @param bool    $available True if available, false otherwise.
5251       * @param WP_User $user      The user to check.
5252       */
5253      return apply_filters( 'wp_is_application_passwords_available_for_user', true, $user );
5254  }
5255  
5256  /**
5257   * Registers the user meta property for persisted preferences.
5258   *
5259   * This property is used to store user preferences across page reloads and is
5260   * currently used by the block editor for preferences like 'fullscreenMode' and
5261   * 'fixedToolbar'.
5262   *
5263   * @since 6.1.0
5264   * @access private
5265   *
5266   * @global wpdb $wpdb WordPress database abstraction object.
5267   */
5268  function wp_register_persisted_preferences_meta() {
5269      /*
5270       * Create a meta key that incorporates the blog prefix so that each site
5271       * on a multisite can have distinct user preferences.
5272       */
5273      global $wpdb;
5274      $meta_key = $wpdb->get_blog_prefix() . 'persisted_preferences';
5275  
5276      register_meta(
5277          'user',
5278          $meta_key,
5279          array(
5280              'type'         => 'object',
5281              'single'       => true,
5282              'show_in_rest' => array(
5283                  'name'   => 'persisted_preferences',
5284                  'type'   => 'object',
5285                  'schema' => array(
5286                      'type'                 => 'object',
5287                      'context'              => array( 'edit' ),
5288                      'properties'           => array(
5289                          '_modified' => array(
5290                              'description' => __( 'The date and time the preferences were updated.' ),
5291                              'type'        => 'string',
5292                              'format'      => 'date-time',
5293                              'readonly'    => false,
5294                          ),
5295                      ),
5296                      'additionalProperties' => true,
5297                  ),
5298              ),
5299          )
5300      );
5301  }
5302  
5303  /**
5304   * Sets the last changed time for the 'users' cache group.
5305   *
5306   * @since 6.3.0
5307   */
5308  function wp_cache_set_users_last_changed() {
5309      wp_cache_set_last_changed( 'users' );
5310  }
5311  
5312  /**
5313   * Checks if password reset is allowed for a specific user.
5314   *
5315   * @since 6.3.0
5316   *
5317   * @param int|WP_User $user The user to check.
5318   * @return bool|WP_Error True if allowed, false or WP_Error otherwise.
5319   */
5320  function wp_is_password_reset_allowed_for_user( $user ) {
5321      if ( ! is_object( $user ) ) {
5322          $user = get_userdata( $user );
5323      }
5324  
5325      if ( ! $user || ! $user->exists() ) {
5326          return false;
5327      }
5328      $allow = true;
5329      if ( is_multisite() && is_user_spammy( $user ) ) {
5330          $allow = false;
5331      }
5332  
5333      /**
5334       * Filters whether to allow a password to be reset.
5335       *
5336       * @since 2.7.0
5337       *
5338       * @param bool $allow   Whether to allow the password to be reset. Default true.
5339       * @param int  $user_id The ID of the user attempting to reset a password.
5340       */
5341      return apply_filters( 'allow_password_reset', $allow, $user->ID );
5342  }


Generated : Fri Oct 16 08:20:34 2026 Cross-referenced by PHPXref