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


Generated : Fri Aug 19 08:20:02 2022 Cross-referenced by PHPXref