[ Index ]

PHP Cross Reference of WordPress

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   * Authenticate 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   * Authenticate 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       * Strip 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, check 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   * Number of posts 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   * 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   * Get 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   * Retrieve 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   * Update 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   * Delete 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   * Retrieve 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   * Get the sites a user belongs to.
 770   *
 771   * @since 3.0.0
 772   * @since 4.7.0 Converted to use `get_sites()`.
 773   *
 774   * @global wpdb $wpdb WordPress database abstraction object.
 775   *
 776   * @param int  $user_id User ID
 777   * @param bool $all     Whether to retrieve all sites, or only sites that are not
 778   *                      marked as deleted, archived, or spam.
 779   * @return object[] A list of the user's sites. An empty array if the user doesn't exist
 780   *                  or belongs to no sites.
 781   */
 782  function get_blogs_of_user( $user_id, $all = false ) {
 783      global $wpdb;
 784  
 785      $user_id = (int) $user_id;
 786  
 787      // Logged out users can't have sites.
 788      if ( empty( $user_id ) ) {
 789          return array();
 790      }
 791  
 792      /**
 793       * Filters the list of a user's sites before it is populated.
 794       *
 795       * Returning a non-null value from the filter will effectively short circuit
 796       * get_blogs_of_user(), returning that value instead.
 797       *
 798       * @since 4.6.0
 799       *
 800       * @param null|object[] $sites   An array of site objects of which the user is a member.
 801       * @param int           $user_id User ID.
 802       * @param bool          $all     Whether the returned array should contain all sites, including
 803       *                               those marked 'deleted', 'archived', or 'spam'. Default false.
 804       */
 805      $sites = apply_filters( 'pre_get_blogs_of_user', null, $user_id, $all );
 806  
 807      if ( null !== $sites ) {
 808          return $sites;
 809      }
 810  
 811      $keys = get_user_meta( $user_id );
 812      if ( empty( $keys ) ) {
 813          return array();
 814      }
 815  
 816      if ( ! is_multisite() ) {
 817          $site_id                        = get_current_blog_id();
 818          $sites                          = array( $site_id => new stdClass );
 819          $sites[ $site_id ]->userblog_id = $site_id;
 820          $sites[ $site_id ]->blogname    = get_option( 'blogname' );
 821          $sites[ $site_id ]->domain      = '';
 822          $sites[ $site_id ]->path        = '';
 823          $sites[ $site_id ]->site_id     = 1;
 824          $sites[ $site_id ]->siteurl     = get_option( 'siteurl' );
 825          $sites[ $site_id ]->archived    = 0;
 826          $sites[ $site_id ]->spam        = 0;
 827          $sites[ $site_id ]->deleted     = 0;
 828          return $sites;
 829      }
 830  
 831      $site_ids = array();
 832  
 833      if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
 834          $site_ids[] = 1;
 835          unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
 836      }
 837  
 838      $keys = array_keys( $keys );
 839  
 840      foreach ( $keys as $key ) {
 841          if ( 'capabilities' !== substr( $key, -12 ) ) {
 842              continue;
 843          }
 844          if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) ) {
 845              continue;
 846          }
 847          $site_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
 848          if ( ! is_numeric( $site_id ) ) {
 849              continue;
 850          }
 851  
 852          $site_ids[] = (int) $site_id;
 853      }
 854  
 855      $sites = array();
 856  
 857      if ( ! empty( $site_ids ) ) {
 858          $args = array(
 859              'number'                 => '',
 860              'site__in'               => $site_ids,
 861              'update_site_meta_cache' => false,
 862          );
 863          if ( ! $all ) {
 864              $args['archived'] = 0;
 865              $args['spam']     = 0;
 866              $args['deleted']  = 0;
 867          }
 868  
 869          $_sites = get_sites( $args );
 870  
 871          foreach ( $_sites as $site ) {
 872              $sites[ $site->id ] = (object) array(
 873                  'userblog_id' => $site->id,
 874                  'blogname'    => $site->blogname,
 875                  'domain'      => $site->domain,
 876                  'path'        => $site->path,
 877                  'site_id'     => $site->network_id,
 878                  'siteurl'     => $site->siteurl,
 879                  'archived'    => $site->archived,
 880                  'mature'      => $site->mature,
 881                  'spam'        => $site->spam,
 882                  'deleted'     => $site->deleted,
 883              );
 884          }
 885      }
 886  
 887      /**
 888       * Filters the list of sites a user belongs to.
 889       *
 890       * @since MU (3.0.0)
 891       *
 892       * @param object[] $sites   An array of site objects belonging to the user.
 893       * @param int      $user_id User ID.
 894       * @param bool     $all     Whether the returned sites array should contain all sites, including
 895       *                          those marked 'deleted', 'archived', or 'spam'. Default false.
 896       */
 897      return apply_filters( 'get_blogs_of_user', $sites, $user_id, $all );
 898  }
 899  
 900  /**
 901   * Find out whether a user is a member of a given blog.
 902   *
 903   * @since MU (3.0.0)
 904   *
 905   * @global wpdb $wpdb WordPress database abstraction object.
 906   *
 907   * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
 908   * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
 909   * @return bool
 910   */
 911  function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
 912      global $wpdb;
 913  
 914      $user_id = (int) $user_id;
 915      $blog_id = (int) $blog_id;
 916  
 917      if ( empty( $user_id ) ) {
 918          $user_id = get_current_user_id();
 919      }
 920  
 921      // Technically not needed, but does save calls to get_site() and get_user_meta()
 922      // in the event that the function is called when a user isn't logged in.
 923      if ( empty( $user_id ) ) {
 924          return false;
 925      } else {
 926          $user = get_userdata( $user_id );
 927          if ( ! $user instanceof WP_User ) {
 928              return false;
 929          }
 930      }
 931  
 932      if ( ! is_multisite() ) {
 933          return true;
 934      }
 935  
 936      if ( empty( $blog_id ) ) {
 937          $blog_id = get_current_blog_id();
 938      }
 939  
 940      $blog = get_site( $blog_id );
 941  
 942      if ( ! $blog || ! isset( $blog->domain ) || $blog->archived || $blog->spam || $blog->deleted ) {
 943          return false;
 944      }
 945  
 946      $keys = get_user_meta( $user_id );
 947      if ( empty( $keys ) ) {
 948          return false;
 949      }
 950  
 951      // No underscore before capabilities in $base_capabilities_key.
 952      $base_capabilities_key = $wpdb->base_prefix . 'capabilities';
 953      $site_capabilities_key = $wpdb->base_prefix . $blog_id . '_capabilities';
 954  
 955      if ( isset( $keys[ $base_capabilities_key ] ) && 1 == $blog_id ) {
 956          return true;
 957      }
 958  
 959      if ( isset( $keys[ $site_capabilities_key ] ) ) {
 960          return true;
 961      }
 962  
 963      return false;
 964  }
 965  
 966  /**
 967   * Adds meta data to a user.
 968   *
 969   * @since 3.0.0
 970   *
 971   * @param int    $user_id    User ID.
 972   * @param string $meta_key   Metadata name.
 973   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
 974   * @param bool   $unique     Optional. Whether the same key should not be added.
 975   *                           Default false.
 976   * @return int|false Meta ID on success, false on failure.
 977   */
 978  function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
 979      return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
 980  }
 981  
 982  /**
 983   * Remove metadata matching criteria from a user.
 984   *
 985   * You can match based on the key, or key and value. Removing based on key and
 986   * value, will keep from removing duplicate metadata with the same key. It also
 987   * allows removing all metadata matching key, if needed.
 988   *
 989   * @since 3.0.0
 990   *
 991   * @link https://developer.wordpress.org/reference/functions/delete_user_meta/
 992   *
 993   * @param int    $user_id    User ID
 994   * @param string $meta_key   Metadata name.
 995   * @param mixed  $meta_value Optional. Metadata value. If provided,
 996   *                           rows will only be removed that match the value.
 997   *                           Must be serializable if non-scalar. Default empty.
 998   * @return bool True on success, false on failure.
 999   */
1000  function delete_user_meta( $user_id, $meta_key, $meta_value = '' ) {
1001      return delete_metadata( 'user', $user_id, $meta_key, $meta_value );
1002  }
1003  
1004  /**
1005   * Retrieve user meta field for a user.
1006   *
1007   * @since 3.0.0
1008   *
1009   * @link https://developer.wordpress.org/reference/functions/get_user_meta/
1010   *
1011   * @param int    $user_id User ID.
1012   * @param string $key     Optional. The meta key to retrieve. By default,
1013   *                        returns data for all keys.
1014   * @param bool   $single  Optional. Whether to return a single value.
1015   *                        This parameter has no effect if `$key` is not specified.
1016   *                        Default false.
1017   * @return mixed An array of values if `$single` is false.
1018   *               The value of meta data field if `$single` is true.
1019   *               False for an invalid `$user_id` (non-numeric, zero, or negative value).
1020   *               An empty string if a valid but non-existing user ID is passed.
1021   */
1022  function get_user_meta( $user_id, $key = '', $single = false ) {
1023      return get_metadata( 'user', $user_id, $key, $single );
1024  }
1025  
1026  /**
1027   * Update user meta field based on user ID.
1028   *
1029   * Use the $prev_value parameter to differentiate between meta fields with the
1030   * same key and user ID.
1031   *
1032   * If the meta field for the user does not exist, it will be added.
1033   *
1034   * @since 3.0.0
1035   *
1036   * @link https://developer.wordpress.org/reference/functions/update_user_meta/
1037   *
1038   * @param int    $user_id    User ID.
1039   * @param string $meta_key   Metadata key.
1040   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
1041   * @param mixed  $prev_value Optional. Previous value to check before updating.
1042   *                           If specified, only update existing metadata entries with
1043   *                           this value. Otherwise, update all entries. Default empty.
1044   * @return int|bool Meta ID if the key didn't exist, true on successful update,
1045   *                  false on failure or if the value passed to the function
1046   *                  is the same as the one that is already in the database.
1047   */
1048  function update_user_meta( $user_id, $meta_key, $meta_value, $prev_value = '' ) {
1049      return update_metadata( 'user', $user_id, $meta_key, $meta_value, $prev_value );
1050  }
1051  
1052  /**
1053   * Count number of users who have each of the user roles.
1054   *
1055   * Assumes there are neither duplicated nor orphaned capabilities meta_values.
1056   * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
1057   * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
1058   * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
1059   *
1060   * @since 3.0.0
1061   * @since 4.4.0 The number of users with no role is now included in the `none` element.
1062   * @since 4.9.0 The `$site_id` parameter was added to support multisite.
1063   *
1064   * @global wpdb $wpdb WordPress database abstraction object.
1065   *
1066   * @param string   $strategy Optional. The computational strategy to use when counting the users.
1067   *                           Accepts either 'time' or 'memory'. Default 'time'.
1068   * @param int|null $site_id  Optional. The site ID to count users for. Defaults to the current site.
1069   * @return array {
1070   *     User counts.
1071   *
1072   *     @type int   $total_users Total number of users on the site.
1073   *     @type int[] $avail_roles Array of user counts keyed by user role.
1074   * }
1075   */
1076  function count_users( $strategy = 'time', $site_id = null ) {
1077      global $wpdb;
1078  
1079      // Initialize.
1080      if ( ! $site_id ) {
1081          $site_id = get_current_blog_id();
1082      }
1083  
1084      /**
1085       * Filters the user count before queries are run.
1086       *
1087       * Return a non-null value to cause count_users() to return early.
1088       *
1089       * @since 5.1.0
1090       *
1091       * @param null|string $result   The value to return instead. Default null to continue with the query.
1092       * @param string      $strategy Optional. The computational strategy to use when counting the users.
1093       *                              Accepts either 'time' or 'memory'. Default 'time'.
1094       * @param int|null    $site_id  Optional. The site ID to count users for. Defaults to the current site.
1095       */
1096      $pre = apply_filters( 'pre_count_users', null, $strategy, $site_id );
1097  
1098      if ( null !== $pre ) {
1099          return $pre;
1100      }
1101  
1102      $blog_prefix = $wpdb->get_blog_prefix( $site_id );
1103      $result      = array();
1104  
1105      if ( 'time' === $strategy ) {
1106          if ( is_multisite() && get_current_blog_id() != $site_id ) {
1107              switch_to_blog( $site_id );
1108              $avail_roles = wp_roles()->get_names();
1109              restore_current_blog();
1110          } else {
1111              $avail_roles = wp_roles()->get_names();
1112          }
1113  
1114          // Build a CPU-intensive query that will return concise information.
1115          $select_count = array();
1116          foreach ( $avail_roles as $this_role => $name ) {
1117              $select_count[] = $wpdb->prepare( 'COUNT(NULLIF(`meta_value` LIKE %s, false))', '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%' );
1118          }
1119          $select_count[] = "COUNT(NULLIF(`meta_value` = 'a:0:{}', false))";
1120          $select_count   = implode( ', ', $select_count );
1121  
1122          // Add the meta_value index to the selection list, then run the query.
1123          $row = $wpdb->get_row(
1124              "
1125              SELECT {$select_count}, COUNT(*)
1126              FROM {$wpdb->usermeta}
1127              INNER JOIN {$wpdb->users} ON user_id = ID
1128              WHERE meta_key = '{$blog_prefix}capabilities'
1129          ",
1130              ARRAY_N
1131          );
1132  
1133          // Run the previous loop again to associate results with role names.
1134          $col         = 0;
1135          $role_counts = array();
1136          foreach ( $avail_roles as $this_role => $name ) {
1137              $count = (int) $row[ $col++ ];
1138              if ( $count > 0 ) {
1139                  $role_counts[ $this_role ] = $count;
1140              }
1141          }
1142  
1143          $role_counts['none'] = (int) $row[ $col++ ];
1144  
1145          // Get the meta_value index from the end of the result set.
1146          $total_users = (int) $row[ $col ];
1147  
1148          $result['total_users'] = $total_users;
1149          $result['avail_roles'] =& $role_counts;
1150      } else {
1151          $avail_roles = array(
1152              'none' => 0,
1153          );
1154  
1155          $users_of_blog = $wpdb->get_col(
1156              "
1157              SELECT meta_value
1158              FROM {$wpdb->usermeta}
1159              INNER JOIN {$wpdb->users} ON user_id = ID
1160              WHERE meta_key = '{$blog_prefix}capabilities'
1161          "
1162          );
1163  
1164          foreach ( $users_of_blog as $caps_meta ) {
1165              $b_roles = maybe_unserialize( $caps_meta );
1166              if ( ! is_array( $b_roles ) ) {
1167                  continue;
1168              }
1169              if ( empty( $b_roles ) ) {
1170                  $avail_roles['none']++;
1171              }
1172              foreach ( $b_roles as $b_role => $val ) {
1173                  if ( isset( $avail_roles[ $b_role ] ) ) {
1174                      $avail_roles[ $b_role ]++;
1175                  } else {
1176                      $avail_roles[ $b_role ] = 1;
1177                  }
1178              }
1179          }
1180  
1181          $result['total_users'] = count( $users_of_blog );
1182          $result['avail_roles'] =& $avail_roles;
1183      }
1184  
1185      return $result;
1186  }
1187  
1188  //
1189  // Private helper functions.
1190  //
1191  
1192  /**
1193   * Set up global user vars.
1194   *
1195   * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
1196   *
1197   * @since 2.0.4
1198   *
1199   * @global string  $user_login    The user username for logging in
1200   * @global WP_User $userdata      User data.
1201   * @global int     $user_level    The level of the user
1202   * @global int     $user_ID       The ID of the user
1203   * @global string  $user_email    The email address of the user
1204   * @global string  $user_url      The url in the user's profile
1205   * @global string  $user_identity The display name of the user
1206   *
1207   * @param int $for_user_id Optional. User ID to set up global data. Default 0.
1208   */
1209  function setup_userdata( $for_user_id = 0 ) {
1210      global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
1211  
1212      if ( ! $for_user_id ) {
1213          $for_user_id = get_current_user_id();
1214      }
1215      $user = get_userdata( $for_user_id );
1216  
1217      if ( ! $user ) {
1218          $user_ID       = 0;
1219          $user_level    = 0;
1220          $userdata      = null;
1221          $user_login    = '';
1222          $user_email    = '';
1223          $user_url      = '';
1224          $user_identity = '';
1225          return;
1226      }
1227  
1228      $user_ID       = (int) $user->ID;
1229      $user_level    = (int) $user->user_level;
1230      $userdata      = $user;
1231      $user_login    = $user->user_login;
1232      $user_email    = $user->user_email;
1233      $user_url      = $user->user_url;
1234      $user_identity = $user->display_name;
1235  }
1236  
1237  /**
1238   * Create dropdown HTML content of users.
1239   *
1240   * The content can either be displayed, which it is by default or retrieved by
1241   * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
1242   * need to be used; all users will be displayed in that case. Only one can be
1243   * used, either 'include' or 'exclude', but not both.
1244   *
1245   * The available arguments are as follows:
1246   *
1247   * @since 2.3.0
1248   * @since 4.5.0 Added the 'display_name_with_login' value for 'show'.
1249   * @since 4.7.0 Added the `$role`, `$role__in`, and `$role__not_in` parameters.
1250   *
1251   * @param array|string $args {
1252   *     Optional. Array or string of arguments to generate a drop-down of users.
1253   *     See WP_User_Query::prepare_query() for additional available arguments.
1254   *
1255   *     @type string       $show_option_all         Text to show as the drop-down default (all).
1256   *                                                 Default empty.
1257   *     @type string       $show_option_none        Text to show as the drop-down default when no
1258   *                                                 users were found. Default empty.
1259   *     @type int|string   $option_none_value       Value to use for $show_option_non when no users
1260   *                                                 were found. Default -1.
1261   *     @type string       $hide_if_only_one_author Whether to skip generating the drop-down
1262   *                                                 if only one user was found. Default empty.
1263   *     @type string       $orderby                 Field to order found users by. Accepts user fields.
1264   *                                                 Default 'display_name'.
1265   *     @type string       $order                   Whether to order users in ascending or descending
1266   *                                                 order. Accepts 'ASC' (ascending) or 'DESC' (descending).
1267   *                                                 Default 'ASC'.
1268   *     @type int[]|string $include                 Array or comma-separated list of user IDs to include.
1269   *                                                 Default empty.
1270   *     @type int[]|string $exclude                 Array or comma-separated list of user IDs to exclude.
1271   *                                                 Default empty.
1272   *     @type bool|int     $multi                   Whether to skip the ID attribute on the 'select' element.
1273   *                                                 Accepts 1|true or 0|false. Default 0|false.
1274   *     @type string       $show                    User data to display. If the selected item is empty
1275   *                                                 then the 'user_login' will be displayed in parentheses.
1276   *                                                 Accepts any user field, or 'display_name_with_login' to show
1277   *                                                 the display name with user_login in parentheses.
1278   *                                                 Default 'display_name'.
1279   *     @type int|bool     $echo                    Whether to echo or return the drop-down. Accepts 1|true (echo)
1280   *                                                 or 0|false (return). Default 1|true.
1281   *     @type int          $selected                Which user ID should be selected. Default 0.
1282   *     @type bool         $include_selected        Whether to always include the selected user ID in the drop-
1283   *                                                 down. Default false.
1284   *     @type string       $name                    Name attribute of select element. Default 'user'.
1285   *     @type string       $id                      ID attribute of the select element. Default is the value of $name.
1286   *     @type string       $class                   Class attribute of the select element. Default empty.
1287   *     @type int          $blog_id                 ID of blog (Multisite only). Default is ID of the current blog.
1288   *     @type string       $who                     Which type of users to query. Accepts only an empty string or
1289   *                                                 'authors'. Default empty.
1290   *     @type string|array $role                    An array or a comma-separated list of role names that users must
1291   *                                                 match to be included in results. Note that this is an inclusive
1292   *                                                 list: users must match *each* role. Default empty.
1293   *     @type string[]     $role__in                An array of role names. Matched users must have at least one of
1294   *                                                 these roles. Default empty array.
1295   *     @type string[]     $role__not_in            An array of role names to exclude. Users matching one or more of
1296   *                                                 these roles will not be included in results. Default empty array.
1297   * }
1298   * @return string HTML dropdown list of users.
1299   */
1300  function wp_dropdown_users( $args = '' ) {
1301      $defaults = array(
1302          'show_option_all'         => '',
1303          'show_option_none'        => '',
1304          'hide_if_only_one_author' => '',
1305          'orderby'                 => 'display_name',
1306          'order'                   => 'ASC',
1307          'include'                 => '',
1308          'exclude'                 => '',
1309          'multi'                   => 0,
1310          'show'                    => 'display_name',
1311          'echo'                    => 1,
1312          'selected'                => 0,
1313          'name'                    => 'user',
1314          'class'                   => '',
1315          'id'                      => '',
1316          'blog_id'                 => get_current_blog_id(),
1317          'who'                     => '',
1318          'include_selected'        => false,
1319          'option_none_value'       => -1,
1320          'role'                    => '',
1321          'role__in'                => array(),
1322          'role__not_in'            => array(),
1323      );
1324  
1325      $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
1326  
1327      $parsed_args = wp_parse_args( $args, $defaults );
1328  
1329      $query_args = wp_array_slice_assoc( $parsed_args, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who', 'role', 'role__in', 'role__not_in' ) );
1330  
1331      $fields = array( 'ID', 'user_login' );
1332  
1333      $show = ! empty( $parsed_args['show'] ) ? $parsed_args['show'] : 'display_name';
1334      if ( 'display_name_with_login' === $show ) {
1335          $fields[] = 'display_name';
1336      } else {
1337          $fields[] = $show;
1338      }
1339  
1340      $query_args['fields'] = $fields;
1341  
1342      $show_option_all   = $parsed_args['show_option_all'];
1343      $show_option_none  = $parsed_args['show_option_none'];
1344      $option_none_value = $parsed_args['option_none_value'];
1345  
1346      /**
1347       * Filters the query arguments for the list of users in the dropdown.
1348       *
1349       * @since 4.4.0
1350       *
1351       * @param array $query_args  The query arguments for get_users().
1352       * @param array $parsed_args The arguments passed to wp_dropdown_users() combined with the defaults.
1353       */
1354      $query_args = apply_filters( 'wp_dropdown_users_args', $query_args, $parsed_args );
1355  
1356      $users = get_users( $query_args );
1357  
1358      $output = '';
1359      if ( ! empty( $users ) && ( empty( $parsed_args['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
1360          $name = esc_attr( $parsed_args['name'] );
1361          if ( $parsed_args['multi'] && ! $parsed_args['id'] ) {
1362              $id = '';
1363          } else {
1364              $id = $parsed_args['id'] ? " id='" . esc_attr( $parsed_args['id'] ) . "'" : " id='$name'";
1365          }
1366          $output = "<select name='{$name}'{$id} class='" . $parsed_args['class'] . "'>\n";
1367  
1368          if ( $show_option_all ) {
1369              $output .= "\t<option value='0'>$show_option_all</option>\n";
1370          }
1371  
1372          if ( $show_option_none ) {
1373              $_selected = selected( $option_none_value, $parsed_args['selected'], false );
1374              $output   .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
1375          }
1376  
1377          if ( $parsed_args['include_selected'] && ( $parsed_args['selected'] > 0 ) ) {
1378              $found_selected          = false;
1379              $parsed_args['selected'] = (int) $parsed_args['selected'];
1380  
1381              foreach ( (array) $users as $user ) {
1382                  $user->ID = (int) $user->ID;
1383                  if ( $user->ID === $parsed_args['selected'] ) {
1384                      $found_selected = true;
1385                  }
1386              }
1387  
1388              if ( ! $found_selected ) {
1389                  $selected_user = get_userdata( $parsed_args['selected'] );
1390                  if ( $selected_user ) {
1391                      $users[] = $selected_user;
1392                  }
1393              }
1394          }
1395  
1396          foreach ( (array) $users as $user ) {
1397              if ( 'display_name_with_login' === $show ) {
1398                  /* translators: 1: User's display name, 2: User login. */
1399                  $display = sprintf( _x( '%1$s (%2$s)', 'user dropdown' ), $user->display_name, $user->user_login );
1400              } elseif ( ! empty( $user->$show ) ) {
1401                  $display = $user->$show;
1402              } else {
1403                  $display = '(' . $user->user_login . ')';
1404              }
1405  
1406              $_selected = selected( $user->ID, $parsed_args['selected'], false );
1407              $output   .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
1408          }
1409  
1410          $output .= '</select>';
1411      }
1412  
1413      /**
1414       * Filters the wp_dropdown_users() HTML output.
1415       *
1416       * @since 2.3.0
1417       *
1418       * @param string $output HTML output generated by wp_dropdown_users().
1419       */
1420      $html = apply_filters( 'wp_dropdown_users', $output );
1421  
1422      if ( $parsed_args['echo'] ) {
1423          echo $html;
1424      }
1425      return $html;
1426  }
1427  
1428  /**
1429   * Sanitize user field based on context.
1430   *
1431   * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1432   * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1433   * when calling filters.
1434   *
1435   * @since 2.3.0
1436   *
1437   * @param string $field   The user Object field name.
1438   * @param mixed  $value   The user Object value.
1439   * @param int    $user_id User ID.
1440   * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
1441   *                        'attribute' and 'js'.
1442   * @return mixed Sanitized value.
1443   */
1444  function sanitize_user_field( $field, $value, $user_id, $context ) {
1445      $int_fields = array( 'ID' );
1446      if ( in_array( $field, $int_fields, true ) ) {
1447          $value = (int) $value;
1448      }
1449  
1450      if ( 'raw' === $context ) {
1451          return $value;
1452      }
1453  
1454      if ( ! is_string( $value ) && ! is_numeric( $value ) ) {
1455          return $value;
1456      }
1457  
1458      $prefixed = false !== strpos( $field, 'user_' );
1459  
1460      if ( 'edit' === $context ) {
1461          if ( $prefixed ) {
1462  
1463              /** This filter is documented in wp-includes/post.php */
1464              $value = apply_filters( "edit_{$field}", $value, $user_id );
1465          } else {
1466  
1467              /**
1468               * Filters a user field value in the 'edit' context.
1469               *
1470               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1471               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1472               *
1473               * @since 2.9.0
1474               *
1475               * @param mixed $value   Value of the prefixed user field.
1476               * @param int   $user_id User ID.
1477               */
1478              $value = apply_filters( "edit_user_{$field}", $value, $user_id );
1479          }
1480  
1481          if ( 'description' === $field ) {
1482              $value = esc_html( $value ); // textarea_escaped?
1483          } else {
1484              $value = esc_attr( $value );
1485          }
1486      } elseif ( 'db' === $context ) {
1487          if ( $prefixed ) {
1488              /** This filter is documented in wp-includes/post.php */
1489              $value = apply_filters( "pre_{$field}", $value );
1490          } else {
1491  
1492              /**
1493               * Filters the value of a user field in the 'db' context.
1494               *
1495               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1496               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1497               *
1498               * @since 2.9.0
1499               *
1500               * @param mixed $value Value of the prefixed user field.
1501               */
1502              $value = apply_filters( "pre_user_{$field}", $value );
1503          }
1504      } else {
1505          // Use display filters by default.
1506          if ( $prefixed ) {
1507  
1508              /** This filter is documented in wp-includes/post.php */
1509              $value = apply_filters( "{$field}", $value, $user_id, $context );
1510          } else {
1511  
1512              /**
1513               * Filters the value of a user field in a standard context.
1514               *
1515               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1516               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1517               *
1518               * @since 2.9.0
1519               *
1520               * @param mixed  $value   The user object value to sanitize.
1521               * @param int    $user_id User ID.
1522               * @param string $context The context to filter within.
1523               */
1524              $value = apply_filters( "user_{$field}", $value, $user_id, $context );
1525          }
1526      }
1527  
1528      if ( 'user_url' === $field ) {
1529          $value = esc_url( $value );
1530      }
1531  
1532      if ( 'attribute' === $context ) {
1533          $value = esc_attr( $value );
1534      } elseif ( 'js' === $context ) {
1535          $value = esc_js( $value );
1536      }
1537  
1538      // Restore the type for integer fields after esc_attr().
1539      if ( in_array( $field, $int_fields, true ) ) {
1540          $value = (int) $value;
1541      }
1542  
1543      return $value;
1544  }
1545  
1546  /**
1547   * Update all user caches
1548   *
1549   * @since 3.0.0
1550   *
1551   * @param object|WP_User $user User object or database row to be cached
1552   * @return void|false Void on success, false on failure.
1553   */
1554  function update_user_caches( $user ) {
1555      if ( $user instanceof WP_User ) {
1556          if ( ! $user->exists() ) {
1557              return false;
1558          }
1559  
1560          $user = $user->data;
1561      }
1562  
1563      wp_cache_add( $user->ID, $user, 'users' );
1564      wp_cache_add( $user->user_login, $user->ID, 'userlogins' );
1565      wp_cache_add( $user->user_email, $user->ID, 'useremail' );
1566      wp_cache_add( $user->user_nicename, $user->ID, 'userslugs' );
1567  }
1568  
1569  /**
1570   * Clean all user caches
1571   *
1572   * @since 3.0.0
1573   * @since 4.4.0 'clean_user_cache' action was added.
1574   * @since 5.8.0 Refreshes the global user instance if cleaning the user cache for the current user.
1575   *
1576   * @global WP_User $current_user The current user object which holds the user data.
1577   *
1578   * @param WP_User|int $user User object or ID to be cleaned from the cache
1579   */
1580  function clean_user_cache( $user ) {
1581      global $current_user;
1582  
1583      if ( is_numeric( $user ) ) {
1584          $user = new WP_User( $user );
1585      }
1586  
1587      if ( ! $user->exists() ) {
1588          return;
1589      }
1590  
1591      wp_cache_delete( $user->ID, 'users' );
1592      wp_cache_delete( $user->user_login, 'userlogins' );
1593      wp_cache_delete( $user->user_email, 'useremail' );
1594      wp_cache_delete( $user->user_nicename, 'userslugs' );
1595  
1596      /**
1597       * Fires immediately after the given user's cache is cleaned.
1598       *
1599       * @since 4.4.0
1600       *
1601       * @param int     $user_id User ID.
1602       * @param WP_User $user    User object.
1603       */
1604      do_action( 'clean_user_cache', $user->ID, $user );
1605  
1606      // Refresh the global user instance if the cleaning current user.
1607      if ( get_current_user_id() === (int) $user->ID ) {
1608          $user_id      = (int) $user->ID;
1609          $current_user = null;
1610          wp_set_current_user( $user_id, '' );
1611      }
1612  }
1613  
1614  /**
1615   * Determines whether the given username exists.
1616   *
1617   * For more information on this and similar theme functions, check out
1618   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
1619   * Conditional Tags} article in the Theme Developer Handbook.
1620   *
1621   * @since 2.0.0
1622   *
1623   * @param string $username The username to check for existence.
1624   * @return int|false The user ID on success, false on failure.
1625   */
1626  function username_exists( $username ) {
1627      $user = get_user_by( 'login', $username );
1628      if ( $user ) {
1629          $user_id = $user->ID;
1630      } else {
1631          $user_id = false;
1632      }
1633  
1634      /**
1635       * Filters whether the given username exists.
1636       *
1637       * @since 4.9.0
1638       *
1639       * @param int|false $user_id  The user ID associated with the username,
1640       *                            or false if the username does not exist.
1641       * @param string    $username The username to check for existence.
1642       */
1643      return apply_filters( 'username_exists', $user_id, $username );
1644  }
1645  
1646  /**
1647   * Determines whether the given email exists.
1648   *
1649   * For more information on this and similar theme functions, check out
1650   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
1651   * Conditional Tags} article in the Theme Developer Handbook.
1652   *
1653   * @since 2.1.0
1654   *
1655   * @param string $email The email to check for existence.
1656   * @return int|false The user ID on success, false on failure.
1657   */
1658  function email_exists( $email ) {
1659      $user = get_user_by( 'email', $email );
1660      if ( $user ) {
1661          $user_id = $user->ID;
1662      } else {
1663          $user_id = false;
1664      }
1665  
1666      /**
1667       * Filters whether the given email exists.
1668       *
1669       * @since 5.6.0
1670       *
1671       * @param int|false $user_id The user ID associated with the email,
1672       *                           or false if the email does not exist.
1673       * @param string    $email   The email to check for existence.
1674       */
1675      return apply_filters( 'email_exists', $user_id, $email );
1676  }
1677  
1678  /**
1679   * Checks whether a username is valid.
1680   *
1681   * @since 2.0.1
1682   * @since 4.4.0 Empty sanitized usernames are now considered invalid.
1683   *
1684   * @param string $username Username.
1685   * @return bool Whether username given is valid.
1686   */
1687  function validate_username( $username ) {
1688      $sanitized = sanitize_user( $username, true );
1689      $valid     = ( $sanitized == $username && ! empty( $sanitized ) );
1690  
1691      /**
1692       * Filters whether the provided username is valid.
1693       *
1694       * @since 2.0.1
1695       *
1696       * @param bool   $valid    Whether given username is valid.
1697       * @param string $username Username to check.
1698       */
1699      return apply_filters( 'validate_username', $valid, $username );
1700  }
1701  
1702  /**
1703   * Insert a user into the database.
1704   *
1705   * Most of the `$userdata` array fields have filters associated with the values. Exceptions are
1706   * 'ID', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl',
1707   * 'user_registered', 'user_activation_key', 'spam', and 'role'. The filters have the prefix
1708   * 'pre_user_' followed by the field name. An example using 'description' would have the filter
1709   * called 'pre_user_description' that can be hooked into.
1710   *
1711   * @since 2.0.0
1712   * @since 3.6.0 The `aim`, `jabber`, and `yim` fields were removed as default user contact
1713   *              methods for new installations. See wp_get_user_contact_methods().
1714   * @since 4.7.0 The `locale` field can be passed to `$userdata`.
1715   * @since 5.3.0 The `user_activation_key` field can be passed to `$userdata`.
1716   * @since 5.3.0 The `spam` field can be passed to `$userdata` (Multisite only).
1717   * @since 5.9.0 The `meta_input` field can be passed to `$userdata` to allow addition of user meta data.
1718   *
1719   * @global wpdb $wpdb WordPress database abstraction object.
1720   *
1721   * @param array|object|WP_User $userdata {
1722   *     An array, object, or WP_User object of user data arguments.
1723   *
1724   *     @type int    $ID                   User ID. If supplied, the user will be updated.
1725   *     @type string $user_pass            The plain-text user password.
1726   *     @type string $user_login           The user's login username.
1727   *     @type string $user_nicename        The URL-friendly user name.
1728   *     @type string $user_url             The user URL.
1729   *     @type string $user_email           The user email address.
1730   *     @type string $display_name         The user's display name.
1731   *                                        Default is the user's username.
1732   *     @type string $nickname             The user's nickname.
1733   *                                        Default is the user's username.
1734   *     @type string $first_name           The user's first name. For new users, will be used
1735   *                                        to build the first part of the user's display name
1736   *                                        if `$display_name` is not specified.
1737   *     @type string $last_name            The user's last name. For new users, will be used
1738   *                                        to build the second part of the user's display name
1739   *                                        if `$display_name` is not specified.
1740   *     @type string $description          The user's biographical description.
1741   *     @type string $rich_editing         Whether to enable the rich-editor for the user.
1742   *                                        Accepts 'true' or 'false' as a string literal,
1743   *                                        not boolean. Default 'true'.
1744   *     @type string $syntax_highlighting  Whether to enable the rich code editor for the user.
1745   *                                        Accepts 'true' or 'false' as a string literal,
1746   *                                        not boolean. Default 'true'.
1747   *     @type string $comment_shortcuts    Whether to enable comment moderation keyboard
1748   *                                        shortcuts for the user. Accepts 'true' or 'false'
1749   *                                        as a string literal, not boolean. Default 'false'.
1750   *     @type string $admin_color          Admin color scheme for the user. Default 'fresh'.
1751   *     @type bool   $use_ssl              Whether the user should always access the admin over
1752   *                                        https. Default false.
1753   *     @type string $user_registered      Date the user registered in UTC. Format is 'Y-m-d H:i:s'.
1754   *     @type string $user_activation_key  Password reset key. Default empty.
1755   *     @type bool   $spam                 Multisite only. Whether the user is marked as spam.
1756   *                                        Default false.
1757   *     @type string $show_admin_bar_front Whether to display the Admin Bar for the user
1758   *                                        on the site's front end. Accepts 'true' or 'false'
1759   *                                        as a string literal, not boolean. Default 'true'.
1760   *     @type string $role                 User's role.
1761   *     @type string $locale               User's locale. Default empty.
1762   *     @type array  $meta_input           Array of custom user meta values keyed by meta key.
1763   *                                        Default empty.
1764   * }
1765   * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
1766   *                      be created.
1767   */
1768  function wp_insert_user( $userdata ) {
1769      global $wpdb;
1770  
1771      if ( $userdata instanceof stdClass ) {
1772          $userdata = get_object_vars( $userdata );
1773      } elseif ( $userdata instanceof WP_User ) {
1774          $userdata = $userdata->to_array();
1775      }
1776  
1777      // Are we updating or creating?
1778      if ( ! empty( $userdata['ID'] ) ) {
1779          $user_id       = (int) $userdata['ID'];
1780          $update        = true;
1781          $old_user_data = get_userdata( $user_id );
1782  
1783          if ( ! $old_user_data ) {
1784              return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
1785          }
1786  
1787          // Hashed in wp_update_user(), plaintext if called directly.
1788          $user_pass = ! empty( $userdata['user_pass'] ) ? $userdata['user_pass'] : $old_user_data->user_pass;
1789      } else {
1790          $update = false;
1791          // Hash the password.
1792          $user_pass = wp_hash_password( $userdata['user_pass'] );
1793      }
1794  
1795      $sanitized_user_login = sanitize_user( $userdata['user_login'], true );
1796  
1797      /**
1798       * Filters a username after it has been sanitized.
1799       *
1800       * This filter is called before the user is created or updated.
1801       *
1802       * @since 2.0.3
1803       *
1804       * @param string $sanitized_user_login Username after it has been sanitized.
1805       */
1806      $pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
1807  
1808      // Remove any non-printable chars from the login string to see if we have ended up with an empty username.
1809      $user_login = trim( $pre_user_login );
1810  
1811      // user_login must be between 0 and 60 characters.
1812      if ( empty( $user_login ) ) {
1813          return new WP_Error( 'empty_user_login', __( 'Cannot create a user with an empty login name.' ) );
1814      } elseif ( mb_strlen( $user_login ) > 60 ) {
1815          return new WP_Error( 'user_login_too_long', __( 'Username may not be longer than 60 characters.' ) );
1816      }
1817  
1818      if ( ! $update && username_exists( $user_login ) ) {
1819          return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
1820      }
1821  
1822      /**
1823       * Filters the list of disallowed usernames.
1824       *
1825       * @since 4.4.0
1826       *
1827       * @param array $usernames Array of disallowed usernames.
1828       */
1829      $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
1830  
1831      if ( in_array( strtolower( $user_login ), array_map( 'strtolower', $illegal_logins ), true ) ) {
1832          return new WP_Error( 'invalid_username', __( 'Sorry, that username is not allowed.' ) );
1833      }
1834  
1835      /*
1836       * If a nicename is provided, remove unsafe user characters before using it.
1837       * Otherwise build a nicename from the user_login.
1838       */
1839      if ( ! empty( $userdata['user_nicename'] ) ) {
1840          $user_nicename = sanitize_user( $userdata['user_nicename'], true );
1841          if ( mb_strlen( $user_nicename ) > 50 ) {
1842              return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
1843          }
1844      } else {
1845          $user_nicename = mb_substr( $user_login, 0, 50 );
1846      }
1847  
1848      $user_nicename = sanitize_title( $user_nicename );
1849  
1850      /**
1851       * Filters a user's nicename before the user is created or updated.
1852       *
1853       * @since 2.0.3
1854       *
1855       * @param string $user_nicename The user's nicename.
1856       */
1857      $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
1858  
1859      $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 ) );
1860  
1861      if ( $user_nicename_check ) {
1862          $suffix = 2;
1863          while ( $user_nicename_check ) {
1864              // user_nicename allows 50 chars. Subtract one for a hyphen, plus the length of the suffix.
1865              $base_length         = 49 - mb_strlen( $suffix );
1866              $alt_user_nicename   = mb_substr( $user_nicename, 0, $base_length ) . "-$suffix";
1867              $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 ) );
1868              $suffix++;
1869          }
1870          $user_nicename = $alt_user_nicename;
1871      }
1872  
1873      $raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];
1874  
1875      /**
1876       * Filters a user's email before the user is created or updated.
1877       *
1878       * @since 2.0.3
1879       *
1880       * @param string $raw_user_email The user's email.
1881       */
1882      $user_email = apply_filters( 'pre_user_email', $raw_user_email );
1883  
1884      /*
1885       * If there is no update, just check for `email_exists`. If there is an update,
1886       * check if current email and new email are the same, and check `email_exists`
1887       * accordingly.
1888       */
1889      if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) )
1890          && ! defined( 'WP_IMPORTING' )
1891          && email_exists( $user_email )
1892      ) {
1893          return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
1894      }
1895  
1896      $raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
1897  
1898      /**
1899       * Filters a user's URL before the user is created or updated.
1900       *
1901       * @since 2.0.3
1902       *
1903       * @param string $raw_user_url The user's URL.
1904       */
1905      $user_url = apply_filters( 'pre_user_url', $raw_user_url );
1906  
1907      $user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];
1908  
1909      $user_activation_key = empty( $userdata['user_activation_key'] ) ? '' : $userdata['user_activation_key'];
1910  
1911      if ( ! empty( $userdata['spam'] ) && ! is_multisite() ) {
1912          return new WP_Error( 'no_spam', __( 'Sorry, marking a user as spam is only supported on Multisite.' ) );
1913      }
1914  
1915      $spam = empty( $userdata['spam'] ) ? 0 : (bool) $userdata['spam'];
1916  
1917      // Store values to save in user meta.
1918      $meta = array();
1919  
1920      $nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];
1921  
1922      /**
1923       * Filters a user's nickname before the user is created or updated.
1924       *
1925       * @since 2.0.3
1926       *
1927       * @param string $nickname The user's nickname.
1928       */
1929      $meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );
1930  
1931      $first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];
1932  
1933      /**
1934       * Filters a user's first name before the user is created or updated.
1935       *
1936       * @since 2.0.3
1937       *
1938       * @param string $first_name The user's first name.
1939       */
1940      $meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );
1941  
1942      $last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];
1943  
1944      /**
1945       * Filters a user's last name before the user is created or updated.
1946       *
1947       * @since 2.0.3
1948       *
1949       * @param string $last_name The user's last name.
1950       */
1951      $meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );
1952  
1953      if ( empty( $userdata['display_name'] ) ) {
1954          if ( $update ) {
1955              $display_name = $user_login;
1956          } elseif ( $meta['first_name'] && $meta['last_name'] ) {
1957              /* translators: 1: User's first name, 2: Last name. */
1958              $display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $meta['first_name'], $meta['last_name'] );
1959          } elseif ( $meta['first_name'] ) {
1960              $display_name = $meta['first_name'];
1961          } elseif ( $meta['last_name'] ) {
1962              $display_name = $meta['last_name'];
1963          } else {
1964              $display_name = $user_login;
1965          }
1966      } else {
1967          $display_name = $userdata['display_name'];
1968      }
1969  
1970      /**
1971       * Filters a user's display name before the user is created or updated.
1972       *
1973       * @since 2.0.3
1974       *
1975       * @param string $display_name The user's display name.
1976       */
1977      $display_name = apply_filters( 'pre_user_display_name', $display_name );
1978  
1979      $description = empty( $userdata['description'] ) ? '' : $userdata['description'];
1980  
1981      /**
1982       * Filters a user's description before the user is created or updated.
1983       *
1984       * @since 2.0.3
1985       *
1986       * @param string $description The user's description.
1987       */
1988      $meta['description'] = apply_filters( 'pre_user_description', $description );
1989  
1990      $meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];
1991  
1992      $meta['syntax_highlighting'] = empty( $userdata['syntax_highlighting'] ) ? 'true' : $userdata['syntax_highlighting'];
1993  
1994      $meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';
1995  
1996      $admin_color         = empty( $userdata['admin_color'] ) ? 'fresh' : $userdata['admin_color'];
1997      $meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );
1998  
1999      $meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? 0 : (bool) $userdata['use_ssl'];
2000  
2001      $meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];
2002  
2003      $meta['locale'] = isset( $userdata['locale'] ) ? $userdata['locale'] : '';
2004  
2005      $compacted = compact( 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'display_name' );
2006      $data      = wp_unslash( $compacted );
2007  
2008      if ( ! $update ) {
2009          $data = $data + compact( 'user_login' );
2010      }
2011  
2012      if ( is_multisite() ) {
2013          $data = $data + compact( 'spam' );
2014      }
2015  
2016      /**
2017       * Filters user data before the record is created or updated.
2018       *
2019       * It only includes data in the users table, not any user metadata.
2020       *
2021       * @since 4.9.0
2022       * @since 5.8.0 The $userdata parameter was added.
2023       *
2024       * @param array    $data {
2025       *     Values and keys for the user.
2026       *
2027       *     @type string $user_login      The user's login. Only included if $update == false
2028       *     @type string $user_pass       The user's password.
2029       *     @type string $user_email      The user's email.
2030       *     @type string $user_url        The user's url.
2031       *     @type string $user_nicename   The user's nice name. Defaults to a URL-safe version of user's login
2032       *     @type string $display_name    The user's display name.
2033       *     @type string $user_registered MySQL timestamp describing the moment when the user registered. Defaults to
2034       *                                   the current UTC timestamp.
2035       * }
2036       * @param bool     $update   Whether the user is being updated rather than created.
2037       * @param int|null $user_id  ID of the user to be updated, or NULL if the user is being created.
2038       * @param array    $userdata The raw array of data passed to wp_insert_user().
2039       */
2040      $data = apply_filters( 'wp_pre_insert_user_data', $data, $update, ( $update ? $user_id : null ), $userdata );
2041  
2042      if ( empty( $data ) || ! is_array( $data ) ) {
2043          return new WP_Error( 'empty_data', __( 'Not enough data to create this user.' ) );
2044      }
2045  
2046      if ( $update ) {
2047          if ( $user_email !== $old_user_data->user_email || $user_pass !== $old_user_data->user_pass ) {
2048              $data['user_activation_key'] = '';
2049          }
2050          $wpdb->update( $wpdb->users, $data, array( 'ID' => $user_id ) );
2051      } else {
2052          $wpdb->insert( $wpdb->users, $data );
2053          $user_id = (int) $wpdb->insert_id;
2054      }
2055  
2056      $user = new WP_User( $user_id );
2057  
2058      /**
2059       * Filters a user's meta values and keys immediately after the user is created or updated
2060       * and before any user meta is inserted or updated.
2061       *
2062       * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`.
2063       *
2064       * For custom meta fields, see the {@see 'insert_custom_user_meta'} filter.
2065       *
2066       * @since 4.4.0
2067       * @since 5.8.0 The $userdata parameter was added.
2068       *
2069       * @param array $meta {
2070       *     Default meta values and keys for the user.
2071       *
2072       *     @type string   $nickname             The user's nickname. Default is the user's username.
2073       *     @type string   $first_name           The user's first name.
2074       *     @type string   $last_name            The user's last name.
2075       *     @type string   $description          The user's description.
2076       *     @type string   $rich_editing         Whether to enable the rich-editor for the user. Default 'true'.
2077       *     @type string   $syntax_highlighting  Whether to enable the rich code editor for the user. Default 'true'.
2078       *     @type string   $comment_shortcuts    Whether to enable keyboard shortcuts for the user. Default 'false'.
2079       *     @type string   $admin_color          The color scheme for a user's admin screen. Default 'fresh'.
2080       *     @type int|bool $use_ssl              Whether to force SSL on the user's admin area. 0|false if SSL
2081       *                                          is not forced.
2082       *     @type string   $show_admin_bar_front Whether to show the admin bar on the front end for the user.
2083       *                                          Default 'true'.
2084       *     @type string   $locale               User's locale. Default empty.
2085       * }
2086       * @param WP_User $user     User object.
2087       * @param bool    $update   Whether the user is being updated rather than created.
2088       * @param array   $userdata The raw array of data passed to wp_insert_user().
2089       */
2090      $meta = apply_filters( 'insert_user_meta', $meta, $user, $update, $userdata );
2091  
2092      $custom_meta = array();
2093      if ( array_key_exists( 'meta_input', $userdata ) && is_array( $userdata['meta_input'] ) && ! empty( $userdata['meta_input'] ) ) {
2094          $custom_meta = $userdata['meta_input'];
2095      }
2096  
2097      /**
2098       * Filters a user's custom meta values and keys immediately after the user is created or updated
2099       * and before any user meta is inserted or updated.
2100       *
2101       * For non-custom meta fields, see the {@see 'insert_user_meta'} filter.
2102       *
2103       * @since 5.9.0
2104       *
2105       * @param array   $custom_meta Array of custom user meta values keyed by meta key.
2106       * @param WP_User $user        User object.
2107       * @param bool    $update      Whether the user is being updated rather than created.
2108       * @param array   $userdata    The raw array of data passed to wp_insert_user().
2109       */
2110      $custom_meta = apply_filters( 'insert_custom_user_meta', $custom_meta, $user, $update, $userdata );
2111  
2112      $meta = array_merge( $meta, $custom_meta );
2113  
2114      // Update user meta.
2115      foreach ( $meta as $key => $value ) {
2116          update_user_meta( $user_id, $key, $value );
2117      }
2118  
2119      foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
2120          if ( isset( $userdata[ $key ] ) ) {
2121              update_user_meta( $user_id, $key, $userdata[ $key ] );
2122          }
2123      }
2124  
2125      if ( isset( $userdata['role'] ) ) {
2126          $user->set_role( $userdata['role'] );
2127      } elseif ( ! $update ) {
2128          $user->set_role( get_option( 'default_role' ) );
2129      }
2130  
2131      clean_user_cache( $user_id );
2132  
2133      if ( $update ) {
2134          /**
2135           * Fires immediately after an existing user is updated.
2136           *
2137           * @since 2.0.0
2138           * @since 5.8.0 The $userdata parameter was added.
2139           *
2140           * @param int     $user_id       User ID.
2141           * @param WP_User $old_user_data Object containing user's data prior to update.
2142           * @param array   $userdata      The raw array of data passed to wp_insert_user().
2143           */
2144          do_action( 'profile_update', $user_id, $old_user_data, $userdata );
2145  
2146          if ( isset( $userdata['spam'] ) && $userdata['spam'] != $old_user_data->spam ) {
2147              if ( 1 == $userdata['spam'] ) {
2148                  /**
2149                   * Fires after the user is marked as a SPAM user.
2150                   *
2151                   * @since 3.0.0
2152                   *
2153                   * @param int $user_id ID of the user marked as SPAM.
2154                   */
2155                  do_action( 'make_spam_user', $user_id );
2156              } else {
2157                  /**
2158                   * Fires after the user is marked as a HAM user. Opposite of SPAM.
2159                   *
2160                   * @since 3.0.0
2161                   *
2162                   * @param int $user_id ID of the user marked as HAM.
2163                   */
2164                  do_action( 'make_ham_user', $user_id );
2165              }
2166          }
2167      } else {
2168          /**
2169           * Fires immediately after a new user is registered.
2170           *
2171           * @since 1.5.0
2172           * @since 5.8.0 The $userdata parameter was added.
2173           *
2174           * @param int   $user_id  User ID.
2175           * @param array $userdata The raw array of data passed to wp_insert_user().
2176           */
2177          do_action( 'user_register', $user_id, $userdata );
2178      }
2179  
2180      return $user_id;
2181  }
2182  
2183  /**
2184   * Update a user in the database.
2185   *
2186   * It is possible to update a user's password by specifying the 'user_pass'
2187   * value in the $userdata parameter array.
2188   *
2189   * If current user's password is being updated, then the cookies will be
2190   * cleared.
2191   *
2192   * @since 2.0.0
2193   *
2194   * @see wp_insert_user() For what fields can be set in $userdata.
2195   *
2196   * @param array|object|WP_User $userdata An array of user data or a user object of type stdClass or WP_User.
2197   * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
2198   */
2199  function wp_update_user( $userdata ) {
2200      if ( $userdata instanceof stdClass ) {
2201          $userdata = get_object_vars( $userdata );
2202      } elseif ( $userdata instanceof WP_User ) {
2203          $userdata = $userdata->to_array();
2204      }
2205  
2206      $user_id = isset( $userdata['ID'] ) ? (int) $userdata['ID'] : 0;
2207      if ( ! $user_id ) {
2208          return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
2209      }
2210  
2211      // First, get all of the original fields.
2212      $user_obj = get_userdata( $user_id );
2213      if ( ! $user_obj ) {
2214          return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
2215      }
2216  
2217      $user = $user_obj->to_array();
2218  
2219      // Add additional custom fields.
2220      foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
2221          $user[ $key ] = get_user_meta( $user_id, $key, true );
2222      }
2223  
2224      // Escape data pulled from DB.
2225      $user = add_magic_quotes( $user );
2226  
2227      if ( ! empty( $userdata['user_pass'] ) && $userdata['user_pass'] !== $user_obj->user_pass ) {
2228          // If password is changing, hash it now.
2229          $plaintext_pass        = $userdata['user_pass'];
2230          $userdata['user_pass'] = wp_hash_password( $userdata['user_pass'] );
2231  
2232          /**
2233           * Filters whether to send the password change email.
2234           *
2235           * @since 4.3.0
2236           *
2237           * @see wp_insert_user() For `$user` and `$userdata` fields.
2238           *
2239           * @param bool  $send     Whether to send the email.
2240           * @param array $user     The original user array.
2241           * @param array $userdata The updated user array.
2242           */
2243          $send_password_change_email = apply_filters( 'send_password_change_email', true, $user, $userdata );
2244      }
2245  
2246      if ( isset( $userdata['user_email'] ) && $user['user_email'] !== $userdata['user_email'] ) {
2247          /**
2248           * Filters whether to send the email change email.
2249           *
2250           * @since 4.3.0
2251           *
2252           * @see wp_insert_user() For `$user` and `$userdata` fields.
2253           *
2254           * @param bool  $send     Whether to send the email.
2255           * @param array $user     The original user array.
2256           * @param array $userdata The updated user array.
2257           */
2258          $send_email_change_email = apply_filters( 'send_email_change_email', true, $user, $userdata );
2259      }
2260  
2261      clean_user_cache( $user_obj );
2262  
2263      // Merge old and new fields with new fields overwriting old ones.
2264      $userdata = array_merge( $user, $userdata );
2265      $user_id  = wp_insert_user( $userdata );
2266  
2267      if ( is_wp_error( $user_id ) ) {
2268          return $user_id;
2269      }
2270  
2271      $blog_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
2272  
2273      $switched_locale = false;
2274      if ( ! empty( $send_password_change_email ) || ! empty( $send_email_change_email ) ) {
2275          $switched_locale = switch_to_locale( get_user_locale( $user_id ) );
2276      }
2277  
2278      if ( ! empty( $send_password_change_email ) ) {
2279          /* translators: Do not translate USERNAME, ADMIN_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
2280          $pass_change_text = __(
2281              'Hi ###USERNAME###,
2282  
2283  This notice confirms that your password was changed on ###SITENAME###.
2284  
2285  If you did not change your password, please contact the Site Administrator at
2286  ###ADMIN_EMAIL###
2287  
2288  This email has been sent to ###EMAIL###
2289  
2290  Regards,
2291  All at ###SITENAME###
2292  ###SITEURL###'
2293          );
2294  
2295          $pass_change_email = array(
2296              'to'      => $user['user_email'],
2297              /* translators: Password change notification email subject. %s: Site title. */
2298              'subject' => __( '[%s] Password Changed' ),
2299              'message' => $pass_change_text,
2300              'headers' => '',
2301          );
2302  
2303          /**
2304           * Filters the contents of the email sent when the user's password is changed.
2305           *
2306           * @since 4.3.0
2307           *
2308           * @param array $pass_change_email {
2309           *     Used to build wp_mail().
2310           *
2311           *     @type string $to      The intended recipients. Add emails in a comma separated string.
2312           *     @type string $subject The subject of the email.
2313           *     @type string $message The content of the email.
2314           *         The following strings have a special meaning and will get replaced dynamically:
2315           *         - ###USERNAME###    The current user's username.
2316           *         - ###ADMIN_EMAIL### The admin email in case this was unexpected.
2317           *         - ###EMAIL###       The user's email address.
2318           *         - ###SITENAME###    The name of the site.
2319           *         - ###SITEURL###     The URL to the site.
2320           *     @type string $headers Headers. Add headers in a newline (\r\n) separated string.
2321           * }
2322           * @param array $user     The original user array.
2323           * @param array $userdata The updated user array.
2324           */
2325          $pass_change_email = apply_filters( 'password_change_email', $pass_change_email, $user, $userdata );
2326  
2327          $pass_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $pass_change_email['message'] );
2328          $pass_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $pass_change_email['message'] );
2329          $pass_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $pass_change_email['message'] );
2330          $pass_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $pass_change_email['message'] );
2331          $pass_change_email['message'] = str_replace( '###SITEURL###', home_url(), $pass_change_email['message'] );
2332  
2333          wp_mail( $pass_change_email['to'], sprintf( $pass_change_email['subject'], $blog_name ), $pass_change_email['message'], $pass_change_email['headers'] );
2334      }
2335  
2336      if ( ! empty( $send_email_change_email ) ) {
2337          /* translators: Do not translate USERNAME, ADMIN_EMAIL, NEW_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
2338          $email_change_text = __(
2339              'Hi ###USERNAME###,
2340  
2341  This notice confirms that your email address on ###SITENAME### was changed to ###NEW_EMAIL###.
2342  
2343  If you did not change your email, please contact the Site Administrator at
2344  ###ADMIN_EMAIL###
2345  
2346  This email has been sent to ###EMAIL###
2347  
2348  Regards,
2349  All at ###SITENAME###
2350  ###SITEURL###'
2351          );
2352  
2353          $email_change_email = array(
2354              'to'      => $user['user_email'],
2355              /* translators: Email change notification email subject. %s: Site title. */
2356              'subject' => __( '[%s] Email Changed' ),
2357              'message' => $email_change_text,
2358              'headers' => '',
2359          );
2360  
2361          /**
2362           * Filters the contents of the email sent when the user's email is changed.
2363           *
2364           * @since 4.3.0
2365           *
2366           * @param array $email_change_email {
2367           *     Used to build wp_mail().
2368           *
2369           *     @type string $to      The intended recipients.
2370           *     @type string $subject The subject of the email.
2371           *     @type string $message The content of the email.
2372           *         The following strings have a special meaning and will get replaced dynamically:
2373           *         - ###USERNAME###    The current user's username.
2374           *         - ###ADMIN_EMAIL### The admin email in case this was unexpected.
2375           *         - ###NEW_EMAIL###   The new email address.
2376           *         - ###EMAIL###       The old email address.
2377           *         - ###SITENAME###    The name of the site.
2378           *         - ###SITEURL###     The URL to the site.
2379           *     @type string $headers Headers.
2380           * }
2381           * @param array $user     The original user array.
2382           * @param array $userdata The updated user array.
2383           */
2384          $email_change_email = apply_filters( 'email_change_email', $email_change_email, $user, $userdata );
2385  
2386          $email_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $email_change_email['message'] );
2387          $email_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $email_change_email['message'] );
2388          $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $userdata['user_email'], $email_change_email['message'] );
2389          $email_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $email_change_email['message'] );
2390          $email_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $email_change_email['message'] );
2391          $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
2392  
2393          wp_mail( $email_change_email['to'], sprintf( $email_change_email['subject'], $blog_name ), $email_change_email['message'], $email_change_email['headers'] );
2394      }
2395  
2396      if ( $switched_locale ) {
2397          restore_previous_locale();
2398      }
2399  
2400      // Update the cookies if the password changed.
2401      $current_user = wp_get_current_user();
2402      if ( $current_user->ID == $user_id ) {
2403          if ( isset( $plaintext_pass ) ) {
2404              wp_clear_auth_cookie();
2405  
2406              // Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
2407              // If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
2408              $logged_in_cookie = wp_parse_auth_cookie( '', 'logged_in' );
2409              /** This filter is documented in wp-includes/pluggable.php */
2410              $default_cookie_life = apply_filters( 'auth_cookie_expiration', ( 2 * DAY_IN_SECONDS ), $user_id, false );
2411              $remember            = false;
2412              if ( false !== $logged_in_cookie && ( $logged_in_cookie['expiration'] - time() ) > $default_cookie_life ) {
2413                  $remember = true;
2414              }
2415  
2416              wp_set_auth_cookie( $user_id, $remember );
2417          }
2418      }
2419  
2420      return $user_id;
2421  }
2422  
2423  /**
2424   * A simpler way of inserting a user into the database.
2425   *
2426   * Creates a new user with just the username, password, and email. For more
2427   * complex user creation use wp_insert_user() to specify more information.
2428   *
2429   * @since 2.0.0
2430   *
2431   * @see wp_insert_user() More complete way to create a new user.
2432   *
2433   * @param string $username The user's username.
2434   * @param string $password The user's password.
2435   * @param string $email    Optional. The user's email. Default empty.
2436   * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
2437   *                      be created.
2438   */
2439  function wp_create_user( $username, $password, $email = '' ) {
2440      $user_login = wp_slash( $username );
2441      $user_email = wp_slash( $email );
2442      $user_pass  = $password;
2443  
2444      $userdata = compact( 'user_login', 'user_email', 'user_pass' );
2445      return wp_insert_user( $userdata );
2446  }
2447  
2448  /**
2449   * Returns a list of meta keys to be (maybe) populated in wp_update_user().
2450   *
2451   * The list of keys returned via this function are dependent on the presence
2452   * of those keys in the user meta data to be set.
2453   *
2454   * @since 3.3.0
2455   * @access private
2456   *
2457   * @param WP_User $user WP_User instance.
2458   * @return string[] List of user keys to be populated in wp_update_user().
2459   */
2460  function _get_additional_user_keys( $user ) {
2461      $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front', 'locale' );
2462      return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
2463  }
2464  
2465  /**
2466   * Set up the user contact methods.
2467   *
2468   * Default contact methods were removed in 3.6. A filter dictates contact methods.
2469   *
2470   * @since 3.7.0
2471   *
2472   * @param WP_User|null $user Optional. WP_User object.
2473   * @return string[] Array of contact method labels keyed by contact method.
2474   */
2475  function wp_get_user_contact_methods( $user = null ) {
2476      $methods = array();
2477      if ( get_site_option( 'initial_db_version' ) < 23588 ) {
2478          $methods = array(
2479              'aim'    => __( 'AIM' ),
2480              'yim'    => __( 'Yahoo IM' ),
2481              'jabber' => __( 'Jabber / Google Talk' ),
2482          );
2483      }
2484  
2485      /**
2486       * Filters the user contact methods.
2487       *
2488       * @since 2.9.0
2489       *
2490       * @param string[]     $methods Array of contact method labels keyed by contact method.
2491       * @param WP_User|null $user    WP_User object or null if none was provided.
2492       */
2493      return apply_filters( 'user_contactmethods', $methods, $user );
2494  }
2495  
2496  /**
2497   * The old private function for setting up user contact methods.
2498   *
2499   * Use wp_get_user_contact_methods() instead.
2500   *
2501   * @since 2.9.0
2502   * @access private
2503   *
2504   * @param WP_User|null $user Optional. WP_User object. Default null.
2505   * @return string[] Array of contact method labels keyed by contact method.
2506   */
2507  function _wp_get_user_contactmethods( $user = null ) {
2508      return wp_get_user_contact_methods( $user );
2509  }
2510  
2511  /**
2512   * Gets the text suggesting how to create strong passwords.
2513   *
2514   * @since 4.1.0
2515   *
2516   * @return string The password hint text.
2517   */
2518  function wp_get_password_hint() {
2519      $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; ).' );
2520  
2521      /**
2522       * Filters the text describing the site's password complexity policy.
2523       *
2524       * @since 4.1.0
2525       *
2526       * @param string $hint The password hint text.
2527       */
2528      return apply_filters( 'password_hint', $hint );
2529  }
2530  
2531  /**
2532   * Creates, stores, then returns a password reset key for user.
2533   *
2534   * @since 4.4.0
2535   *
2536   * @global PasswordHash $wp_hasher Portable PHP password hashing framework.
2537   *
2538   * @param WP_User $user User to retrieve password reset key for.
2539   * @return string|WP_Error Password reset key on success. WP_Error on error.
2540   */
2541  function get_password_reset_key( $user ) {
2542      global $wp_hasher;
2543  
2544      if ( ! ( $user instanceof WP_User ) ) {
2545          return new WP_Error( 'invalidcombo', __( '<strong>Error</strong>: There is no account with that username or email address.' ) );
2546      }
2547  
2548      /**
2549       * Fires before a new password is retrieved.
2550       *
2551       * Use the {@see 'retrieve_password'} hook instead.
2552       *
2553       * @since 1.5.0
2554       * @deprecated 1.5.1 Misspelled. Use {@see 'retrieve_password'} hook instead.
2555       *
2556       * @param string $user_login The user login name.
2557       */
2558      do_action_deprecated( 'retreive_password', array( $user->user_login ), '1.5.1', 'retrieve_password' );
2559  
2560      /**
2561       * Fires before a new password is retrieved.
2562       *
2563       * @since 1.5.1
2564       *
2565       * @param string $user_login The user login name.
2566       */
2567      do_action( 'retrieve_password', $user->user_login );
2568  
2569      $allow = true;
2570      if ( is_multisite() && is_user_spammy( $user ) ) {
2571          $allow = false;
2572      }
2573  
2574      /**
2575       * Filters whether to allow a password to be reset.
2576       *
2577       * @since 2.7.0
2578       *
2579       * @param bool $allow   Whether to allow the password to be reset. Default true.
2580       * @param int  $user_id The ID of the user attempting to reset a password.
2581       */
2582      $allow = apply_filters( 'allow_password_reset', $allow, $user->ID );
2583  
2584      if ( ! $allow ) {
2585          return new WP_Error( 'no_password_reset', __( 'Password reset is not allowed for this user' ) );
2586      } elseif ( is_wp_error( $allow ) ) {
2587          return $allow;
2588      }
2589  
2590      // Generate something random for a password reset key.
2591      $key = wp_generate_password( 20, false );
2592  
2593      /**
2594       * Fires when a password reset key is generated.
2595       *
2596       * @since 2.5.0
2597       *
2598       * @param string $user_login The username for the user.
2599       * @param string $key        The generated password reset key.
2600       */
2601      do_action( 'retrieve_password_key', $user->user_login, $key );
2602  
2603      // Now insert the key, hashed, into the DB.
2604      if ( empty( $wp_hasher ) ) {
2605          require_once  ABSPATH . WPINC . '/class-phpass.php';
2606          $wp_hasher = new PasswordHash( 8, true );
2607      }
2608  
2609      $hashed = time() . ':' . $wp_hasher->HashPassword( $key );
2610  
2611      $key_saved = wp_update_user(
2612          array(
2613              'ID'                  => $user->ID,
2614              'user_activation_key' => $hashed,
2615          )
2616      );
2617  
2618      if ( is_wp_error( $key_saved ) ) {
2619          return $key_saved;
2620      }
2621  
2622      return $key;
2623  }
2624  
2625  /**
2626   * Retrieves a user row based on password reset key and login
2627   *
2628   * A key is considered 'expired' if it exactly matches the value of the
2629   * user_activation_key field, rather than being matched after going through the
2630   * hashing process. This field is now hashed; old values are no longer accepted
2631   * but have a different WP_Error code so good user feedback can be provided.
2632   *
2633   * @since 3.1.0
2634   *
2635   * @global wpdb         $wpdb      WordPress database object for queries.
2636   * @global PasswordHash $wp_hasher Portable PHP password hashing framework instance.
2637   *
2638   * @param string $key       Hash to validate sending user's password.
2639   * @param string $login     The user login.
2640   * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
2641   */
2642  function check_password_reset_key( $key, $login ) {
2643      global $wpdb, $wp_hasher;
2644  
2645      $key = preg_replace( '/[^a-z0-9]/i', '', $key );
2646  
2647      if ( empty( $key ) || ! is_string( $key ) ) {
2648          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
2649      }
2650  
2651      if ( empty( $login ) || ! is_string( $login ) ) {
2652          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
2653      }
2654  
2655      $user = get_user_by( 'login', $login );
2656  
2657      if ( ! $user ) {
2658          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
2659      }
2660  
2661      if ( empty( $wp_hasher ) ) {
2662          require_once  ABSPATH . WPINC . '/class-phpass.php';
2663          $wp_hasher = new PasswordHash( 8, true );
2664      }
2665  
2666      /**
2667       * Filters the expiration time of password reset keys.
2668       *
2669       * @since 4.3.0
2670       *
2671       * @param int $expiration The expiration time in seconds.
2672       */
2673      $expiration_duration = apply_filters( 'password_reset_expiration', DAY_IN_SECONDS );
2674  
2675      if ( false !== strpos( $user->user_activation_key, ':' ) ) {
2676          list( $pass_request_time, $pass_key ) = explode( ':', $user->user_activation_key, 2 );
2677          $expiration_time                      = $pass_request_time + $expiration_duration;
2678      } else {
2679          $pass_key        = $user->user_activation_key;
2680          $expiration_time = false;
2681      }
2682  
2683      if ( ! $pass_key ) {
2684          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
2685      }
2686  
2687      $hash_is_correct = $wp_hasher->CheckPassword( $key, $pass_key );
2688  
2689      if ( $hash_is_correct && $expiration_time && time() < $expiration_time ) {
2690          return $user;
2691      } elseif ( $hash_is_correct && $expiration_time ) {
2692          // Key has an expiration time that's passed.
2693          return new WP_Error( 'expired_key', __( 'Invalid key.' ) );
2694      }
2695  
2696      if ( hash_equals( $user->user_activation_key, $key ) || ( $hash_is_correct && ! $expiration_time ) ) {
2697          $return  = new WP_Error( 'expired_key', __( 'Invalid key.' ) );
2698          $user_id = $user->ID;
2699  
2700          /**
2701           * Filters the return value of check_password_reset_key() when an
2702           * old-style key is used.
2703           *
2704           * @since 3.7.0 Previously plain-text keys were stored in the database.
2705           * @since 4.3.0 Previously key hashes were stored without an expiration time.
2706           *
2707           * @param WP_Error $return  A WP_Error object denoting an expired key.
2708           *                          Return a WP_User object to validate the key.
2709           * @param int      $user_id The matched user ID.
2710           */
2711          return apply_filters( 'password_reset_key_expired', $return, $user_id );
2712      }
2713  
2714      return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
2715  }
2716  
2717  /**
2718   * Handles sending a password retrieval email to a user.
2719   *
2720   * @since 2.5.0
2721   * @since 5.7.0 Added `$user_login` parameter.
2722   *
2723   * @global wpdb         $wpdb       WordPress database abstraction object.
2724   * @global PasswordHash $wp_hasher  Portable PHP password hashing framework.
2725   *
2726   * @param string $user_login Optional. Username to send a password retrieval email for.
2727   *                           Defaults to `$_POST['user_login']` if not set.
2728   * @return true|WP_Error True when finished, WP_Error object on error.
2729   */
2730  function retrieve_password( $user_login = null ) {
2731      $errors    = new WP_Error();
2732      $user_data = false;
2733  
2734      // Use the passed $user_login if available, otherwise use $_POST['user_login'].
2735      if ( ! $user_login && ! empty( $_POST['user_login'] ) ) {
2736          $user_login = $_POST['user_login'];
2737      }
2738  
2739      if ( empty( $user_login ) ) {
2740          $errors->add( 'empty_username', __( '<strong>Error</strong>: Please enter a username or email address.' ) );
2741      } elseif ( strpos( $user_login, '@' ) ) {
2742          $user_data = get_user_by( 'email', trim( wp_unslash( $user_login ) ) );
2743          if ( empty( $user_data ) ) {
2744              $errors->add( 'invalid_email', __( '<strong>Error</strong>: There is no account with that username or email address.' ) );
2745          }
2746      } else {
2747          $user_data = get_user_by( 'login', trim( wp_unslash( $user_login ) ) );
2748      }
2749  
2750      /**
2751       * Filters the user data during a password reset request.
2752       *
2753       * Allows, for example, custom validation using data other than username or email address.
2754       *
2755       * @since 5.7.0
2756       *
2757       * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
2758       * @param WP_Error      $errors    A WP_Error object containing any errors generated
2759       *                                 by using invalid credentials.
2760       */
2761      $user_data = apply_filters( 'lostpassword_user_data', $user_data, $errors );
2762  
2763      /**
2764       * Fires before errors are returned from a password reset request.
2765       *
2766       * @since 2.1.0
2767       * @since 4.4.0 Added the `$errors` parameter.
2768       * @since 5.4.0 Added the `$user_data` parameter.
2769       *
2770       * @param WP_Error      $errors    A WP_Error object containing any errors generated
2771       *                                 by using invalid credentials.
2772       * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
2773       */
2774      do_action( 'lostpassword_post', $errors, $user_data );
2775  
2776      /**
2777       * Filters the errors encountered on a password reset request.
2778       *
2779       * The filtered WP_Error object may, for example, contain errors for an invalid
2780       * username or email address. A WP_Error object should always be returned,
2781       * but may or may not contain errors.
2782       *
2783       * If any errors are present in $errors, this will abort the password reset request.
2784       *
2785       * @since 5.5.0
2786       *
2787       * @param WP_Error      $errors    A WP_Error object containing any errors generated
2788       *                                 by using invalid credentials.
2789       * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
2790       */
2791      $errors = apply_filters( 'lostpassword_errors', $errors, $user_data );
2792  
2793      if ( $errors->has_errors() ) {
2794          return $errors;
2795      }
2796  
2797      if ( ! $user_data ) {
2798          $errors->add( 'invalidcombo', __( '<strong>Error</strong>: There is no account with that username or email address.' ) );
2799          return $errors;
2800      }
2801  
2802      // Redefining user_login ensures we return the right case in the email.
2803      $user_login = $user_data->user_login;
2804      $user_email = $user_data->user_email;
2805      $key        = get_password_reset_key( $user_data );
2806  
2807      if ( is_wp_error( $key ) ) {
2808          return $key;
2809      }
2810  
2811      // Localize password reset message content for user.
2812      $locale = get_user_locale( $user_data );
2813  
2814      $switched_locale = switch_to_locale( $locale );
2815  
2816      if ( is_multisite() ) {
2817          $site_name = get_network()->site_name;
2818      } else {
2819          /*
2820           * The blogname option is escaped with esc_html on the way into the database
2821           * in sanitize_option. We want to reverse this for the plain text arena of emails.
2822           */
2823          $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
2824      }
2825  
2826      $message = __( 'Someone has requested a password reset for the following account:' ) . "\r\n\r\n";
2827      /* translators: %s: Site name. */
2828      $message .= sprintf( __( 'Site Name: %s' ), $site_name ) . "\r\n\r\n";
2829      /* translators: %s: User login. */
2830      $message .= sprintf( __( 'Username: %s' ), $user_login ) . "\r\n\r\n";
2831      $message .= __( 'If this was a mistake, ignore this email and nothing will happen.' ) . "\r\n\r\n";
2832      $message .= __( 'To reset your password, visit the following address:' ) . "\r\n\r\n";
2833      $message .= network_site_url( "wp-login.php?action=rp&key=$key&login=" . rawurlencode( $user_login ), 'login' ) . '&wp_lang=' . $locale . "\r\n\r\n";
2834  
2835      if ( ! is_user_logged_in() ) {
2836          $requester_ip = $_SERVER['REMOTE_ADDR'];
2837          if ( $requester_ip ) {
2838              $message .= sprintf(
2839                  /* translators: %s: IP address of password reset requester. */
2840                  __( 'This password reset request originated from the IP address %s.' ),
2841                  $requester_ip
2842              ) . "\r\n";
2843          }
2844      }
2845  
2846      /* translators: Password reset notification email subject. %s: Site title. */
2847      $title = sprintf( __( '[%s] Password Reset' ), $site_name );
2848  
2849      /**
2850       * Filters the subject of the password reset email.
2851       *
2852       * @since 2.8.0
2853       * @since 4.4.0 Added the `$user_login` and `$user_data` parameters.
2854       *
2855       * @param string  $title      Email subject.
2856       * @param string  $user_login The username for the user.
2857       * @param WP_User $user_data  WP_User object.
2858       */
2859      $title = apply_filters( 'retrieve_password_title', $title, $user_login, $user_data );
2860  
2861      /**
2862       * Filters the message body of the password reset mail.
2863       *
2864       * If the filtered message is empty, the password reset email will not be sent.
2865       *
2866       * @since 2.8.0
2867       * @since 4.1.0 Added `$user_login` and `$user_data` parameters.
2868       *
2869       * @param string  $message    Email message.
2870       * @param string  $key        The activation key.
2871       * @param string  $user_login The username for the user.
2872       * @param WP_User $user_data  WP_User object.
2873       */
2874      $message = apply_filters( 'retrieve_password_message', $message, $key, $user_login, $user_data );
2875  
2876      if ( $switched_locale ) {
2877          restore_previous_locale();
2878      }
2879  
2880      if ( $message && ! wp_mail( $user_email, wp_specialchars_decode( $title ), $message ) ) {
2881          $errors->add(
2882              'retrieve_password_email_failure',
2883              sprintf(
2884                  /* translators: %s: Documentation URL. */
2885                  __( '<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>.' ),
2886                  esc_url( __( 'https://wordpress.org/support/article/resetting-your-password/' ) )
2887              )
2888          );
2889          return $errors;
2890      }
2891  
2892      return true;
2893  }
2894  
2895  /**
2896   * Handles resetting the user's password.
2897   *
2898   * @since 2.5.0
2899   *
2900   * @param WP_User $user     The user
2901   * @param string  $new_pass New password for the user in plaintext
2902   */
2903  function reset_password( $user, $new_pass ) {
2904      /**
2905       * Fires before the user's password is reset.
2906       *
2907       * @since 1.5.0
2908       *
2909       * @param WP_User $user     The user.
2910       * @param string  $new_pass New user password.
2911       */
2912      do_action( 'password_reset', $user, $new_pass );
2913  
2914      wp_set_password( $new_pass, $user->ID );
2915      update_user_meta( $user->ID, 'default_password_nag', false );
2916  
2917      /**
2918       * Fires after the user's password is reset.
2919       *
2920       * @since 4.4.0
2921       *
2922       * @param WP_User $user     The user.
2923       * @param string  $new_pass New user password.
2924       */
2925      do_action( 'after_password_reset', $user, $new_pass );
2926  }
2927  
2928  /**
2929   * Handles registering a new user.
2930   *
2931   * @since 2.5.0
2932   *
2933   * @param string $user_login User's username for logging in
2934   * @param string $user_email User's email address to send password and add
2935   * @return int|WP_Error Either user's ID or error on failure.
2936   */
2937  function register_new_user( $user_login, $user_email ) {
2938      $errors = new WP_Error();
2939  
2940      $sanitized_user_login = sanitize_user( $user_login );
2941      /**
2942       * Filters the email address of a user being registered.
2943       *
2944       * @since 2.1.0
2945       *
2946       * @param string $user_email The email address of the new user.
2947       */
2948      $user_email = apply_filters( 'user_registration_email', $user_email );
2949  
2950      // Check the username.
2951      if ( '' === $sanitized_user_login ) {
2952          $errors->add( 'empty_username', __( '<strong>Error</strong>: Please enter a username.' ) );
2953      } elseif ( ! validate_username( $user_login ) ) {
2954          $errors->add( 'invalid_username', __( '<strong>Error</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
2955          $sanitized_user_login = '';
2956      } elseif ( username_exists( $sanitized_user_login ) ) {
2957          $errors->add( 'username_exists', __( '<strong>Error</strong>: This username is already registered. Please choose another one.' ) );
2958  
2959      } else {
2960          /** This filter is documented in wp-includes/user.php */
2961          $illegal_user_logins = (array) apply_filters( 'illegal_user_logins', array() );
2962          if ( in_array( strtolower( $sanitized_user_login ), array_map( 'strtolower', $illegal_user_logins ), true ) ) {
2963              $errors->add( 'invalid_username', __( '<strong>Error</strong>: Sorry, that username is not allowed.' ) );
2964          }
2965      }
2966  
2967      // Check the email address.
2968      if ( '' === $user_email ) {
2969          $errors->add( 'empty_email', __( '<strong>Error</strong>: Please type your email address.' ) );
2970      } elseif ( ! is_email( $user_email ) ) {
2971          $errors->add( 'invalid_email', __( '<strong>Error</strong>: The email address isn&#8217;t correct.' ) );
2972          $user_email = '';
2973      } elseif ( email_exists( $user_email ) ) {
2974          $errors->add( 'email_exists', __( '<strong>Error</strong>: This email is already registered. Please choose another one.' ) );
2975      }
2976  
2977      /**
2978       * Fires when submitting registration form data, before the user is created.
2979       *
2980       * @since 2.1.0
2981       *
2982       * @param string   $sanitized_user_login The submitted username after being sanitized.
2983       * @param string   $user_email           The submitted email.
2984       * @param WP_Error $errors               Contains any errors with submitted username and email,
2985       *                                       e.g., an empty field, an invalid username or email,
2986       *                                       or an existing username or email.
2987       */
2988      do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
2989  
2990      /**
2991       * Filters the errors encountered when a new user is being registered.
2992       *
2993       * The filtered WP_Error object may, for example, contain errors for an invalid
2994       * or existing username or email address. A WP_Error object should always be returned,
2995       * but may or may not contain errors.
2996       *
2997       * If any errors are present in $errors, this will abort the user's registration.
2998       *
2999       * @since 2.1.0
3000       *
3001       * @param WP_Error $errors               A WP_Error object containing any errors encountered
3002       *                                       during registration.
3003       * @param string   $sanitized_user_login User's username after it has been sanitized.
3004       * @param string   $user_email           User's email.
3005       */
3006      $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
3007  
3008      if ( $errors->has_errors() ) {
3009          return $errors;
3010      }
3011  
3012      $user_pass = wp_generate_password( 12, false );
3013      $user_id   = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
3014      if ( ! $user_id || is_wp_error( $user_id ) ) {
3015          $errors->add(
3016              'registerfail',
3017              sprintf(
3018                  /* translators: %s: Admin email address. */
3019                  __( '<strong>Error</strong>: Couldn&#8217;t register you&hellip; please contact the <a href="mailto:%s">site admin</a>!' ),
3020                  get_option( 'admin_email' )
3021              )
3022          );
3023          return $errors;
3024      }
3025  
3026      update_user_meta( $user_id, 'default_password_nag', true ); // Set up the password change nag.
3027  
3028      /**
3029       * Fires after a new user registration has been recorded.
3030       *
3031       * @since 4.4.0
3032       *
3033       * @param int $user_id ID of the newly registered user.
3034       */
3035      do_action( 'register_new_user', $user_id );
3036  
3037      return $user_id;
3038  }
3039  
3040  /**
3041   * Initiates email notifications related to the creation of new users.
3042   *
3043   * Notifications are sent both to the site admin and to the newly created user.
3044   *
3045   * @since 4.4.0
3046   * @since 4.6.0 Converted the `$notify` parameter to accept 'user' for sending
3047   *              notifications only to the user created.
3048   *
3049   * @param int    $user_id ID of the newly created user.
3050   * @param string $notify  Optional. Type of notification that should happen. Accepts 'admin'
3051   *                        or an empty string (admin only), 'user', or 'both' (admin and user).
3052   *                        Default 'both'.
3053   */
3054  function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {
3055      wp_new_user_notification( $user_id, null, $notify );
3056  }
3057  
3058  /**
3059   * Retrieve the current session token from the logged_in cookie.
3060   *
3061   * @since 4.0.0
3062   *
3063   * @return string Token.
3064   */
3065  function wp_get_session_token() {
3066      $cookie = wp_parse_auth_cookie( '', 'logged_in' );
3067      return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
3068  }
3069  
3070  /**
3071   * Retrieve a list of sessions for the current user.
3072   *
3073   * @since 4.0.0
3074   *
3075   * @return array Array of sessions.
3076   */
3077  function wp_get_all_sessions() {
3078      $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3079      return $manager->get_all();
3080  }
3081  
3082  /**
3083   * Remove the current session token from the database.
3084   *
3085   * @since 4.0.0
3086   */
3087  function wp_destroy_current_session() {
3088      $token = wp_get_session_token();
3089      if ( $token ) {
3090          $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3091          $manager->destroy( $token );
3092      }
3093  }
3094  
3095  /**
3096   * Remove all but the current session token for the current user for the database.
3097   *
3098   * @since 4.0.0
3099   */
3100  function wp_destroy_other_sessions() {
3101      $token = wp_get_session_token();
3102      if ( $token ) {
3103          $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3104          $manager->destroy_others( $token );
3105      }
3106  }
3107  
3108  /**
3109   * Remove all session tokens for the current user from the database.
3110   *
3111   * @since 4.0.0
3112   */
3113  function wp_destroy_all_sessions() {
3114      $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
3115      $manager->destroy_all();
3116  }
3117  
3118  /**
3119   * Get the user IDs of all users with no role on this site.
3120   *
3121   * @since 4.4.0
3122   * @since 4.9.0 The `$site_id` parameter was added to support multisite.
3123   *
3124   * @param int|null $site_id Optional. The site ID to get users with no role for. Defaults to the current site.
3125   * @return string[] Array of user IDs as strings.
3126   */
3127  function wp_get_users_with_no_role( $site_id = null ) {
3128      global $wpdb;
3129  
3130      if ( ! $site_id ) {
3131          $site_id = get_current_blog_id();
3132      }
3133  
3134      $prefix = $wpdb->get_blog_prefix( $site_id );
3135  
3136      if ( is_multisite() && get_current_blog_id() != $site_id ) {
3137          switch_to_blog( $site_id );
3138          $role_names = wp_roles()->get_names();
3139          restore_current_blog();
3140      } else {
3141          $role_names = wp_roles()->get_names();
3142      }
3143  
3144      $regex = implode( '|', array_keys( $role_names ) );
3145      $regex = preg_replace( '/[^a-zA-Z_\|-]/', '', $regex );
3146      $users = $wpdb->get_col(
3147          $wpdb->prepare(
3148              "
3149          SELECT user_id
3150          FROM $wpdb->usermeta
3151          WHERE meta_key = '{$prefix}capabilities'
3152          AND meta_value NOT REGEXP %s
3153      ",
3154              $regex
3155          )
3156      );
3157  
3158      return $users;
3159  }
3160  
3161  /**
3162   * Retrieves the current user object.
3163   *
3164   * Will set the current user, if the current user is not set. The current user
3165   * will be set to the logged-in person. If no user is logged-in, then it will
3166   * set the current user to 0, which is invalid and won't have any permissions.
3167   *
3168   * This function is used by the pluggable functions wp_get_current_user() and
3169   * get_currentuserinfo(), the latter of which is deprecated but used for backward
3170   * compatibility.
3171   *
3172   * @since 4.5.0
3173   * @access private
3174   *
3175   * @see wp_get_current_user()
3176   * @global WP_User $current_user Checks if the current user is set.
3177   *
3178   * @return WP_User Current WP_User instance.
3179   */
3180  function _wp_get_current_user() {
3181      global $current_user;
3182  
3183      if ( ! empty( $current_user ) ) {
3184          if ( $current_user instanceof WP_User ) {
3185              return $current_user;
3186          }
3187  
3188          // Upgrade stdClass to WP_User.
3189          if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
3190              $cur_id       = $current_user->ID;
3191              $current_user = null;
3192              wp_set_current_user( $cur_id );
3193              return $current_user;
3194          }
3195  
3196          // $current_user has a junk value. Force to WP_User with ID 0.
3197          $current_user = null;
3198          wp_set_current_user( 0 );
3199          return $current_user;
3200      }
3201  
3202      if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
3203          wp_set_current_user( 0 );
3204          return $current_user;
3205      }
3206  
3207      /**
3208       * Filters the current user.
3209       *
3210       * The default filters use this to determine the current user from the
3211       * request's cookies, if available.
3212       *
3213       * Returning a value of false will effectively short-circuit setting
3214       * the current user.
3215       *
3216       * @since 3.9.0
3217       *
3218       * @param int|false $user_id User ID if one has been determined, false otherwise.
3219       */
3220      $user_id = apply_filters( 'determine_current_user', false );
3221      if ( ! $user_id ) {
3222          wp_set_current_user( 0 );
3223          return $current_user;
3224      }
3225  
3226      wp_set_current_user( $user_id );
3227  
3228      return $current_user;
3229  }
3230  
3231  /**
3232   * Send a confirmation request email when a change of user email address is attempted.
3233   *
3234   * @since 3.0.0
3235   * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
3236   *
3237   * @global WP_Error $errors WP_Error object.
3238   */
3239  function send_confirmation_on_profile_email() {
3240      global $errors;
3241  
3242      $current_user = wp_get_current_user();
3243      if ( ! is_object( $errors ) ) {
3244          $errors = new WP_Error();
3245      }
3246  
3247      if ( $current_user->ID != $_POST['user_id'] ) {
3248          return false;
3249      }
3250  
3251      if ( $current_user->user_email != $_POST['email'] ) {
3252          if ( ! is_email( $_POST['email'] ) ) {
3253              $errors->add(
3254                  'user_email',
3255                  __( '<strong>Error</strong>: The email address isn&#8217;t correct.' ),
3256                  array(
3257                      'form-field' => 'email',
3258                  )
3259              );
3260  
3261              return;
3262          }
3263  
3264          if ( email_exists( $_POST['email'] ) ) {
3265              $errors->add(
3266                  'user_email',
3267                  __( '<strong>Error</strong>: The email address is already used.' ),
3268                  array(
3269                      'form-field' => 'email',
3270                  )
3271              );
3272              delete_user_meta( $current_user->ID, '_new_email' );
3273  
3274              return;
3275          }
3276  
3277          $hash           = md5( $_POST['email'] . time() . wp_rand() );
3278          $new_user_email = array(
3279              'hash'     => $hash,
3280              'newemail' => $_POST['email'],
3281          );
3282          update_user_meta( $current_user->ID, '_new_email', $new_user_email );
3283  
3284          $sitename = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
3285  
3286          /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */
3287          $email_text = __(
3288              'Howdy ###USERNAME###,
3289  
3290  You recently requested to have the email address on your account changed.
3291  
3292  If this is correct, please click on the following link to change it:
3293  ###ADMIN_URL###
3294  
3295  You can safely ignore and delete this email if you do not want to
3296  take this action.
3297  
3298  This email has been sent to ###EMAIL###
3299  
3300  Regards,
3301  All at ###SITENAME###
3302  ###SITEURL###'
3303          );
3304  
3305          /**
3306           * Filters the text of the email sent when a change of user email address is attempted.
3307           *
3308           * The following strings have a special meaning and will get replaced dynamically:
3309           * - ###USERNAME###  The current user's username.
3310           * - ###ADMIN_URL### The link to click on to confirm the email change.
3311           * - ###EMAIL###     The new email.
3312           * - ###SITENAME###  The name of the site.
3313           * - ###SITEURL###   The URL to the site.
3314           *
3315           * @since MU (3.0.0)
3316           * @since 4.9.0 This filter is no longer Multisite specific.
3317           *
3318           * @param string $email_text     Text in the email.
3319           * @param array  $new_user_email {
3320           *     Data relating to the new user email address.
3321           *
3322           *     @type string $hash     The secure hash used in the confirmation link URL.
3323           *     @type string $newemail The proposed new email address.
3324           * }
3325           */
3326          $content = apply_filters( 'new_user_email_content', $email_text, $new_user_email );
3327  
3328          $content = str_replace( '###USERNAME###', $current_user->user_login, $content );
3329          $content = str_replace( '###ADMIN_URL###', esc_url( admin_url( 'profile.php?newuseremail=' . $hash ) ), $content );
3330          $content = str_replace( '###EMAIL###', $_POST['email'], $content );
3331          $content = str_replace( '###SITENAME###', $sitename, $content );
3332          $content = str_replace( '###SITEURL###', home_url(), $content );
3333  
3334          /* translators: New email address notification email subject. %s: Site title. */
3335          wp_mail( $_POST['email'], sprintf( __( '[%s] Email Change Request' ), $sitename ), $content );
3336  
3337          $_POST['email'] = $current_user->user_email;
3338      }
3339  }
3340  
3341  /**
3342   * Adds an admin notice alerting the user to check for confirmation request email
3343   * after email address change.
3344   *
3345   * @since 3.0.0
3346   * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
3347   *
3348   * @global string $pagenow
3349   */
3350  function new_user_email_admin_notice() {
3351      global $pagenow;
3352  
3353      if ( 'profile.php' === $pagenow && isset( $_GET['updated'] ) ) {
3354          $email = get_user_meta( get_current_user_id(), '_new_email', true );
3355          if ( $email ) {
3356              /* translators: %s: New email address. */
3357              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>';
3358          }
3359      }
3360  }
3361  
3362  /**
3363   * Get all personal data request types.
3364   *
3365   * @since 4.9.6
3366   * @access private
3367   *
3368   * @return array List of core privacy action types.
3369   */
3370  function _wp_privacy_action_request_types() {
3371      return array(
3372          'export_personal_data',
3373          'remove_personal_data',
3374      );
3375  }
3376  
3377  /**
3378   * Registers the personal data exporter for users.
3379   *
3380   * @since 4.9.6
3381   *
3382   * @param array $exporters  An array of personal data exporters.
3383   * @return array An array of personal data exporters.
3384   */
3385  function wp_register_user_personal_data_exporter( $exporters ) {
3386      $exporters['wordpress-user'] = array(
3387          'exporter_friendly_name' => __( 'WordPress User' ),
3388          'callback'               => 'wp_user_personal_data_exporter',
3389      );
3390  
3391      return $exporters;
3392  }
3393  
3394  /**
3395   * Finds and exports personal data associated with an email address from the user and user_meta table.
3396   *
3397   * @since 4.9.6
3398   * @since 5.4.0 Added 'Community Events Location' group to the export data.
3399   * @since 5.4.0 Added 'Session Tokens' group to the export data.
3400   *
3401   * @param string $email_address  The user's email address.
3402   * @return array An array of personal data.
3403   */
3404  function wp_user_personal_data_exporter( $email_address ) {
3405      $email_address = trim( $email_address );
3406  
3407      $data_to_export = array();
3408  
3409      $user = get_user_by( 'email', $email_address );
3410  
3411      if ( ! $user ) {
3412          return array(
3413              'data' => array(),
3414              'done' => true,
3415          );
3416      }
3417  
3418      $user_meta = get_user_meta( $user->ID );
3419  
3420      $user_props_to_export = array(
3421          'ID'              => __( 'User ID' ),
3422          'user_login'      => __( 'User Login Name' ),
3423          'user_nicename'   => __( 'User Nice Name' ),
3424          'user_email'      => __( 'User Email' ),
3425          'user_url'        => __( 'User URL' ),
3426          'user_registered' => __( 'User Registration Date' ),
3427          'display_name'    => __( 'User Display Name' ),
3428          'nickname'        => __( 'User Nickname' ),
3429          'first_name'      => __( 'User First Name' ),
3430          'last_name'       => __( 'User Last Name' ),
3431          'description'     => __( 'User Description' ),
3432      );
3433  
3434      $user_data_to_export = array();
3435  
3436      foreach ( $user_props_to_export as $key => $name ) {
3437          $value = '';
3438  
3439          switch ( $key ) {
3440              case 'ID':
3441              case 'user_login':
3442              case 'user_nicename':
3443              case 'user_email':
3444              case 'user_url':
3445              case 'user_registered':
3446              case 'display_name':
3447                  $value = $user->data->$key;
3448                  break;
3449              case 'nickname':
3450              case 'first_name':
3451              case 'last_name':
3452              case 'description':
3453                  $value = $user_meta[ $key ][0];
3454                  break;
3455          }
3456  
3457          if ( ! empty( $value ) ) {
3458              $user_data_to_export[] = array(
3459                  'name'  => $name,
3460                  'value' => $value,
3461              );
3462          }
3463      }
3464  
3465      // Get the list of reserved names.
3466      $reserved_names = array_values( $user_props_to_export );
3467  
3468      /**
3469       * Filter to extend the user's profile data for the privacy exporter.
3470       *
3471       * @since 5.4.0
3472       *
3473       * @param array    $additional_user_profile_data {
3474       *     An array of name-value pairs of additional user data items. Default empty array.
3475       *
3476       *     @type string $name  The user-facing name of an item name-value pair,e.g. 'IP Address'.
3477       *     @type string $value The user-facing value of an item data pair, e.g. '50.60.70.0'.
3478       * }
3479       * @param WP_User  $user           The user whose data is being exported.
3480       * @param string[] $reserved_names An array of reserved names. Any item in `$additional_user_data`
3481       *                                 that uses one of these for its `name` will not be included in the export.
3482       */
3483      $_extra_data = apply_filters( 'wp_privacy_additional_user_profile_data', array(), $user, $reserved_names );
3484  
3485      if ( is_array( $_extra_data ) && ! empty( $_extra_data ) ) {
3486          // Remove items that use reserved names.
3487          $extra_data = array_filter(
3488              $_extra_data,
3489              static function( $item ) use ( $reserved_names ) {
3490                  return ! in_array( $item['name'], $reserved_names, true );
3491              }
3492          );
3493  
3494          if ( count( $extra_data ) !== count( $_extra_data ) ) {
3495              _doing_it_wrong(
3496                  __FUNCTION__,
3497                  sprintf(
3498                      /* translators: %s: wp_privacy_additional_user_profile_data */
3499                      __( 'Filter %s returned items with reserved names.' ),
3500                      '<code>wp_privacy_additional_user_profile_data</code>'
3501                  ),
3502                  '5.4.0'
3503              );
3504          }
3505  
3506          if ( ! empty( $extra_data ) ) {
3507              $user_data_to_export = array_merge( $user_data_to_export, $extra_data );
3508          }
3509      }
3510  
3511      $data_to_export[] = array(
3512          'group_id'          => 'user',
3513          'group_label'       => __( 'User' ),
3514          'group_description' => __( 'User&#8217;s profile data.' ),
3515          'item_id'           => "user-{$user->ID}",
3516          'data'              => $user_data_to_export,
3517      );
3518  
3519      if ( isset( $user_meta['community-events-location'] ) ) {
3520          $location = maybe_unserialize( $user_meta['community-events-location'][0] );
3521  
3522          $location_props_to_export = array(
3523              'description' => __( 'City' ),
3524              'country'     => __( 'Country' ),
3525              'latitude'    => __( 'Latitude' ),
3526              'longitude'   => __( 'Longitude' ),
3527              'ip'          => __( 'IP' ),
3528          );
3529  
3530          $location_data_to_export = array();
3531  
3532          foreach ( $location_props_to_export as $key => $name ) {
3533              if ( ! empty( $location[ $key ] ) ) {
3534                  $location_data_to_export[] = array(
3535                      'name'  => $name,
3536                      'value' => $location[ $key ],
3537                  );
3538              }
3539          }
3540  
3541          $data_to_export[] = array(
3542              'group_id'          => 'community-events-location',
3543              'group_label'       => __( 'Community Events Location' ),
3544              'group_description' => __( 'User&#8217;s location data used for the Community Events in the WordPress Events and News dashboard widget.' ),
3545              'item_id'           => "community-events-location-{$user->ID}",
3546              'data'              => $location_data_to_export,
3547          );
3548      }
3549  
3550      if ( isset( $user_meta['session_tokens'] ) ) {
3551          $session_tokens = maybe_unserialize( $user_meta['session_tokens'][0] );
3552  
3553          $session_tokens_props_to_export = array(
3554              'expiration' => __( 'Expiration' ),
3555              'ip'         => __( 'IP' ),
3556              'ua'         => __( 'User Agent' ),
3557              'login'      => __( 'Last Login' ),
3558          );
3559  
3560          foreach ( $session_tokens as $token_key => $session_token ) {
3561              $session_tokens_data_to_export = array();
3562  
3563              foreach ( $session_tokens_props_to_export as $key => $name ) {
3564                  if ( ! empty( $session_token[ $key ] ) ) {
3565                      $value = $session_token[ $key ];
3566                      if ( in_array( $key, array( 'expiration', 'login' ), true ) ) {
3567                          $value = date_i18n( 'F d, Y H:i A', $value );
3568                      }
3569                      $session_tokens_data_to_export[] = array(
3570                          'name'  => $name,
3571                          'value' => $value,
3572                      );
3573                  }
3574              }
3575  
3576              $data_to_export[] = array(
3577                  'group_id'          => 'session-tokens',
3578                  'group_label'       => __( 'Session Tokens' ),
3579                  'group_description' => __( 'User&#8217;s Session Tokens data.' ),
3580                  'item_id'           => "session-tokens-{$user->ID}-{$token_key}",
3581                  'data'              => $session_tokens_data_to_export,
3582              );
3583          }
3584      }
3585  
3586      return array(
3587          'data' => $data_to_export,
3588          'done' => true,
3589      );
3590  }
3591  
3592  /**
3593   * Update log when privacy request is confirmed.
3594   *
3595   * @since 4.9.6
3596   * @access private
3597   *
3598   * @param int $request_id ID of the request.
3599   */
3600  function _wp_privacy_account_request_confirmed( $request_id ) {
3601      $request = wp_get_user_request( $request_id );
3602  
3603      if ( ! $request ) {
3604          return;
3605      }
3606  
3607      if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
3608          return;
3609      }
3610  
3611      update_post_meta( $request_id, '_wp_user_request_confirmed_timestamp', time() );
3612      wp_update_post(
3613          array(
3614              'ID'          => $request_id,
3615              'post_status' => 'request-confirmed',
3616          )
3617      );
3618  }
3619  
3620  /**
3621   * Notify the site administrator via email when a request is confirmed.
3622   *
3623   * Without this, the admin would have to manually check the site to see if any
3624   * action was needed on their part yet.
3625   *
3626   * @since 4.9.6
3627   *
3628   * @param int $request_id The ID of the request.
3629   */
3630  function _wp_privacy_send_request_confirmation_notification( $request_id ) {
3631      $request = wp_get_user_request( $request_id );
3632  
3633      if ( ! is_a( $request, 'WP_User_Request' ) || 'request-confirmed' !== $request->status ) {
3634          return;
3635      }
3636  
3637      $already_notified = (bool) get_post_meta( $request_id, '_wp_admin_notified', true );
3638  
3639      if ( $already_notified ) {
3640          return;
3641      }
3642  
3643      if ( 'export_personal_data' === $request->action_name ) {
3644          $manage_url = admin_url( 'export-personal-data.php' );
3645      } elseif ( 'remove_personal_data' === $request->action_name ) {
3646          $manage_url = admin_url( 'erase-personal-data.php' );
3647      }
3648      $action_description = wp_user_request_action_description( $request->action_name );
3649  
3650      /**
3651       * Filters the recipient of the data request confirmation notification.
3652       *
3653       * In a Multisite environment, this will default to the email address of the
3654       * network admin because, by default, single site admins do not have the
3655       * capabilities required to process requests. Some networks may wish to
3656       * delegate those capabilities to a single-site admin, or a dedicated person
3657       * responsible for managing privacy requests.
3658       *
3659       * @since 4.9.6
3660       *
3661       * @param string          $admin_email The email address of the notification recipient.
3662       * @param WP_User_Request $request     The request that is initiating the notification.
3663       */
3664      $admin_email = apply_filters( 'user_request_confirmed_email_to', get_site_option( 'admin_email' ), $request );
3665  
3666      $email_data = array(
3667          'request'     => $request,
3668          'user_email'  => $request->email,
3669          'description' => $action_description,
3670          'manage_url'  => $manage_url,
3671          'sitename'    => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
3672          'siteurl'     => home_url(),
3673          'admin_email' => $admin_email,
3674      );
3675  
3676      $subject = sprintf(
3677          /* translators: Privacy data request confirmed notification email subject. 1: Site title, 2: Name of the confirmed action. */
3678          __( '[%1$s] Action Confirmed: %2$s' ),
3679          $email_data['sitename'],
3680          $action_description
3681      );
3682  
3683      /**
3684       * Filters the subject of the user request confirmation email.
3685       *
3686       * @since 4.9.8
3687       *
3688       * @param string $subject    The email subject.
3689       * @param string $sitename   The name of the site.
3690       * @param array  $email_data {
3691       *     Data relating to the account action email.
3692       *
3693       *     @type WP_User_Request $request     User request object.
3694       *     @type string          $user_email  The email address confirming a request
3695       *     @type string          $description Description of the action being performed so the user knows what the email is for.
3696       *     @type string          $manage_url  The link to click manage privacy requests of this type.
3697       *     @type string          $sitename    The site name sending the mail.
3698       *     @type string          $siteurl     The site URL sending the mail.
3699       *     @type string          $admin_email The administrator email receiving the mail.
3700       * }
3701       */
3702      $subject = apply_filters( 'user_request_confirmed_email_subject', $subject, $email_data['sitename'], $email_data );
3703  
3704      /* translators: Do not translate SITENAME, USER_EMAIL, DESCRIPTION, MANAGE_URL, SITEURL; those are placeholders. */
3705      $content = __(
3706          'Howdy,
3707  
3708  A user data privacy request has been confirmed on ###SITENAME###:
3709  
3710  User: ###USER_EMAIL###
3711  Request: ###DESCRIPTION###
3712  
3713  You can view and manage these data privacy requests here:
3714  
3715  ###MANAGE_URL###
3716  
3717  Regards,
3718  All at ###SITENAME###
3719  ###SITEURL###'
3720      );
3721  
3722      /**
3723       * Filters the body of the user request confirmation email.
3724       *
3725       * The email is sent to an administrator when a user request is confirmed.
3726       *
3727       * The following strings have a special meaning and will get replaced dynamically:
3728       *
3729       * ###SITENAME###    The name of the site.
3730       * ###USER_EMAIL###  The user email for the request.
3731       * ###DESCRIPTION### Description of the action being performed so the user knows what the email is for.
3732       * ###MANAGE_URL###  The URL to manage requests.
3733       * ###SITEURL###     The URL to the site.
3734       *
3735       * @since 4.9.6
3736       * @deprecated 5.8.0 Use {@see 'user_request_confirmed_email_content'} instead.
3737       *                   For user erasure fulfillment email content
3738       *                   use {@see 'user_erasure_fulfillment_email_content'} instead.
3739       *
3740       * @param string $content    The email content.
3741       * @param array  $email_data {
3742       *     Data relating to the account action email.
3743       *
3744       *     @type WP_User_Request $request     User request object.
3745       *     @type string          $user_email  The email address confirming a request
3746       *     @type string          $description Description of the action being performed
3747       *                                        so the user knows what the email is for.
3748       *     @type string          $manage_url  The link to click manage privacy requests of this type.
3749       *     @type string          $sitename    The site name sending the mail.
3750       *     @type string          $siteurl     The site URL sending the mail.
3751       *     @type string          $admin_email The administrator email receiving the mail.
3752       * }
3753       */
3754      $content = apply_filters_deprecated(
3755          'user_confirmed_action_email_content',
3756          array( $content, $email_data ),
3757          '5.8.0',
3758          sprintf(
3759              /* translators: 1 & 2: Deprecation replacement options. */
3760              __( '%1$s or %2$s' ),
3761              'user_request_confirmed_email_content',
3762              'user_erasure_fulfillment_email_content'
3763          )
3764      );
3765  
3766      /**
3767       * Filters the body of the user request confirmation email.
3768       *
3769       * The email is sent to an administrator when a user request is confirmed.
3770       * The following strings have a special meaning and will get replaced dynamically:
3771       *
3772       * ###SITENAME###    The name of the site.
3773       * ###USER_EMAIL###  The user email for the request.
3774       * ###DESCRIPTION### Description of the action being performed so the user knows what the email is for.
3775       * ###MANAGE_URL###  The URL to manage requests.
3776       * ###SITEURL###     The URL to the site.
3777       *
3778       * @since 5.8.0
3779       *
3780       * @param string $content    The email content.
3781       * @param array  $email_data {
3782       *     Data relating to the account action email.
3783       *
3784       *     @type WP_User_Request $request     User request object.
3785       *     @type string          $user_email  The email address confirming a request
3786       *     @type string          $description Description of the action being performed so the user knows what the email is for.
3787       *     @type string          $manage_url  The link to click manage privacy requests of this type.
3788       *     @type string          $sitename    The site name sending the mail.
3789       *     @type string          $siteurl     The site URL sending the mail.
3790       *     @type string          $admin_email The administrator email receiving the mail.
3791       * }
3792       */
3793      $content = apply_filters( 'user_request_confirmed_email_content', $content, $email_data );
3794  
3795      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
3796      $content = str_replace( '###USER_EMAIL###', $email_data['user_email'], $content );
3797      $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
3798      $content = str_replace( '###MANAGE_URL###', esc_url_raw( $email_data['manage_url'] ), $content );
3799      $content = str_replace( '###SITEURL###', esc_url_raw( $email_data['siteurl'] ), $content );
3800  
3801      $headers = '';
3802  
3803      /**
3804       * Filters the headers of the user request confirmation email.
3805       *
3806       * @since 5.4.0
3807       *
3808       * @param string|array $headers    The email headers.
3809       * @param string       $subject    The email subject.
3810       * @param string       $content    The email content.
3811       * @param int          $request_id The request ID.
3812       * @param array        $email_data {
3813       *     Data relating to the account action email.
3814       *
3815       *     @type WP_User_Request $request     User request object.
3816       *     @type string          $user_email  The email address confirming a request
3817       *     @type string          $description Description of the action being performed so the user knows what the email is for.
3818       *     @type string          $manage_url  The link to click manage privacy requests of this type.
3819       *     @type string          $sitename    The site name sending the mail.
3820       *     @type string          $siteurl     The site URL sending the mail.
3821       *     @type string          $admin_email The administrator email receiving the mail.
3822       * }
3823       */
3824      $headers = apply_filters( 'user_request_confirmed_email_headers', $headers, $subject, $content, $request_id, $email_data );
3825  
3826      $email_sent = wp_mail( $email_data['admin_email'], $subject, $content, $headers );
3827  
3828      if ( $email_sent ) {
3829          update_post_meta( $request_id, '_wp_admin_notified', true );
3830      }
3831  }
3832  
3833  /**
3834   * Notify the user when their erasure request is fulfilled.
3835   *
3836   * Without this, the user would never know if their data was actually erased.
3837   *
3838   * @since 4.9.6
3839   *
3840   * @param int $request_id The privacy request post ID associated with this request.
3841   */
3842  function _wp_privacy_send_erasure_fulfillment_notification( $request_id ) {
3843      $request = wp_get_user_request( $request_id );
3844  
3845      if ( ! is_a( $request, 'WP_User_Request' ) || 'request-completed' !== $request->status ) {
3846          return;
3847      }
3848  
3849      $already_notified = (bool) get_post_meta( $request_id, '_wp_user_notified', true );
3850  
3851      if ( $already_notified ) {
3852          return;
3853      }
3854  
3855      // Localize message content for user; fallback to site default for visitors.
3856      if ( ! empty( $request->user_id ) ) {
3857          $locale = get_user_locale( $request->user_id );
3858      } else {
3859          $locale = get_locale();
3860      }
3861  
3862      $switched_locale = switch_to_locale( $locale );
3863  
3864      /**
3865       * Filters the recipient of the data erasure fulfillment notification.
3866       *
3867       * @since 4.9.6
3868       *
3869       * @param string          $user_email The email address of the notification recipient.
3870       * @param WP_User_Request $request    The request that is initiating the notification.
3871       */
3872      $user_email = apply_filters( 'user_erasure_fulfillment_email_to', $request->email, $request );
3873  
3874      $email_data = array(
3875          'request'            => $request,
3876          'message_recipient'  => $user_email,
3877          'privacy_policy_url' => get_privacy_policy_url(),
3878          'sitename'           => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
3879          'siteurl'            => home_url(),
3880      );
3881  
3882      $subject = sprintf(
3883          /* translators: Erasure request fulfilled notification email subject. %s: Site title. */
3884          __( '[%s] Erasure Request Fulfilled' ),
3885          $email_data['sitename']
3886      );
3887  
3888      /**
3889       * Filters the subject of the email sent when an erasure request is completed.
3890       *
3891       * @since 4.9.8
3892       * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_subject'} instead.
3893       *
3894       * @param string $subject    The email subject.
3895       * @param string $sitename   The name of the site.
3896       * @param array  $email_data {
3897       *     Data relating to the account action email.
3898       *
3899       *     @type WP_User_Request $request            User request object.
3900       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
3901       *                                               to the value of `$request->email`, but can be changed
3902       *                                               by the `user_erasure_fulfillment_email_to` filter.
3903       *     @type string          $privacy_policy_url Privacy policy URL.
3904       *     @type string          $sitename           The site name sending the mail.
3905       *     @type string          $siteurl            The site URL sending the mail.
3906       * }
3907       */
3908      $subject = apply_filters_deprecated(
3909          'user_erasure_complete_email_subject',
3910          array( $subject, $email_data['sitename'], $email_data ),
3911          '5.8.0',
3912          'user_erasure_fulfillment_email_subject'
3913      );
3914  
3915      /**
3916       * Filters the subject of the email sent when an erasure request is completed.
3917       *
3918       * @since 5.8.0
3919       *
3920       * @param string $subject    The email subject.
3921       * @param string $sitename   The name of the site.
3922       * @param array  $email_data {
3923       *     Data relating to the account action email.
3924       *
3925       *     @type WP_User_Request $request            User request object.
3926       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
3927       *                                               to the value of `$request->email`, but can be changed
3928       *                                               by the `user_erasure_fulfillment_email_to` filter.
3929       *     @type string          $privacy_policy_url Privacy policy URL.
3930       *     @type string          $sitename           The site name sending the mail.
3931       *     @type string          $siteurl            The site URL sending the mail.
3932       * }
3933       */
3934      $subject = apply_filters( 'user_erasure_fulfillment_email_subject', $subject, $email_data['sitename'], $email_data );
3935  
3936      /* translators: Do not translate SITENAME, SITEURL; those are placeholders. */
3937      $content = __(
3938          'Howdy,
3939  
3940  Your request to erase your personal data on ###SITENAME### has been completed.
3941  
3942  If you have any follow-up questions or concerns, please contact the site administrator.
3943  
3944  Regards,
3945  All at ###SITENAME###
3946  ###SITEURL###'
3947      );
3948  
3949      if ( ! empty( $email_data['privacy_policy_url'] ) ) {
3950          /* translators: Do not translate SITENAME, SITEURL, PRIVACY_POLICY_URL; those are placeholders. */
3951          $content = __(
3952              'Howdy,
3953  
3954  Your request to erase your personal data on ###SITENAME### has been completed.
3955  
3956  If you have any follow-up questions or concerns, please contact the site administrator.
3957  
3958  For more information, you can also read our privacy policy: ###PRIVACY_POLICY_URL###
3959  
3960  Regards,
3961  All at ###SITENAME###
3962  ###SITEURL###'
3963          );
3964      }
3965  
3966      /**
3967       * Filters the body of the data erasure fulfillment notification.
3968       *
3969       * The email is sent to a user when their data erasure request is fulfilled
3970       * by an administrator.
3971       *
3972       * The following strings have a special meaning and will get replaced dynamically:
3973       *
3974       * ###SITENAME###           The name of the site.
3975       * ###PRIVACY_POLICY_URL### Privacy policy page URL.
3976       * ###SITEURL###            The URL to the site.
3977       *
3978       * @since 4.9.6
3979       * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_content'} instead.
3980       *                   For user request confirmation email content
3981       *                   use {@see 'user_request_confirmed_email_content'} instead.
3982       *
3983       * @param string $content The email content.
3984       * @param array  $email_data {
3985       *     Data relating to the account action email.
3986       *
3987       *     @type WP_User_Request $request            User request object.
3988       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
3989       *                                               to the value of `$request->email`, but can be changed
3990       *                                               by the `user_erasure_fulfillment_email_to` filter.
3991       *     @type string          $privacy_policy_url Privacy policy URL.
3992       *     @type string          $sitename           The site name sending the mail.
3993       *     @type string          $siteurl            The site URL sending the mail.
3994       * }
3995       */
3996      $content = apply_filters_deprecated(
3997          'user_confirmed_action_email_content',
3998          array( $content, $email_data ),
3999          '5.8.0',
4000          sprintf(
4001              /* translators: 1 & 2: Deprecation replacement options. */
4002              __( '%1$s or %2$s' ),
4003              'user_erasure_fulfillment_email_content',
4004              'user_request_confirmed_email_content'
4005          )
4006      );
4007  
4008      /**
4009       * Filters the body of the data erasure fulfillment notification.
4010       *
4011       * The email is sent to a user when their data erasure request is fulfilled
4012       * by an administrator.
4013       *
4014       * The following strings have a special meaning and will get replaced dynamically:
4015       *
4016       * ###SITENAME###           The name of the site.
4017       * ###PRIVACY_POLICY_URL### Privacy policy page URL.
4018       * ###SITEURL###            The URL to the site.
4019       *
4020       * @since 5.8.0
4021       *
4022       * @param string $content The email content.
4023       * @param array  $email_data {
4024       *     Data relating to the account action email.
4025       *
4026       *     @type WP_User_Request $request            User request object.
4027       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4028       *                                               to the value of `$request->email`, but can be changed
4029       *                                               by the `user_erasure_fulfillment_email_to` filter.
4030       *     @type string          $privacy_policy_url Privacy policy URL.
4031       *     @type string          $sitename           The site name sending the mail.
4032       *     @type string          $siteurl            The site URL sending the mail.
4033       * }
4034       */
4035      $content = apply_filters( 'user_erasure_fulfillment_email_content', $content, $email_data );
4036  
4037      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
4038      $content = str_replace( '###PRIVACY_POLICY_URL###', $email_data['privacy_policy_url'], $content );
4039      $content = str_replace( '###SITEURL###', esc_url_raw( $email_data['siteurl'] ), $content );
4040  
4041      $headers = '';
4042  
4043      /**
4044       * Filters the headers of the data erasure fulfillment notification.
4045       *
4046       * @since 5.4.0
4047       * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_headers'} instead.
4048       *
4049       * @param string|array $headers    The email headers.
4050       * @param string       $subject    The email subject.
4051       * @param string       $content    The email content.
4052       * @param int          $request_id The request ID.
4053       * @param array        $email_data {
4054       *     Data relating to the account action email.
4055       *
4056       *     @type WP_User_Request $request            User request object.
4057       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4058       *                                               to the value of `$request->email`, but can be changed
4059       *                                               by the `user_erasure_fulfillment_email_to` filter.
4060       *     @type string          $privacy_policy_url Privacy policy URL.
4061       *     @type string          $sitename           The site name sending the mail.
4062       *     @type string          $siteurl            The site URL sending the mail.
4063       * }
4064       */
4065      $headers = apply_filters_deprecated(
4066          'user_erasure_complete_email_headers',
4067          array( $headers, $subject, $content, $request_id, $email_data ),
4068          '5.8.0',
4069          'user_erasure_fulfillment_email_headers'
4070      );
4071  
4072      /**
4073       * Filters the headers of the data erasure fulfillment notification.
4074       *
4075       * @since 5.8.0
4076       *
4077       * @param string|array $headers    The email headers.
4078       * @param string       $subject    The email subject.
4079       * @param string       $content    The email content.
4080       * @param int          $request_id The request ID.
4081       * @param array        $email_data {
4082       *     Data relating to the account action email.
4083       *
4084       *     @type WP_User_Request $request            User request object.
4085       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
4086       *                                               to the value of `$request->email`, but can be changed
4087       *                                               by the `user_erasure_fulfillment_email_to` filter.
4088       *     @type string          $privacy_policy_url Privacy policy URL.
4089       *     @type string          $sitename           The site name sending the mail.
4090       *     @type string          $siteurl            The site URL sending the mail.
4091       * }
4092       */
4093      $headers = apply_filters( 'user_erasure_fulfillment_email_headers', $headers, $subject, $content, $request_id, $email_data );
4094  
4095      $email_sent = wp_mail( $user_email, $subject, $content, $headers );
4096  
4097      if ( $switched_locale ) {
4098          restore_previous_locale();
4099      }
4100  
4101      if ( $email_sent ) {
4102          update_post_meta( $request_id, '_wp_user_notified', true );
4103      }
4104  }
4105  
4106  /**
4107   * Return request confirmation message HTML.
4108   *
4109   * @since 4.9.6
4110   * @access private
4111   *
4112   * @param int $request_id The request ID being confirmed.
4113   * @return string The confirmation message.
4114   */
4115  function _wp_privacy_account_request_confirmed_message( $request_id ) {
4116      $request = wp_get_user_request( $request_id );
4117  
4118      $message  = '<p class="success">' . __( 'Action has been confirmed.' ) . '</p>';
4119      $message .= '<p>' . __( 'The site administrator has been notified and will fulfill your request as soon as possible.' ) . '</p>';
4120  
4121      if ( $request && in_array( $request->action_name, _wp_privacy_action_request_types(), true ) ) {
4122          if ( 'export_personal_data' === $request->action_name ) {
4123              $message  = '<p class="success">' . __( 'Thanks for confirming your export request.' ) . '</p>';
4124              $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>';
4125          } elseif ( 'remove_personal_data' === $request->action_name ) {
4126              $message  = '<p class="success">' . __( 'Thanks for confirming your erasure request.' ) . '</p>';
4127              $message .= '<p>' . __( 'The site administrator has been notified. You will receive an email confirmation when they erase your data.' ) . '</p>';
4128          }
4129      }
4130  
4131      /**
4132       * Filters the message displayed to a user when they confirm a data request.
4133       *
4134       * @since 4.9.6
4135       *
4136       * @param string $message    The message to the user.
4137       * @param int    $request_id The ID of the request being confirmed.
4138       */
4139      $message = apply_filters( 'user_request_action_confirmed_message', $message, $request_id );
4140  
4141      return $message;
4142  }
4143  
4144  /**
4145   * Create and log a user request to perform a specific action.
4146   *
4147   * Requests are stored inside a post type named `user_request` since they can apply to both
4148   * users on the site, or guests without a user account.
4149   *
4150   * @since 4.9.6
4151   * @since 5.7.0 Added the `$status` parameter.
4152   *
4153   * @param string $email_address           User email address. This can be the address of a registered
4154   *                                        or non-registered user.
4155   * @param string $action_name             Name of the action that is being confirmed. Required.
4156   * @param array  $request_data            Misc data you want to send with the verification request and pass
4157   *                                        to the actions once the request is confirmed.
4158   * @param string $status                  Optional request status (pending or confirmed). Default 'pending'.
4159   * @return int|WP_Error                   Returns the request ID if successful, or a WP_Error object on failure.
4160   */
4161  function wp_create_user_request( $email_address = '', $action_name = '', $request_data = array(), $status = 'pending' ) {
4162      $email_address = sanitize_email( $email_address );
4163      $action_name   = sanitize_key( $action_name );
4164  
4165      if ( ! is_email( $email_address ) ) {
4166          return new WP_Error( 'invalid_email', __( 'Invalid email address.' ) );
4167      }
4168  
4169      if ( ! in_array( $action_name, _wp_privacy_action_request_types(), true ) ) {
4170          return new WP_Error( 'invalid_action', __( 'Invalid action name.' ) );
4171      }
4172  
4173      if ( ! in_array( $status, array( 'pending', 'confirmed' ), true ) ) {
4174          return new WP_Error( 'invalid_status', __( 'Invalid request status.' ) );
4175      }
4176  
4177      $user    = get_user_by( 'email', $email_address );
4178      $user_id = $user && ! is_wp_error( $user ) ? $user->ID : 0;
4179  
4180      // Check for duplicates.
4181      $requests_query = new WP_Query(
4182          array(
4183              'post_type'     => 'user_request',
4184              'post_name__in' => array( $action_name ), // Action name stored in post_name column.
4185              'title'         => $email_address,        // Email address stored in post_title column.
4186              'post_status'   => array(
4187                  'request-pending',
4188                  'request-confirmed',
4189              ),
4190              'fields'        => 'ids',
4191          )
4192      );
4193  
4194      if ( $requests_query->found_posts ) {
4195          return new WP_Error( 'duplicate_request', __( 'An incomplete personal data request for this email address already exists.' ) );
4196      }
4197  
4198      $request_id = wp_insert_post(
4199          array(
4200              'post_author'   => $user_id,
4201              'post_name'     => $action_name,
4202              'post_title'    => $email_address,
4203              'post_content'  => wp_json_encode( $request_data ),
4204              'post_status'   => 'request-' . $status,
4205              'post_type'     => 'user_request',
4206              'post_date'     => current_time( 'mysql', false ),
4207              'post_date_gmt' => current_time( 'mysql', true ),
4208          ),
4209          true
4210      );
4211  
4212      return $request_id;
4213  }
4214  
4215  /**
4216   * Get action description from the name and return a string.
4217   *
4218   * @since 4.9.6
4219   *
4220   * @param string $action_name Action name of the request.
4221   * @return string Human readable action name.
4222   */
4223  function wp_user_request_action_description( $action_name ) {
4224      switch ( $action_name ) {
4225          case 'export_personal_data':
4226              $description = __( 'Export Personal Data' );
4227              break;
4228          case 'remove_personal_data':
4229              $description = __( 'Erase Personal Data' );
4230              break;
4231          default:
4232              /* translators: %s: Action name. */
4233              $description = sprintf( __( 'Confirm the "%s" action' ), $action_name );
4234              break;
4235      }
4236  
4237      /**
4238       * Filters the user action description.
4239       *
4240       * @since 4.9.6
4241       *
4242       * @param string $description The default description.
4243       * @param string $action_name The name of the request.
4244       */
4245      return apply_filters( 'user_request_action_description', $description, $action_name );
4246  }
4247  
4248  /**
4249   * Send a confirmation request email to confirm an action.
4250   *
4251   * If the request is not already pending, it will be updated.
4252   *
4253   * @since 4.9.6
4254   *
4255   * @param string $request_id ID of the request created via wp_create_user_request().
4256   * @return true|WP_Error True on success, `WP_Error` on failure.
4257   */
4258  function wp_send_user_request( $request_id ) {
4259      $request_id = absint( $request_id );
4260      $request    = wp_get_user_request( $request_id );
4261  
4262      if ( ! $request ) {
4263          return new WP_Error( 'invalid_request', __( 'Invalid personal data request.' ) );
4264      }
4265  
4266      // Localize message content for user; fallback to site default for visitors.
4267      if ( ! empty( $request->user_id ) ) {
4268          $locale = get_user_locale( $request->user_id );
4269      } else {
4270          $locale = get_locale();
4271      }
4272  
4273      $switched_locale = switch_to_locale( $locale );
4274  
4275      $email_data = array(
4276          'request'     => $request,
4277          'email'       => $request->email,
4278          'description' => wp_user_request_action_description( $request->action_name ),
4279          'confirm_url' => add_query_arg(
4280              array(
4281                  'action'      => 'confirmaction',
4282                  'request_id'  => $request_id,
4283                  'confirm_key' => wp_generate_user_request_key( $request_id ),
4284              ),
4285              wp_login_url()
4286          ),
4287          'sitename'    => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
4288          'siteurl'     => home_url(),
4289      );
4290  
4291      /* translators: Confirm privacy data request notification email subject. 1: Site title, 2: Name of the action. */
4292      $subject = sprintf( __( '[%1$s] Confirm Action: %2$s' ), $email_data['sitename'], $email_data['description'] );
4293  
4294      /**
4295       * Filters the subject of the email sent when an account action is attempted.
4296       *
4297       * @since 4.9.6
4298       *
4299       * @param string $subject    The email subject.
4300       * @param string $sitename   The name of the site.
4301       * @param array  $email_data {
4302       *     Data relating to the account action email.
4303       *
4304       *     @type WP_User_Request $request     User request object.
4305       *     @type string          $email       The email address this is being sent to.
4306       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4307       *     @type string          $confirm_url The link to click on to confirm the account action.
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_request_action_email_subject', $subject, $email_data['sitename'], $email_data );
4313  
4314      /* translators: Do not translate DESCRIPTION, CONFIRM_URL, SITENAME, SITEURL: those are placeholders. */
4315      $content = __(
4316          'Howdy,
4317  
4318  A request has been made to perform the following action on your account:
4319  
4320       ###DESCRIPTION###
4321  
4322  To confirm this, please click on the following link:
4323  ###CONFIRM_URL###
4324  
4325  You can safely ignore and delete this email if you do not want to
4326  take this action.
4327  
4328  Regards,
4329  All at ###SITENAME###
4330  ###SITEURL###'
4331      );
4332  
4333      /**
4334       * Filters the text of the email sent when an account action is attempted.
4335       *
4336       * The following strings have a special meaning and will get replaced dynamically:
4337       *
4338       * ###DESCRIPTION### Description of the action being performed so the user knows what the email is for.
4339       * ###CONFIRM_URL### The link to click on to confirm the account action.
4340       * ###SITENAME###    The name of the site.
4341       * ###SITEURL###     The URL to the site.
4342       *
4343       * @since 4.9.6
4344       *
4345       * @param string $content Text in the email.
4346       * @param array  $email_data {
4347       *     Data relating to the account action email.
4348       *
4349       *     @type WP_User_Request $request     User request object.
4350       *     @type string          $email       The email address this is being sent to.
4351       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4352       *     @type string          $confirm_url The link to click on to confirm the account action.
4353       *     @type string          $sitename    The site name sending the mail.
4354       *     @type string          $siteurl     The site URL sending the mail.
4355       * }
4356       */
4357      $content = apply_filters( 'user_request_action_email_content', $content, $email_data );
4358  
4359      $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
4360      $content = str_replace( '###CONFIRM_URL###', esc_url_raw( $email_data['confirm_url'] ), $content );
4361      $content = str_replace( '###EMAIL###', $email_data['email'], $content );
4362      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
4363      $content = str_replace( '###SITEURL###', esc_url_raw( $email_data['siteurl'] ), $content );
4364  
4365      $headers = '';
4366  
4367      /**
4368       * Filters the headers of the email sent when an account action is attempted.
4369       *
4370       * @since 5.4.0
4371       *
4372       * @param string|array $headers    The email headers.
4373       * @param string       $subject    The email subject.
4374       * @param string       $content    The email content.
4375       * @param int          $request_id The request ID.
4376       * @param array        $email_data {
4377       *     Data relating to the account action email.
4378       *
4379       *     @type WP_User_Request $request     User request object.
4380       *     @type string          $email       The email address this is being sent to.
4381       *     @type string          $description Description of the action being performed so the user knows what the email is for.
4382       *     @type string          $confirm_url The link to click on to confirm the account action.
4383       *     @type string          $sitename    The site name sending the mail.
4384       *     @type string          $siteurl     The site URL sending the mail.
4385       * }
4386       */
4387      $headers = apply_filters( 'user_request_action_email_headers', $headers, $subject, $content, $request_id, $email_data );
4388  
4389      $email_sent = wp_mail( $email_data['email'], $subject, $content, $headers );
4390  
4391      if ( $switched_locale ) {
4392          restore_previous_locale();
4393      }
4394  
4395      if ( ! $email_sent ) {
4396          return new WP_Error( 'privacy_email_error', __( 'Unable to send personal data export confirmation email.' ) );
4397      }
4398  
4399      return true;
4400  }
4401  
4402  /**
4403   * Returns a confirmation key for a user action and stores the hashed version for future comparison.
4404   *
4405   * @since 4.9.6
4406   *
4407   * @param int $request_id Request ID.
4408   * @return string Confirmation key.
4409   */
4410  function wp_generate_user_request_key( $request_id ) {
4411      global $wp_hasher;
4412  
4413      // Generate something random for a confirmation key.
4414      $key = wp_generate_password( 20, false );
4415  
4416      // Return the key, hashed.
4417      if ( empty( $wp_hasher ) ) {
4418          require_once  ABSPATH . WPINC . '/class-phpass.php';
4419          $wp_hasher = new PasswordHash( 8, true );
4420      }
4421  
4422      wp_update_post(
4423          array(
4424              'ID'            => $request_id,
4425              'post_status'   => 'request-pending',
4426              'post_password' => $wp_hasher->HashPassword( $key ),
4427          )
4428      );
4429  
4430      return $key;
4431  }
4432  
4433  /**
4434   * Validate a user request by comparing the key with the request's key.
4435   *
4436   * @since 4.9.6
4437   *
4438   * @param string $request_id ID of the request being confirmed.
4439   * @param string $key        Provided key to validate.
4440   * @return true|WP_Error True on success, WP_Error on failure.
4441   */
4442  function wp_validate_user_request_key( $request_id, $key ) {
4443      global $wp_hasher;
4444  
4445      $request_id       = absint( $request_id );
4446      $request          = wp_get_user_request( $request_id );
4447      $saved_key        = $request->confirm_key;
4448      $key_request_time = $request->modified_timestamp;
4449  
4450      if ( ! $request || ! $saved_key || ! $key_request_time ) {
4451          return new WP_Error( 'invalid_request', __( 'Invalid personal data request.' ) );
4452      }
4453  
4454      if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
4455          return new WP_Error( 'expired_request', __( 'This personal data request has expired.' ) );
4456      }
4457  
4458      if ( empty( $key ) ) {
4459          return new WP_Error( 'missing_key', __( 'The confirmation key is missing from this personal data request.' ) );
4460      }
4461  
4462      if ( empty( $wp_hasher ) ) {
4463          require_once  ABSPATH . WPINC . '/class-phpass.php';
4464          $wp_hasher = new PasswordHash( 8, true );
4465      }
4466  
4467      /**
4468       * Filters the expiration time of confirm keys.
4469       *
4470       * @since 4.9.6
4471       *
4472       * @param int $expiration The expiration time in seconds.
4473       */
4474      $expiration_duration = (int) apply_filters( 'user_request_key_expiration', DAY_IN_SECONDS );
4475      $expiration_time     = $key_request_time + $expiration_duration;
4476  
4477      if ( ! $wp_hasher->CheckPassword( $key, $saved_key ) ) {
4478          return new WP_Error( 'invalid_key', __( 'The confirmation key is invalid for this personal data request.' ) );
4479      }
4480  
4481      if ( ! $expiration_time || time() > $expiration_time ) {
4482          return new WP_Error( 'expired_key', __( 'The confirmation key has expired for this personal data request.' ) );
4483      }
4484  
4485      return true;
4486  }
4487  
4488  /**
4489   * Return the user request object for the specified request ID.
4490   *
4491   * @since 4.9.6
4492   *
4493   * @param int $request_id The ID of the user request.
4494   * @return WP_User_Request|false
4495   */
4496  function wp_get_user_request( $request_id ) {
4497      $request_id = absint( $request_id );
4498      $post       = get_post( $request_id );
4499  
4500      if ( ! $post || 'user_request' !== $post->post_type ) {
4501          return false;
4502      }
4503  
4504      return new WP_User_Request( $post );
4505  }
4506  
4507  /**
4508   * Checks if Application Passwords is globally available.
4509   *
4510   * By default, Application Passwords is available to all sites using SSL or to local environments.
4511   * Use {@see 'wp_is_application_passwords_available'} to adjust its availability.
4512   *
4513   * @since 5.6.0
4514   *
4515   * @return bool
4516   */
4517  function wp_is_application_passwords_available() {
4518      $available = is_ssl() || 'local' === wp_get_environment_type();
4519  
4520      /**
4521       * Filters whether Application Passwords is available.
4522       *
4523       * @since 5.6.0
4524       *
4525       * @param bool $available True if available, false otherwise.
4526       */
4527      return apply_filters( 'wp_is_application_passwords_available', $available );
4528  }
4529  
4530  /**
4531   * Checks if Application Passwords is available for a specific user.
4532   *
4533   * By default all users can use Application Passwords. Use {@see 'wp_is_application_passwords_available_for_user'}
4534   * to restrict availability to certain users.
4535   *
4536   * @since 5.6.0
4537   *
4538   * @param int|WP_User $user The user to check.
4539   * @return bool
4540   */
4541  function wp_is_application_passwords_available_for_user( $user ) {
4542      if ( ! wp_is_application_passwords_available() ) {
4543          return false;
4544      }
4545  
4546      if ( ! is_object( $user ) ) {
4547          $user = get_userdata( $user );
4548      }
4549  
4550      if ( ! $user || ! $user->exists() ) {
4551          return false;
4552      }
4553  
4554      /**
4555       * Filters whether Application Passwords is available for a specific user.
4556       *
4557       * @since 5.6.0
4558       *
4559       * @param bool    $available True if available, false otherwise.
4560       * @param WP_User $user      The user to check.
4561       */
4562      return apply_filters( 'wp_is_application_passwords_available_for_user', true, $user );
4563  }


Generated: Tue Oct 26 01:00:02 2021 Cross-referenced by PHPXref 0.7.1