[ Index ]

WordPress 5.4.1

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]     [ Statistics ]    

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              __( 'Unknown username. Check again or try your email address.' )
 153          );
 154      }
 155  
 156      /**
 157       * Filters whether the given user can be authenticated with the provided $password.
 158       *
 159       * @since 2.5.0
 160       *
 161       * @param WP_User|WP_Error $user     WP_User or WP_Error object if a previous
 162       *                                   callback failed authentication.
 163       * @param string           $password Password to check against the user.
 164       */
 165      $user = apply_filters( 'wp_authenticate_user', $user, $password );
 166      if ( is_wp_error( $user ) ) {
 167          return $user;
 168      }
 169  
 170      if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {
 171          return new WP_Error(
 172              'incorrect_password',
 173              sprintf(
 174                  /* translators: %s: User name. */
 175                  __( '<strong>Error</strong>: The password you entered for the username %s is incorrect.' ),
 176                  '<strong>' . $username . '</strong>'
 177              ) .
 178              ' <a href="' . wp_lostpassword_url() . '">' .
 179              __( 'Lost your password?' ) .
 180              '</a>'
 181          );
 182      }
 183  
 184      return $user;
 185  }
 186  
 187  /**
 188   * Authenticates a user using the email and password.
 189   *
 190   * @since 4.5.0
 191   *
 192   * @param WP_User|WP_Error|null $user     WP_User or WP_Error object if a previous
 193   *                                        callback failed authentication.
 194   * @param string                $email    Email address for authentication.
 195   * @param string                $password Password for authentication.
 196   * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 197   */
 198  function wp_authenticate_email_password( $user, $email, $password ) {
 199      if ( $user instanceof WP_User ) {
 200          return $user;
 201      }
 202  
 203      if ( empty( $email ) || empty( $password ) ) {
 204          if ( is_wp_error( $user ) ) {
 205              return $user;
 206          }
 207  
 208          $error = new WP_Error();
 209  
 210          if ( empty( $email ) ) {
 211              // Uses 'empty_username' for back-compat with wp_signon().
 212              $error->add( 'empty_username', __( '<strong>Error</strong>: The email field is empty.' ) );
 213          }
 214  
 215          if ( empty( $password ) ) {
 216              $error->add( 'empty_password', __( '<strong>Error</strong>: The password field is empty.' ) );
 217          }
 218  
 219          return $error;
 220      }
 221  
 222      if ( ! is_email( $email ) ) {
 223          return $user;
 224      }
 225  
 226      $user = get_user_by( 'email', $email );
 227  
 228      if ( ! $user ) {
 229          return new WP_Error(
 230              'invalid_email',
 231              __( 'Unknown email address. Check again or try your username.' )
 232          );
 233      }
 234  
 235      /** This filter is documented in wp-includes/user.php */
 236      $user = apply_filters( 'wp_authenticate_user', $user, $password );
 237  
 238      if ( is_wp_error( $user ) ) {
 239          return $user;
 240      }
 241  
 242      if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {
 243          return new WP_Error(
 244              'incorrect_password',
 245              sprintf(
 246                  /* translators: %s: Email address. */
 247                  __( '<strong>Error</strong>: The password you entered for the email address %s is incorrect.' ),
 248                  '<strong>' . $email . '</strong>'
 249              ) .
 250              ' <a href="' . wp_lostpassword_url() . '">' .
 251              __( 'Lost your password?' ) .
 252              '</a>'
 253          );
 254      }
 255  
 256      return $user;
 257  }
 258  
 259  /**
 260   * Authenticate the user using the WordPress auth cookie.
 261   *
 262   * @since 2.8.0
 263   *
 264   * @global string $auth_secure_cookie
 265   *
 266   * @param WP_User|WP_Error|null $user     WP_User or WP_Error object from a previous callback. Default null.
 267   * @param string                $username Username. If not empty, cancels the cookie authentication.
 268   * @param string                $password Password. If not empty, cancels the cookie authentication.
 269   * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
 270   */
 271  function wp_authenticate_cookie( $user, $username, $password ) {
 272      if ( $user instanceof WP_User ) {
 273          return $user;
 274      }
 275  
 276      if ( empty( $username ) && empty( $password ) ) {
 277          $user_id = wp_validate_auth_cookie();
 278          if ( $user_id ) {
 279              return new WP_User( $user_id );
 280          }
 281  
 282          global $auth_secure_cookie;
 283  
 284          if ( $auth_secure_cookie ) {
 285              $auth_cookie = SECURE_AUTH_COOKIE;
 286          } else {
 287              $auth_cookie = AUTH_COOKIE;
 288          }
 289  
 290          if ( ! empty( $_COOKIE[ $auth_cookie ] ) ) {
 291              return new WP_Error( 'expired_session', __( 'Please log in again.' ) );
 292          }
 293  
 294          // If the cookie is not set, be silent.
 295      }
 296  
 297      return $user;
 298  }
 299  
 300  /**
 301   * For Multisite blogs, check if the authenticated user has been marked as a
 302   * spammer, or if the user's primary blog has been marked as spam.
 303   *
 304   * @since 3.7.0
 305   *
 306   * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
 307   * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
 308   */
 309  function wp_authenticate_spam_check( $user ) {
 310      if ( $user instanceof WP_User && is_multisite() ) {
 311          /**
 312           * Filters whether the user has been marked as a spammer.
 313           *
 314           * @since 3.7.0
 315           *
 316           * @param bool    $spammed Whether the user is considered a spammer.
 317           * @param WP_User $user    User to check against.
 318           */
 319          $spammed = apply_filters( 'check_is_user_spammed', is_user_spammy( $user ), $user );
 320  
 321          if ( $spammed ) {
 322              return new WP_Error( 'spammer_account', __( '<strong>Error</strong>: Your account has been marked as a spammer.' ) );
 323          }
 324      }
 325      return $user;
 326  }
 327  
 328  /**
 329   * Validates the logged-in cookie.
 330   *
 331   * Checks the logged-in cookie if the previous auth cookie could not be
 332   * validated and parsed.
 333   *
 334   * This is a callback for the {@see 'determine_current_user'} filter, rather than API.
 335   *
 336   * @since 3.9.0
 337   *
 338   * @param int|bool $user_id The user ID (or false) as received from
 339   *                          the `determine_current_user` filter.
 340   * @return int|false User ID if validated, false otherwise. If a user ID from
 341   *                   an earlier filter callback is received, that value is returned.
 342   */
 343  function wp_validate_logged_in_cookie( $user_id ) {
 344      if ( $user_id ) {
 345          return $user_id;
 346      }
 347  
 348      if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
 349          return false;
 350      }
 351  
 352      return wp_validate_auth_cookie( $_COOKIE[ LOGGED_IN_COOKIE ], 'logged_in' );
 353  }
 354  
 355  /**
 356   * Number of posts user has written.
 357   *
 358   * @since 3.0.0
 359   * @since 4.1.0 Added `$post_type` argument.
 360   * @since 4.3.0 Added `$public_only` argument. Added the ability to pass an array
 361   *              of post types to `$post_type`.
 362   *
 363   * @global wpdb $wpdb WordPress database abstraction object.
 364   *
 365   * @param int          $userid      User ID.
 366   * @param array|string $post_type   Optional. Single post type or array of post types to count the number of posts for. Default 'post'.
 367   * @param bool         $public_only Optional. Whether to only return counts for public posts. Default false.
 368   * @return string Number of posts the user has written in this post type.
 369   */
 370  function count_user_posts( $userid, $post_type = 'post', $public_only = false ) {
 371      global $wpdb;
 372  
 373      $where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
 374  
 375      $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
 376  
 377      /**
 378       * Filters the number of posts a user has written.
 379       *
 380       * @since 2.7.0
 381       * @since 4.1.0 Added `$post_type` argument.
 382       * @since 4.3.1 Added `$public_only` argument.
 383       *
 384       * @param int          $count       The user's post count.
 385       * @param int          $userid      User ID.
 386       * @param string|array $post_type   Single post type or array of post types to count the number of posts for.
 387       * @param bool         $public_only Whether to limit counted posts to public posts.
 388       */
 389      return apply_filters( 'get_usernumposts', $count, $userid, $post_type, $public_only );
 390  }
 391  
 392  /**
 393   * Number of posts written by a list of users.
 394   *
 395   * @since 3.0.0
 396   *
 397   * @global wpdb $wpdb WordPress database abstraction object.
 398   *
 399   * @param int[]           $users       Array of user IDs.
 400   * @param string|string[] $post_type   Optional. Single post type or array of post types to check. Defaults to 'post'.
 401   * @param bool            $public_only Optional. Only return counts for public posts.  Defaults to false.
 402   * @return string[] Amount of posts each user has written, as strings, keyed by user ID.
 403   */
 404  function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
 405      global $wpdb;
 406  
 407      $count = array();
 408      if ( empty( $users ) || ! is_array( $users ) ) {
 409          return $count;
 410      }
 411  
 412      $userlist = implode( ',', array_map( 'absint', $users ) );
 413      $where    = get_posts_by_author_sql( $post_type, true, null, $public_only );
 414  
 415      $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
 416      foreach ( $result as $row ) {
 417          $count[ $row[0] ] = $row[1];
 418      }
 419  
 420      foreach ( $users as $id ) {
 421          if ( ! isset( $count[ $id ] ) ) {
 422              $count[ $id ] = 0;
 423          }
 424      }
 425  
 426      return $count;
 427  }
 428  
 429  //
 430  // User option functions.
 431  //
 432  
 433  /**
 434   * Get the current user's ID
 435   *
 436   * @since MU (3.0.0)
 437   *
 438   * @return int The current user's ID, or 0 if no user is logged in.
 439   */
 440  function get_current_user_id() {
 441      if ( ! function_exists( 'wp_get_current_user' ) ) {
 442          return 0;
 443      }
 444      $user = wp_get_current_user();
 445      return ( isset( $user->ID ) ? (int) $user->ID : 0 );
 446  }
 447  
 448  /**
 449   * Retrieve user option that can be either per Site or per Network.
 450   *
 451   * If the user ID is not given, then the current user will be used instead. If
 452   * the user ID is given, then the user data will be retrieved. The filter for
 453   * the result, will also pass the original option name and finally the user data
 454   * object as the third parameter.
 455   *
 456   * The option will first check for the per site name and then the per Network name.
 457   *
 458   * @since 2.0.0
 459   *
 460   * @global wpdb $wpdb WordPress database abstraction object.
 461   *
 462   * @param string $option     User option name.
 463   * @param int    $user       Optional. User ID.
 464   * @param string $deprecated Use get_option() to check for an option in the options table.
 465   * @return mixed User option value on success, false on failure.
 466   */
 467  function get_user_option( $option, $user = 0, $deprecated = '' ) {
 468      global $wpdb;
 469  
 470      if ( ! empty( $deprecated ) ) {
 471          _deprecated_argument( __FUNCTION__, '3.0.0' );
 472      }
 473  
 474      if ( empty( $user ) ) {
 475          $user = get_current_user_id();
 476      }
 477  
 478      $user = get_userdata( $user );
 479      if ( ! $user ) {
 480          return false;
 481      }
 482  
 483      $prefix = $wpdb->get_blog_prefix();
 484      if ( $user->has_prop( $prefix . $option ) ) { // Blog-specific.
 485          $result = $user->get( $prefix . $option );
 486      } elseif ( $user->has_prop( $option ) ) { // User-specific and cross-blog.
 487          $result = $user->get( $option );
 488      } else {
 489          $result = false;
 490      }
 491  
 492      /**
 493       * Filters a specific user option value.
 494       *
 495       * The dynamic portion of the hook name, `$option`, refers to the user option name.
 496       *
 497       * @since 2.5.0
 498       *
 499       * @param mixed   $result Value for the user's option.
 500       * @param string  $option Name of the option being retrieved.
 501       * @param WP_User $user   WP_User object of the user whose option is being retrieved.
 502       */
 503      return apply_filters( "get_user_option_{$option}", $result, $option, $user );
 504  }
 505  
 506  /**
 507   * Update user option with global blog capability.
 508   *
 509   * User options are just like user metadata except that they have support for
 510   * global blog options. If the 'global' parameter is false, which it is by default
 511   * it will prepend the WordPress table prefix to the option name.
 512   *
 513   * Deletes the user option if $newvalue is empty.
 514   *
 515   * @since 2.0.0
 516   *
 517   * @global wpdb $wpdb WordPress database abstraction object.
 518   *
 519   * @param int    $user_id     User ID.
 520   * @param string $option_name User option name.
 521   * @param mixed  $newvalue    User option value.
 522   * @param bool   $global      Optional. Whether option name is global or blog specific.
 523   *                            Default false (blog specific).
 524   * @return int|bool User meta ID if the option didn't exist, true on successful update,
 525   *                  false on failure.
 526   */
 527  function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
 528      global $wpdb;
 529  
 530      if ( ! $global ) {
 531          $option_name = $wpdb->get_blog_prefix() . $option_name;
 532      }
 533  
 534      return update_user_meta( $user_id, $option_name, $newvalue );
 535  }
 536  
 537  /**
 538   * Delete user option with global blog capability.
 539   *
 540   * User options are just like user metadata except that they have support for
 541   * global blog options. If the 'global' parameter is false, which it is by default
 542   * it will prepend the WordPress table prefix to the option name.
 543   *
 544   * @since 3.0.0
 545   *
 546   * @global wpdb $wpdb WordPress database abstraction object.
 547   *
 548   * @param int    $user_id     User ID
 549   * @param string $option_name User option name.
 550   * @param bool   $global      Optional. Whether option name is global or blog specific.
 551   *                            Default false (blog specific).
 552   * @return bool True on success, false on failure.
 553   */
 554  function delete_user_option( $user_id, $option_name, $global = false ) {
 555      global $wpdb;
 556  
 557      if ( ! $global ) {
 558          $option_name = $wpdb->get_blog_prefix() . $option_name;
 559      }
 560      return delete_user_meta( $user_id, $option_name );
 561  }
 562  
 563  /**
 564   * Retrieve list of users matching criteria.
 565   *
 566   * @since 3.1.0
 567   *
 568   * @see WP_User_Query
 569   *
 570   * @param array $args Optional. Arguments to retrieve users. See WP_User_Query::prepare_query().
 571   *                    for more information on accepted arguments.
 572   * @return array List of users.
 573   */
 574  function get_users( $args = array() ) {
 575  
 576      $args                = wp_parse_args( $args );
 577      $args['count_total'] = false;
 578  
 579      $user_search = new WP_User_Query( $args );
 580  
 581      return (array) $user_search->get_results();
 582  }
 583  
 584  /**
 585   * Get the sites a user belongs to.
 586   *
 587   * @since 3.0.0
 588   * @since 4.7.0 Converted to use `get_sites()`.
 589   *
 590   * @global wpdb $wpdb WordPress database abstraction object.
 591   *
 592   * @param int  $user_id User ID
 593   * @param bool $all     Whether to retrieve all sites, or only sites that are not
 594   *                      marked as deleted, archived, or spam.
 595   * @return array A list of the user's sites. An empty array if the user doesn't exist
 596   *               or belongs to no sites.
 597   */
 598  function get_blogs_of_user( $user_id, $all = false ) {
 599      global $wpdb;
 600  
 601      $user_id = (int) $user_id;
 602  
 603      // Logged out users can't have sites.
 604      if ( empty( $user_id ) ) {
 605          return array();
 606      }
 607  
 608      /**
 609       * Filters the list of a user's sites before it is populated.
 610       *
 611       * Passing a non-null value to the filter will effectively short circuit
 612       * get_blogs_of_user(), returning that value instead.
 613       *
 614       * @since 4.6.0
 615       *
 616       * @param null|array $sites   An array of site objects of which the user is a member.
 617       * @param int        $user_id User ID.
 618       * @param bool       $all     Whether the returned array should contain all sites, including
 619       *                            those marked 'deleted', 'archived', or 'spam'. Default false.
 620       */
 621      $sites = apply_filters( 'pre_get_blogs_of_user', null, $user_id, $all );
 622  
 623      if ( null !== $sites ) {
 624          return $sites;
 625      }
 626  
 627      $keys = get_user_meta( $user_id );
 628      if ( empty( $keys ) ) {
 629          return array();
 630      }
 631  
 632      if ( ! is_multisite() ) {
 633          $site_id                        = get_current_blog_id();
 634          $sites                          = array( $site_id => new stdClass );
 635          $sites[ $site_id ]->userblog_id = $site_id;
 636          $sites[ $site_id ]->blogname    = get_option( 'blogname' );
 637          $sites[ $site_id ]->domain      = '';
 638          $sites[ $site_id ]->path        = '';
 639          $sites[ $site_id ]->site_id     = 1;
 640          $sites[ $site_id ]->siteurl     = get_option( 'siteurl' );
 641          $sites[ $site_id ]->archived    = 0;
 642          $sites[ $site_id ]->spam        = 0;
 643          $sites[ $site_id ]->deleted     = 0;
 644          return $sites;
 645      }
 646  
 647      $site_ids = array();
 648  
 649      if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
 650          $site_ids[] = 1;
 651          unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
 652      }
 653  
 654      $keys = array_keys( $keys );
 655  
 656      foreach ( $keys as $key ) {
 657          if ( 'capabilities' !== substr( $key, -12 ) ) {
 658              continue;
 659          }
 660          if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) ) {
 661              continue;
 662          }
 663          $site_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
 664          if ( ! is_numeric( $site_id ) ) {
 665              continue;
 666          }
 667  
 668          $site_ids[] = (int) $site_id;
 669      }
 670  
 671      $sites = array();
 672  
 673      if ( ! empty( $site_ids ) ) {
 674          $args = array(
 675              'number'                 => '',
 676              'site__in'               => $site_ids,
 677              'update_site_meta_cache' => false,
 678          );
 679          if ( ! $all ) {
 680              $args['archived'] = 0;
 681              $args['spam']     = 0;
 682              $args['deleted']  = 0;
 683          }
 684  
 685          $_sites = get_sites( $args );
 686  
 687          foreach ( $_sites as $site ) {
 688              $sites[ $site->id ] = (object) array(
 689                  'userblog_id' => $site->id,
 690                  'blogname'    => $site->blogname,
 691                  'domain'      => $site->domain,
 692                  'path'        => $site->path,
 693                  'site_id'     => $site->network_id,
 694                  'siteurl'     => $site->siteurl,
 695                  'archived'    => $site->archived,
 696                  'mature'      => $site->mature,
 697                  'spam'        => $site->spam,
 698                  'deleted'     => $site->deleted,
 699              );
 700          }
 701      }
 702  
 703      /**
 704       * Filters the list of sites a user belongs to.
 705       *
 706       * @since MU (3.0.0)
 707       *
 708       * @param array $sites   An array of site objects belonging to the user.
 709       * @param int   $user_id User ID.
 710       * @param bool  $all     Whether the returned sites array should contain all sites, including
 711       *                       those marked 'deleted', 'archived', or 'spam'. Default false.
 712       */
 713      return apply_filters( 'get_blogs_of_user', $sites, $user_id, $all );
 714  }
 715  
 716  /**
 717   * Find out whether a user is a member of a given blog.
 718   *
 719   * @since MU (3.0.0)
 720   *
 721   * @global wpdb $wpdb WordPress database abstraction object.
 722   *
 723   * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
 724   * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
 725   * @return bool
 726   */
 727  function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
 728      global $wpdb;
 729  
 730      $user_id = (int) $user_id;
 731      $blog_id = (int) $blog_id;
 732  
 733      if ( empty( $user_id ) ) {
 734          $user_id = get_current_user_id();
 735      }
 736  
 737      // Technically not needed, but does save calls to get_site() and get_user_meta()
 738      // in the event that the function is called when a user isn't logged in.
 739      if ( empty( $user_id ) ) {
 740          return false;
 741      } else {
 742          $user = get_userdata( $user_id );
 743          if ( ! $user instanceof WP_User ) {
 744              return false;
 745          }
 746      }
 747  
 748      if ( ! is_multisite() ) {
 749          return true;
 750      }
 751  
 752      if ( empty( $blog_id ) ) {
 753          $blog_id = get_current_blog_id();
 754      }
 755  
 756      $blog = get_site( $blog_id );
 757  
 758      if ( ! $blog || ! isset( $blog->domain ) || $blog->archived || $blog->spam || $blog->deleted ) {
 759          return false;
 760      }
 761  
 762      $keys = get_user_meta( $user_id );
 763      if ( empty( $keys ) ) {
 764          return false;
 765      }
 766  
 767      // No underscore before capabilities in $base_capabilities_key.
 768      $base_capabilities_key = $wpdb->base_prefix . 'capabilities';
 769      $site_capabilities_key = $wpdb->base_prefix . $blog_id . '_capabilities';
 770  
 771      if ( isset( $keys[ $base_capabilities_key ] ) && 1 == $blog_id ) {
 772          return true;
 773      }
 774  
 775      if ( isset( $keys[ $site_capabilities_key ] ) ) {
 776          return true;
 777      }
 778  
 779      return false;
 780  }
 781  
 782  /**
 783   * Adds meta data to a user.
 784   *
 785   * @since 3.0.0
 786   *
 787   * @param int    $user_id    User ID.
 788   * @param string $meta_key   Metadata name.
 789   * @param mixed  $meta_value Metadata value.
 790   * @param bool   $unique     Optional. Whether the same key should not be added. Default false.
 791   * @return int|false Meta ID on success, false on failure.
 792   */
 793  function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
 794      return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
 795  }
 796  
 797  /**
 798   * Remove metadata matching criteria from a user.
 799   *
 800   * You can match based on the key, or key and value. Removing based on key and
 801   * value, will keep from removing duplicate metadata with the same key. It also
 802   * allows removing all metadata matching key, if needed.
 803   *
 804   * @since 3.0.0
 805   * @link https://developer.wordpress.org/reference/functions/delete_user_meta/
 806   *
 807   * @param int    $user_id    User ID
 808   * @param string $meta_key   Metadata name.
 809   * @param mixed  $meta_value Optional. Metadata value.
 810   * @return bool True on success, false on failure.
 811   */
 812  function delete_user_meta( $user_id, $meta_key, $meta_value = '' ) {
 813      return delete_metadata( 'user', $user_id, $meta_key, $meta_value );
 814  }
 815  
 816  /**
 817   * Retrieve user meta field for a user.
 818   *
 819   * @since 3.0.0
 820   * @link https://developer.wordpress.org/reference/functions/get_user_meta/
 821   *
 822   * @param int    $user_id User ID.
 823   * @param string $key     Optional. The meta key to retrieve. By default, returns data for all keys.
 824   * @param bool   $single  Whether to return a single value.
 825   * @return mixed Will be an array if $single is false. Will be value of meta data field if $single is true.
 826   */
 827  function get_user_meta( $user_id, $key = '', $single = false ) {
 828      return get_metadata( 'user', $user_id, $key, $single );
 829  }
 830  
 831  /**
 832   * Update user meta field based on user ID.
 833   *
 834   * Use the $prev_value parameter to differentiate between meta fields with the
 835   * same key and user ID.
 836   *
 837   * If the meta field for the user does not exist, it will be added.
 838   *
 839   * @since 3.0.0
 840   * @link https://developer.wordpress.org/reference/functions/update_user_meta/
 841   *
 842   * @param int    $user_id    User ID.
 843   * @param string $meta_key   Metadata key.
 844   * @param mixed  $meta_value Metadata value.
 845   * @param mixed  $prev_value Optional. Previous value to check before removing.
 846   * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
 847   */
 848  function update_user_meta( $user_id, $meta_key, $meta_value, $prev_value = '' ) {
 849      return update_metadata( 'user', $user_id, $meta_key, $meta_value, $prev_value );
 850  }
 851  
 852  /**
 853   * Count number of users who have each of the user roles.
 854   *
 855   * Assumes there are neither duplicated nor orphaned capabilities meta_values.
 856   * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
 857   * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
 858   * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
 859   *
 860   * @since 3.0.0
 861   * @since 4.4.0 The number of users with no role is now included in the `none` element.
 862   * @since 4.9.0 The `$site_id` parameter was added to support multisite.
 863   *
 864   * @global wpdb $wpdb WordPress database abstraction object.
 865   *
 866   * @param string   $strategy Optional. The computational strategy to use when counting the users.
 867   *                           Accepts either 'time' or 'memory'. Default 'time'.
 868   * @param int|null $site_id  Optional. The site ID to count users for. Defaults to the current site.
 869   * @return array {
 870   *     User counts.
 871   *
 872   *     @type int   $total_users Total number of users on the site.
 873   *     @type int[] $avail_roles Array of user counts keyed by user role.
 874   * }
 875   */
 876  function count_users( $strategy = 'time', $site_id = null ) {
 877      global $wpdb;
 878  
 879      // Initialize.
 880      if ( ! $site_id ) {
 881          $site_id = get_current_blog_id();
 882      }
 883  
 884      /**
 885       * Filter the user count before queries are run. Return a non-null value to cause count_users()
 886       * to return early.
 887       *
 888       * @since 5.1.0
 889       *
 890       * @param null|string $result   The value to return instead. Default null to continue with the query.
 891       * @param string      $strategy Optional. The computational strategy to use when counting the users.
 892       *                              Accepts either 'time' or 'memory'. Default 'time'.
 893       * @param int|null    $site_id  Optional. The site ID to count users for. Defaults to the current site.
 894       */
 895      $pre = apply_filters( 'pre_count_users', null, $strategy, $site_id );
 896  
 897      if ( null !== $pre ) {
 898          return $pre;
 899      }
 900  
 901      $blog_prefix = $wpdb->get_blog_prefix( $site_id );
 902      $result      = array();
 903  
 904      if ( 'time' == $strategy ) {
 905          if ( is_multisite() && get_current_blog_id() != $site_id ) {
 906              switch_to_blog( $site_id );
 907              $avail_roles = wp_roles()->get_names();
 908              restore_current_blog();
 909          } else {
 910              $avail_roles = wp_roles()->get_names();
 911          }
 912  
 913          // Build a CPU-intensive query that will return concise information.
 914          $select_count = array();
 915          foreach ( $avail_roles as $this_role => $name ) {
 916              $select_count[] = $wpdb->prepare( 'COUNT(NULLIF(`meta_value` LIKE %s, false))', '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%' );
 917          }
 918          $select_count[] = "COUNT(NULLIF(`meta_value` = 'a:0:{}', false))";
 919          $select_count   = implode( ', ', $select_count );
 920  
 921          // Add the meta_value index to the selection list, then run the query.
 922          $row = $wpdb->get_row(
 923              "
 924              SELECT {$select_count}, COUNT(*)
 925              FROM {$wpdb->usermeta}
 926              INNER JOIN {$wpdb->users} ON user_id = ID
 927              WHERE meta_key = '{$blog_prefix}capabilities'
 928          ",
 929              ARRAY_N
 930          );
 931  
 932          // Run the previous loop again to associate results with role names.
 933          $col         = 0;
 934          $role_counts = array();
 935          foreach ( $avail_roles as $this_role => $name ) {
 936              $count = (int) $row[ $col++ ];
 937              if ( $count > 0 ) {
 938                  $role_counts[ $this_role ] = $count;
 939              }
 940          }
 941  
 942          $role_counts['none'] = (int) $row[ $col++ ];
 943  
 944          // Get the meta_value index from the end of the result set.
 945          $total_users = (int) $row[ $col ];
 946  
 947          $result['total_users'] = $total_users;
 948          $result['avail_roles'] =& $role_counts;
 949      } else {
 950          $avail_roles = array(
 951              'none' => 0,
 952          );
 953  
 954          $users_of_blog = $wpdb->get_col(
 955              "
 956              SELECT meta_value
 957              FROM {$wpdb->usermeta}
 958              INNER JOIN {$wpdb->users} ON user_id = ID
 959              WHERE meta_key = '{$blog_prefix}capabilities'
 960          "
 961          );
 962  
 963          foreach ( $users_of_blog as $caps_meta ) {
 964              $b_roles = maybe_unserialize( $caps_meta );
 965              if ( ! is_array( $b_roles ) ) {
 966                  continue;
 967              }
 968              if ( empty( $b_roles ) ) {
 969                  $avail_roles['none']++;
 970              }
 971              foreach ( $b_roles as $b_role => $val ) {
 972                  if ( isset( $avail_roles[ $b_role ] ) ) {
 973                      $avail_roles[ $b_role ]++;
 974                  } else {
 975                      $avail_roles[ $b_role ] = 1;
 976                  }
 977              }
 978          }
 979  
 980          $result['total_users'] = count( $users_of_blog );
 981          $result['avail_roles'] =& $avail_roles;
 982      }
 983  
 984      return $result;
 985  }
 986  
 987  //
 988  // Private helper functions.
 989  //
 990  
 991  /**
 992   * Set up global user vars.
 993   *
 994   * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
 995   *
 996   * @since 2.0.4
 997   *
 998   * @global string  $user_login    The user username for logging in
 999   * @global WP_User $userdata      User data.
1000   * @global int     $user_level    The level of the user
1001   * @global int     $user_ID       The ID of the user
1002   * @global string  $user_email    The email address of the user
1003   * @global string  $user_url      The url in the user's profile
1004   * @global string  $user_identity The display name of the user
1005   *
1006   * @param int $for_user_id Optional. User ID to set up global data. Default 0.
1007   */
1008  function setup_userdata( $for_user_id = 0 ) {
1009      global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
1010  
1011      if ( ! $for_user_id ) {
1012          $for_user_id = get_current_user_id();
1013      }
1014      $user = get_userdata( $for_user_id );
1015  
1016      if ( ! $user ) {
1017          $user_ID       = 0;
1018          $user_level    = 0;
1019          $userdata      = null;
1020          $user_login    = '';
1021          $user_email    = '';
1022          $user_url      = '';
1023          $user_identity = '';
1024          return;
1025      }
1026  
1027      $user_ID       = (int) $user->ID;
1028      $user_level    = (int) $user->user_level;
1029      $userdata      = $user;
1030      $user_login    = $user->user_login;
1031      $user_email    = $user->user_email;
1032      $user_url      = $user->user_url;
1033      $user_identity = $user->display_name;
1034  }
1035  
1036  /**
1037   * Create dropdown HTML content of users.
1038   *
1039   * The content can either be displayed, which it is by default or retrieved by
1040   * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
1041   * need to be used; all users will be displayed in that case. Only one can be
1042   * used, either 'include' or 'exclude', but not both.
1043   *
1044   * The available arguments are as follows:
1045   *
1046   * @since 2.3.0
1047   * @since 4.5.0 Added the 'display_name_with_login' value for 'show'.
1048   * @since 4.7.0 Added the `$role`, `$role__in`, and `$role__not_in` parameters.
1049   *
1050   * @param array|string $args {
1051   *     Optional. Array or string of arguments to generate a drop-down of users.
1052   *     See WP_User_Query::prepare_query() for additional available arguments.
1053   *
1054   *     @type string       $show_option_all         Text to show as the drop-down default (all).
1055   *                                                 Default empty.
1056   *     @type string       $show_option_none        Text to show as the drop-down default when no
1057   *                                                 users were found. Default empty.
1058   *     @type int|string   $option_none_value       Value to use for $show_option_non when no users
1059   *                                                 were found. Default -1.
1060   *     @type string       $hide_if_only_one_author Whether to skip generating the drop-down
1061   *                                                 if only one user was found. Default empty.
1062   *     @type string       $orderby                 Field to order found users by. Accepts user fields.
1063   *                                                 Default 'display_name'.
1064   *     @type string       $order                   Whether to order users in ascending or descending
1065   *                                                 order. Accepts 'ASC' (ascending) or 'DESC' (descending).
1066   *                                                 Default 'ASC'.
1067   *     @type array|string $include                 Array or comma-separated list of user IDs to include.
1068   *                                                 Default empty.
1069   *     @type array|string $exclude                 Array or comma-separated list of user IDs to exclude.
1070   *                                                 Default empty.
1071   *     @type bool|int     $multi                   Whether to skip the ID attribute on the 'select' element.
1072   *                                                 Accepts 1|true or 0|false. Default 0|false.
1073   *     @type string       $show                    User data to display. If the selected item is empty
1074   *                                                 then the 'user_login' will be displayed in parentheses.
1075   *                                                 Accepts any user field, or 'display_name_with_login' to show
1076   *                                                 the display name with user_login in parentheses.
1077   *                                                 Default 'display_name'.
1078   *     @type int|bool     $echo                    Whether to echo or return the drop-down. Accepts 1|true (echo)
1079   *                                                 or 0|false (return). Default 1|true.
1080   *     @type int          $selected                Which user ID should be selected. Default 0.
1081   *     @type bool         $include_selected        Whether to always include the selected user ID in the drop-
1082   *                                                 down. Default false.
1083   *     @type string       $name                    Name attribute of select element. Default 'user'.
1084   *     @type string       $id                      ID attribute of the select element. Default is the value of $name.
1085   *     @type string       $class                   Class attribute of the select element. Default empty.
1086   *     @type int          $blog_id                 ID of blog (Multisite only). Default is ID of the current blog.
1087   *     @type string       $who                     Which type of users to query. Accepts only an empty string or
1088   *                                                 'authors'. Default empty.
1089   *     @type string|array $role                    An array or a comma-separated list of role names that users must
1090   *                                                 match to be included in results. Note that this is an inclusive
1091   *                                                 list: users must match *each* role. Default empty.
1092   *     @type array        $role__in                An array of role names. Matched users must have at least one of
1093   *                                                 these roles. Default empty array.
1094   *     @type array        $role__not_in            An array of role names to exclude. Users matching one or more of
1095   *                                                 these roles will not be included in results. Default empty array.
1096   * }
1097   * @return string HTML dropdown list of users.
1098   */
1099  function wp_dropdown_users( $args = '' ) {
1100      $defaults = array(
1101          'show_option_all'         => '',
1102          'show_option_none'        => '',
1103          'hide_if_only_one_author' => '',
1104          'orderby'                 => 'display_name',
1105          'order'                   => 'ASC',
1106          'include'                 => '',
1107          'exclude'                 => '',
1108          'multi'                   => 0,
1109          'show'                    => 'display_name',
1110          'echo'                    => 1,
1111          'selected'                => 0,
1112          'name'                    => 'user',
1113          'class'                   => '',
1114          'id'                      => '',
1115          'blog_id'                 => get_current_blog_id(),
1116          'who'                     => '',
1117          'include_selected'        => false,
1118          'option_none_value'       => -1,
1119          'role'                    => '',
1120          'role__in'                => array(),
1121          'role__not_in'            => array(),
1122      );
1123  
1124      $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
1125  
1126      $parsed_args = wp_parse_args( $args, $defaults );
1127  
1128      $query_args = wp_array_slice_assoc( $parsed_args, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who', 'role', 'role__in', 'role__not_in' ) );
1129  
1130      $fields = array( 'ID', 'user_login' );
1131  
1132      $show = ! empty( $parsed_args['show'] ) ? $parsed_args['show'] : 'display_name';
1133      if ( 'display_name_with_login' === $show ) {
1134          $fields[] = 'display_name';
1135      } else {
1136          $fields[] = $show;
1137      }
1138  
1139      $query_args['fields'] = $fields;
1140  
1141      $show_option_all   = $parsed_args['show_option_all'];
1142      $show_option_none  = $parsed_args['show_option_none'];
1143      $option_none_value = $parsed_args['option_none_value'];
1144  
1145      /**
1146       * Filters the query arguments for the list of users in the dropdown.
1147       *
1148       * @since 4.4.0
1149       *
1150       * @param array $query_args  The query arguments for get_users().
1151       * @param array $parsed_args The arguments passed to wp_dropdown_users() combined with the defaults.
1152       */
1153      $query_args = apply_filters( 'wp_dropdown_users_args', $query_args, $parsed_args );
1154  
1155      $users = get_users( $query_args );
1156  
1157      $output = '';
1158      if ( ! empty( $users ) && ( empty( $parsed_args['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
1159          $name = esc_attr( $parsed_args['name'] );
1160          if ( $parsed_args['multi'] && ! $parsed_args['id'] ) {
1161              $id = '';
1162          } else {
1163              $id = $parsed_args['id'] ? " id='" . esc_attr( $parsed_args['id'] ) . "'" : " id='$name'";
1164          }
1165          $output = "<select name='{$name}'{$id} class='" . $parsed_args['class'] . "'>\n";
1166  
1167          if ( $show_option_all ) {
1168              $output .= "\t<option value='0'>$show_option_all</option>\n";
1169          }
1170  
1171          if ( $show_option_none ) {
1172              $_selected = selected( $option_none_value, $parsed_args['selected'], false );
1173              $output   .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
1174          }
1175  
1176          if ( $parsed_args['include_selected'] && ( $parsed_args['selected'] > 0 ) ) {
1177              $found_selected          = false;
1178              $parsed_args['selected'] = (int) $parsed_args['selected'];
1179              foreach ( (array) $users as $user ) {
1180                  $user->ID = (int) $user->ID;
1181                  if ( $user->ID === $parsed_args['selected'] ) {
1182                      $found_selected = true;
1183                  }
1184              }
1185  
1186              if ( ! $found_selected ) {
1187                  $users[] = get_userdata( $parsed_args['selected'] );
1188              }
1189          }
1190  
1191          foreach ( (array) $users as $user ) {
1192              if ( 'display_name_with_login' === $show ) {
1193                  /* translators: 1: User's display name, 2: User login. */
1194                  $display = sprintf( _x( '%1$s (%2$s)', 'user dropdown' ), $user->display_name, $user->user_login );
1195              } elseif ( ! empty( $user->$show ) ) {
1196                  $display = $user->$show;
1197              } else {
1198                  $display = '(' . $user->user_login . ')';
1199              }
1200  
1201              $_selected = selected( $user->ID, $parsed_args['selected'], false );
1202              $output   .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
1203          }
1204  
1205          $output .= '</select>';
1206      }
1207  
1208      /**
1209       * Filters the wp_dropdown_users() HTML output.
1210       *
1211       * @since 2.3.0
1212       *
1213       * @param string $output HTML output generated by wp_dropdown_users().
1214       */
1215      $html = apply_filters( 'wp_dropdown_users', $output );
1216  
1217      if ( $parsed_args['echo'] ) {
1218          echo $html;
1219      }
1220      return $html;
1221  }
1222  
1223  /**
1224   * Sanitize user field based on context.
1225   *
1226   * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
1227   * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
1228   * when calling filters.
1229   *
1230   * @since 2.3.0
1231   *
1232   * @param string $field   The user Object field name.
1233   * @param mixed  $value   The user Object value.
1234   * @param int    $user_id User ID.
1235   * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
1236   *                        'attribute' and 'js'.
1237   * @return mixed Sanitized value.
1238   */
1239  function sanitize_user_field( $field, $value, $user_id, $context ) {
1240      $int_fields = array( 'ID' );
1241      if ( in_array( $field, $int_fields ) ) {
1242          $value = (int) $value;
1243      }
1244  
1245      if ( 'raw' == $context ) {
1246          return $value;
1247      }
1248  
1249      if ( ! is_string( $value ) && ! is_numeric( $value ) ) {
1250          return $value;
1251      }
1252  
1253      $prefixed = false !== strpos( $field, 'user_' );
1254  
1255      if ( 'edit' == $context ) {
1256          if ( $prefixed ) {
1257  
1258              /** This filter is documented in wp-includes/post.php */
1259              $value = apply_filters( "edit_{$field}", $value, $user_id );
1260          } else {
1261  
1262              /**
1263               * Filters a user field value in the 'edit' context.
1264               *
1265               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1266               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1267               *
1268               * @since 2.9.0
1269               *
1270               * @param mixed $value   Value of the prefixed user field.
1271               * @param int   $user_id User ID.
1272               */
1273              $value = apply_filters( "edit_user_{$field}", $value, $user_id );
1274          }
1275  
1276          if ( 'description' == $field ) {
1277              $value = esc_html( $value ); // textarea_escaped?
1278          } else {
1279              $value = esc_attr( $value );
1280          }
1281      } elseif ( 'db' == $context ) {
1282          if ( $prefixed ) {
1283              /** This filter is documented in wp-includes/post.php */
1284              $value = apply_filters( "pre_{$field}", $value );
1285          } else {
1286  
1287              /**
1288               * Filters the value of a user field in the 'db' context.
1289               *
1290               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1291               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1292               *
1293               * @since 2.9.0
1294               *
1295               * @param mixed $value Value of the prefixed user field.
1296               */
1297              $value = apply_filters( "pre_user_{$field}", $value );
1298          }
1299      } else {
1300          // Use display filters by default.
1301          if ( $prefixed ) {
1302  
1303              /** This filter is documented in wp-includes/post.php */
1304              $value = apply_filters( "{$field}", $value, $user_id, $context );
1305          } else {
1306  
1307              /**
1308               * Filters the value of a user field in a standard context.
1309               *
1310               * The dynamic portion of the hook name, `$field`, refers to the prefixed user
1311               * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
1312               *
1313               * @since 2.9.0
1314               *
1315               * @param mixed  $value   The user object value to sanitize.
1316               * @param int    $user_id User ID.
1317               * @param string $context The context to filter within.
1318               */
1319              $value = apply_filters( "user_{$field}", $value, $user_id, $context );
1320          }
1321      }
1322  
1323      if ( 'user_url' == $field ) {
1324          $value = esc_url( $value );
1325      }
1326  
1327      if ( 'attribute' == $context ) {
1328          $value = esc_attr( $value );
1329      } elseif ( 'js' == $context ) {
1330          $value = esc_js( $value );
1331      }
1332      return $value;
1333  }
1334  
1335  /**
1336   * Update all user caches
1337   *
1338   * @since 3.0.0
1339   *
1340   * @param WP_User $user User object to be cached
1341   * @return bool|null Returns false on failure.
1342   */
1343  function update_user_caches( $user ) {
1344      if ( $user instanceof WP_User ) {
1345          if ( ! $user->exists() ) {
1346              return false;
1347          }
1348  
1349          $user = $user->data;
1350      }
1351  
1352      wp_cache_add( $user->ID, $user, 'users' );
1353      wp_cache_add( $user->user_login, $user->ID, 'userlogins' );
1354      wp_cache_add( $user->user_email, $user->ID, 'useremail' );
1355      wp_cache_add( $user->user_nicename, $user->ID, 'userslugs' );
1356  }
1357  
1358  /**
1359   * Clean all user caches
1360   *
1361   * @since 3.0.0
1362   * @since 4.4.0 'clean_user_cache' action was added.
1363   *
1364   * @param WP_User|int $user User object or ID to be cleaned from the cache
1365   */
1366  function clean_user_cache( $user ) {
1367      if ( is_numeric( $user ) ) {
1368          $user = new WP_User( $user );
1369      }
1370  
1371      if ( ! $user->exists() ) {
1372          return;
1373      }
1374  
1375      wp_cache_delete( $user->ID, 'users' );
1376      wp_cache_delete( $user->user_login, 'userlogins' );
1377      wp_cache_delete( $user->user_email, 'useremail' );
1378      wp_cache_delete( $user->user_nicename, 'userslugs' );
1379  
1380      /**
1381       * Fires immediately after the given user's cache is cleaned.
1382       *
1383       * @since 4.4.0
1384       *
1385       * @param int     $user_id User ID.
1386       * @param WP_User $user    User object.
1387       */
1388      do_action( 'clean_user_cache', $user->ID, $user );
1389  }
1390  
1391  /**
1392   * Determines whether the given username exists.
1393   *
1394   * For more information on this and similar theme functions, check out
1395   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
1396   * Conditional Tags} article in the Theme Developer Handbook.
1397   *
1398   * @since 2.0.0
1399   *
1400   * @param string $username Username.
1401   * @return int|false The user's ID on success, and false on failure.
1402   */
1403  function username_exists( $username ) {
1404      $user = get_user_by( 'login', $username );
1405      if ( $user ) {
1406          $user_id = $user->ID;
1407      } else {
1408          $user_id = false;
1409      }
1410  
1411      /**
1412       * Filters whether the given username exists or not.
1413       *
1414       * @since 4.9.0
1415       *
1416       * @param int|false $user_id  The user's ID on success, and false on failure.
1417       * @param string    $username Username to check.
1418       */
1419      return apply_filters( 'username_exists', $user_id, $username );
1420  }
1421  
1422  /**
1423   * Determines whether the given email exists.
1424   *
1425   * For more information on this and similar theme functions, check out
1426   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
1427   * Conditional Tags} article in the Theme Developer Handbook.
1428   *
1429   * @since 2.1.0
1430   *
1431   * @param string $email Email.
1432   * @return int|false The user's ID on success, and false on failure.
1433   */
1434  function email_exists( $email ) {
1435      $user = get_user_by( 'email', $email );
1436      if ( $user ) {
1437          return $user->ID;
1438      }
1439      return false;
1440  }
1441  
1442  /**
1443   * Checks whether a username is valid.
1444   *
1445   * @since 2.0.1
1446   * @since 4.4.0 Empty sanitized usernames are now considered invalid
1447   *
1448   * @param string $username Username.
1449   * @return bool Whether username given is valid
1450   */
1451  function validate_username( $username ) {
1452      $sanitized = sanitize_user( $username, true );
1453      $valid     = ( $sanitized == $username && ! empty( $sanitized ) );
1454  
1455      /**
1456       * Filters whether the provided username is valid or not.
1457       *
1458       * @since 2.0.1
1459       *
1460       * @param bool   $valid    Whether given username is valid.
1461       * @param string $username Username to check.
1462       */
1463      return apply_filters( 'validate_username', $valid, $username );
1464  }
1465  
1466  /**
1467   * Insert a user into the database.
1468   *
1469   * Most of the `$userdata` array fields have filters associated with the values. Exceptions are
1470   * 'ID', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl',
1471   * 'user_registered', 'user_activation_key', 'spam', and 'role'. The filters have the prefix
1472   * 'pre_user_' followed by the field name. An example using 'description' would have the filter
1473   * called 'pre_user_description' that can be hooked into.
1474   *
1475   * @since 2.0.0
1476   * @since 3.6.0 The `aim`, `jabber`, and `yim` fields were removed as default user contact
1477   *              methods for new installations. See wp_get_user_contact_methods().
1478   * @since 4.7.0 The user's locale can be passed to `$userdata`.
1479   * @since 5.3.0 The `user_activation_key` field can be passed to `$userdata`.
1480   * @since 5.3.0 The `spam` field can be passed to `$userdata` (Multisite only).
1481   *
1482   * @global wpdb $wpdb WordPress database abstraction object.
1483   *
1484   * @param array|object|WP_User $userdata {
1485   *     An array, object, or WP_User object of user data arguments.
1486   *
1487   *     @type int    $ID                   User ID. If supplied, the user will be updated.
1488   *     @type string $user_pass            The plain-text user password.
1489   *     @type string $user_login           The user's login username.
1490   *     @type string $user_nicename        The URL-friendly user name.
1491   *     @type string $user_url             The user URL.
1492   *     @type string $user_email           The user email address.
1493   *     @type string $display_name         The user's display name.
1494   *                                        Default is the user's username.
1495   *     @type string $nickname             The user's nickname.
1496   *                                        Default is the user's username.
1497   *     @type string $first_name           The user's first name. For new users, will be used
1498   *                                        to build the first part of the user's display name
1499   *                                        if `$display_name` is not specified.
1500   *     @type string $last_name            The user's last name. For new users, will be used
1501   *                                        to build the second part of the user's display name
1502   *                                        if `$display_name` is not specified.
1503   *     @type string $description          The user's biographical description.
1504   *     @type string $rich_editing         Whether to enable the rich-editor for the user.
1505   *                                        Accepts 'true' or 'false' as a string literal,
1506   *                                        not boolean. Default 'true'.
1507   *     @type string $syntax_highlighting  Whether to enable the rich code editor for the user.
1508   *                                        Accepts 'true' or 'false' as a string literal,
1509   *                                        not boolean. Default 'true'.
1510   *     @type string $comment_shortcuts    Whether to enable comment moderation keyboard
1511   *                                        shortcuts for the user. Accepts 'true' or 'false'
1512   *                                        as a string literal, not boolean. Default 'false'.
1513   *     @type string $admin_color          Admin color scheme for the user. Default 'fresh'.
1514   *     @type bool   $use_ssl              Whether the user should always access the admin over
1515   *                                        https. Default false.
1516   *     @type string $user_registered      Date the user registered. Format is 'Y-m-d H:i:s'.
1517   *     @type string $user_activation_key  Password reset key. Default empty.
1518   *     @type bool   $spam                 Multisite only. Whether the user is marked as spam.
1519   *                                        Default false.
1520   *     @type string $show_admin_bar_front Whether to display the Admin Bar for the user
1521   *                                        on the site's front end. Accepts 'true' or 'false'
1522   *                                        as a string literal, not boolean. Default 'true'.
1523   *     @type string $role                 User's role.
1524   *     @type string $locale               User's locale. Default empty.
1525   * }
1526   * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
1527   *                      be created.
1528   */
1529  function wp_insert_user( $userdata ) {
1530      global $wpdb;
1531  
1532      if ( $userdata instanceof stdClass ) {
1533          $userdata = get_object_vars( $userdata );
1534      } elseif ( $userdata instanceof WP_User ) {
1535          $userdata = $userdata->to_array();
1536      }
1537  
1538      // Are we updating or creating?
1539      if ( ! empty( $userdata['ID'] ) ) {
1540          $ID            = (int) $userdata['ID'];
1541          $update        = true;
1542          $old_user_data = get_userdata( $ID );
1543  
1544          if ( ! $old_user_data ) {
1545              return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
1546          }
1547  
1548          // hashed in wp_update_user(), plaintext if called directly.
1549          $user_pass = ! empty( $userdata['user_pass'] ) ? $userdata['user_pass'] : $old_user_data->user_pass;
1550      } else {
1551          $update = false;
1552          // Hash the password.
1553          $user_pass = wp_hash_password( $userdata['user_pass'] );
1554      }
1555  
1556      $sanitized_user_login = sanitize_user( $userdata['user_login'], true );
1557  
1558      /**
1559       * Filters a username after it has been sanitized.
1560       *
1561       * This filter is called before the user is created or updated.
1562       *
1563       * @since 2.0.3
1564       *
1565       * @param string $sanitized_user_login Username after it has been sanitized.
1566       */
1567      $pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
1568  
1569      // Remove any non-printable chars from the login string to see if we have ended up with an empty username.
1570      $user_login = trim( $pre_user_login );
1571  
1572      // user_login must be between 0 and 60 characters.
1573      if ( empty( $user_login ) ) {
1574          return new WP_Error( 'empty_user_login', __( 'Cannot create a user with an empty login name.' ) );
1575      } elseif ( mb_strlen( $user_login ) > 60 ) {
1576          return new WP_Error( 'user_login_too_long', __( 'Username may not be longer than 60 characters.' ) );
1577      }
1578  
1579      if ( ! $update && username_exists( $user_login ) ) {
1580          return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
1581      }
1582  
1583      /**
1584       * Filters the list of blacklisted usernames.
1585       *
1586       * @since 4.4.0
1587       *
1588       * @param array $usernames Array of blacklisted usernames.
1589       */
1590      $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
1591  
1592      if ( in_array( strtolower( $user_login ), array_map( 'strtolower', $illegal_logins ), true ) ) {
1593          return new WP_Error( 'invalid_username', __( 'Sorry, that username is not allowed.' ) );
1594      }
1595  
1596      /*
1597       * If a nicename is provided, remove unsafe user characters before using it.
1598       * Otherwise build a nicename from the user_login.
1599       */
1600      if ( ! empty( $userdata['user_nicename'] ) ) {
1601          $user_nicename = sanitize_user( $userdata['user_nicename'], true );
1602          if ( mb_strlen( $user_nicename ) > 50 ) {
1603              return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
1604          }
1605      } else {
1606          $user_nicename = mb_substr( $user_login, 0, 50 );
1607      }
1608  
1609      $user_nicename = sanitize_title( $user_nicename );
1610  
1611      /**
1612       * Filters a user's nicename before the user is created or updated.
1613       *
1614       * @since 2.0.3
1615       *
1616       * @param string $user_nicename The user's nicename.
1617       */
1618      $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
1619  
1620      $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 ) );
1621  
1622      if ( $user_nicename_check ) {
1623          $suffix = 2;
1624          while ( $user_nicename_check ) {
1625              // user_nicename allows 50 chars. Subtract one for a hyphen, plus the length of the suffix.
1626              $base_length         = 49 - mb_strlen( $suffix );
1627              $alt_user_nicename   = mb_substr( $user_nicename, 0, $base_length ) . "-$suffix";
1628              $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 ) );
1629              $suffix++;
1630          }
1631          $user_nicename = $alt_user_nicename;
1632      }
1633  
1634      $raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];
1635  
1636      /**
1637       * Filters a user's email before the user is created or updated.
1638       *
1639       * @since 2.0.3
1640       *
1641       * @param string $raw_user_email The user's email.
1642       */
1643      $user_email = apply_filters( 'pre_user_email', $raw_user_email );
1644  
1645      /*
1646       * If there is no update, just check for `email_exists`. If there is an update,
1647       * check if current email and new email are the same, or not, and check `email_exists`
1648       * accordingly.
1649       */
1650      if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) )
1651          && ! defined( 'WP_IMPORTING' )
1652          && email_exists( $user_email )
1653      ) {
1654          return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
1655      }
1656  
1657      $raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
1658  
1659      /**
1660       * Filters a user's URL before the user is created or updated.
1661       *
1662       * @since 2.0.3
1663       *
1664       * @param string $raw_user_url The user's URL.
1665       */
1666      $user_url = apply_filters( 'pre_user_url', $raw_user_url );
1667  
1668      $user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];
1669  
1670      $user_activation_key = empty( $userdata['user_activation_key'] ) ? '' : $userdata['user_activation_key'];
1671  
1672      if ( ! empty( $userdata['spam'] ) && ! is_multisite() ) {
1673          return new WP_Error( 'no_spam', __( 'Sorry, marking a user as spam is only supported on Multisite.' ) );
1674      }
1675  
1676      $spam = empty( $userdata['spam'] ) ? 0 : (bool) $userdata['spam'];
1677  
1678      // Store values to save in user meta.
1679      $meta = array();
1680  
1681      $nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];
1682  
1683      /**
1684       * Filters a user's nickname before the user is created or updated.
1685       *
1686       * @since 2.0.3
1687       *
1688       * @param string $nickname The user's nickname.
1689       */
1690      $meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );
1691  
1692      $first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];
1693  
1694      /**
1695       * Filters a user's first name before the user is created or updated.
1696       *
1697       * @since 2.0.3
1698       *
1699       * @param string $first_name The user's first name.
1700       */
1701      $meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );
1702  
1703      $last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];
1704  
1705      /**
1706       * Filters a user's last name before the user is created or updated.
1707       *
1708       * @since 2.0.3
1709       *
1710       * @param string $last_name The user's last name.
1711       */
1712      $meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );
1713  
1714      if ( empty( $userdata['display_name'] ) ) {
1715          if ( $update ) {
1716              $display_name = $user_login;
1717          } elseif ( $meta['first_name'] && $meta['last_name'] ) {
1718              /* translators: 1: User's first name, 2: Last name. */
1719              $display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $meta['first_name'], $meta['last_name'] );
1720          } elseif ( $meta['first_name'] ) {
1721              $display_name = $meta['first_name'];
1722          } elseif ( $meta['last_name'] ) {
1723              $display_name = $meta['last_name'];
1724          } else {
1725              $display_name = $user_login;
1726          }
1727      } else {
1728          $display_name = $userdata['display_name'];
1729      }
1730  
1731      /**
1732       * Filters a user's display name before the user is created or updated.
1733       *
1734       * @since 2.0.3
1735       *
1736       * @param string $display_name The user's display name.
1737       */
1738      $display_name = apply_filters( 'pre_user_display_name', $display_name );
1739  
1740      $description = empty( $userdata['description'] ) ? '' : $userdata['description'];
1741  
1742      /**
1743       * Filters a user's description before the user is created or updated.
1744       *
1745       * @since 2.0.3
1746       *
1747       * @param string $description The user's description.
1748       */
1749      $meta['description'] = apply_filters( 'pre_user_description', $description );
1750  
1751      $meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];
1752  
1753      $meta['syntax_highlighting'] = empty( $userdata['syntax_highlighting'] ) ? 'true' : $userdata['syntax_highlighting'];
1754  
1755      $meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';
1756  
1757      $admin_color         = empty( $userdata['admin_color'] ) ? 'fresh' : $userdata['admin_color'];
1758      $meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );
1759  
1760      $meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? 0 : (bool) $userdata['use_ssl'];
1761  
1762      $meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];
1763  
1764      $meta['locale'] = isset( $userdata['locale'] ) ? $userdata['locale'] : '';
1765  
1766      $compacted = compact( 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'display_name' );
1767      $data      = wp_unslash( $compacted );
1768  
1769      if ( ! $update ) {
1770          $data = $data + compact( 'user_login' );
1771      }
1772  
1773      if ( is_multisite() ) {
1774          $data = $data + compact( 'spam' );
1775      }
1776  
1777      /**
1778       * Filters user data before the record is created or updated.
1779       *
1780       * It only includes data in the wp_users table wp_user, not any user metadata.
1781       *
1782       * @since 4.9.0
1783       *
1784       * @param array    $data {
1785       *     Values and keys for the user.
1786       *
1787       *     @type string $user_login      The user's login. Only included if $update == false
1788       *     @type string $user_pass       The user's password.
1789       *     @type string $user_email      The user's email.
1790       *     @type string $user_url        The user's url.
1791       *     @type string $user_nicename   The user's nice name. Defaults to a URL-safe version of user's login
1792       *     @type string $display_name    The user's display name.
1793       *     @type string $user_registered MySQL timestamp describing the moment when the user registered. Defaults to
1794       *                                   the current UTC timestamp.
1795       * }
1796       * @param bool     $update Whether the user is being updated rather than created.
1797       * @param int|null $id     ID of the user to be updated, or NULL if the user is being created.
1798       */
1799      $data = apply_filters( 'wp_pre_insert_user_data', $data, $update, $update ? (int) $ID : null );
1800  
1801      if ( empty( $data ) || ! is_array( $data ) ) {
1802          return new WP_Error( 'empty_data', __( 'Not enough data to create this user.' ) );
1803      }
1804  
1805      if ( $update ) {
1806          if ( $user_email !== $old_user_data->user_email || $user_pass !== $old_user_data->user_pass ) {
1807              $data['user_activation_key'] = '';
1808          }
1809          $wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
1810          $user_id = (int) $ID;
1811      } else {
1812          $wpdb->insert( $wpdb->users, $data );
1813          $user_id = (int) $wpdb->insert_id;
1814      }
1815  
1816      $user = new WP_User( $user_id );
1817  
1818      /**
1819       * Filters a user's meta values and keys immediately after the user is created or updated
1820       * and before any user meta is inserted or updated.
1821       *
1822       * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`.
1823       *
1824       * @since 4.4.0
1825       *
1826       * @param array $meta {
1827       *     Default meta values and keys for the user.
1828       *
1829       *     @type string   $nickname             The user's nickname. Default is the user's username.
1830       *     @type string   $first_name           The user's first name.
1831       *     @type string   $last_name            The user's last name.
1832       *     @type string   $description          The user's description.
1833       *     @type string   $rich_editing         Whether to enable the rich-editor for the user. Default 'true'.
1834       *     @type string   $syntax_highlighting  Whether to enable the rich code editor for the user. Default 'true'.
1835       *     @type string   $comment_shortcuts    Whether to enable keyboard shortcuts for the user. Default 'false'.
1836       *     @type string   $admin_color          The color scheme for a user's admin screen. Default 'fresh'.
1837       *     @type int|bool $use_ssl              Whether to force SSL on the user's admin area. 0|false if SSL
1838       *                                          is not forced.
1839       *     @type string   $show_admin_bar_front Whether to show the admin bar on the front end for the user.
1840       *                                          Default 'true'.
1841       *     @type string   $locale               User's locale. Default empty.
1842       * }
1843       * @param WP_User $user   User object.
1844       * @param bool    $update Whether the user is being updated rather than created.
1845       */
1846      $meta = apply_filters( 'insert_user_meta', $meta, $user, $update );
1847  
1848      // Update user meta.
1849      foreach ( $meta as $key => $value ) {
1850          update_user_meta( $user_id, $key, $value );
1851      }
1852  
1853      foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
1854          if ( isset( $userdata[ $key ] ) ) {
1855              update_user_meta( $user_id, $key, $userdata[ $key ] );
1856          }
1857      }
1858  
1859      if ( isset( $userdata['role'] ) ) {
1860          $user->set_role( $userdata['role'] );
1861      } elseif ( ! $update ) {
1862          $user->set_role( get_option( 'default_role' ) );
1863      }
1864  
1865      clean_user_cache( $user_id );
1866  
1867      if ( $update ) {
1868          /**
1869           * Fires immediately after an existing user is updated.
1870           *
1871           * @since 2.0.0
1872           *
1873           * @param int     $user_id       User ID.
1874           * @param WP_User $old_user_data Object containing user's data prior to update.
1875           */
1876          do_action( 'profile_update', $user_id, $old_user_data );
1877  
1878          if ( isset( $userdata['spam'] ) && $userdata['spam'] != $old_user_data->spam ) {
1879              if ( 1 == $userdata['spam'] ) {
1880                  /**
1881                   * Fires after the user is marked as a SPAM user.
1882                   *
1883                   * @since 3.0.0
1884                   *
1885                   * @param int $user_id ID of the user marked as SPAM.
1886                   */
1887                  do_action( 'make_spam_user', $user_id );
1888              } else {
1889                  /**
1890                   * Fires after the user is marked as a HAM user. Opposite of SPAM.
1891                   *
1892                   * @since 3.0.0
1893                   *
1894                   * @param int $user_id ID of the user marked as HAM.
1895                   */
1896                  do_action( 'make_ham_user', $user_id );
1897              }
1898          }
1899      } else {
1900          /**
1901           * Fires immediately after a new user is registered.
1902           *
1903           * @since 1.5.0
1904           *
1905           * @param int $user_id User ID.
1906           */
1907          do_action( 'user_register', $user_id );
1908      }
1909  
1910      return $user_id;
1911  }
1912  
1913  /**
1914   * Update a user in the database.
1915   *
1916   * It is possible to update a user's password by specifying the 'user_pass'
1917   * value in the $userdata parameter array.
1918   *
1919   * If current user's password is being updated, then the cookies will be
1920   * cleared.
1921   *
1922   * @since 2.0.0
1923   *
1924   * @see wp_insert_user() For what fields can be set in $userdata.
1925   *
1926   * @param array|object|WP_User $userdata An array of user data or a user object of type stdClass or WP_User.
1927   * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
1928   */
1929  function wp_update_user( $userdata ) {
1930      if ( $userdata instanceof stdClass ) {
1931          $userdata = get_object_vars( $userdata );
1932      } elseif ( $userdata instanceof WP_User ) {
1933          $userdata = $userdata->to_array();
1934      }
1935  
1936      $ID = isset( $userdata['ID'] ) ? (int) $userdata['ID'] : 0;
1937      if ( ! $ID ) {
1938          return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
1939      }
1940  
1941      // First, get all of the original fields.
1942      $user_obj = get_userdata( $ID );
1943      if ( ! $user_obj ) {
1944          return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
1945      }
1946  
1947      $user = $user_obj->to_array();
1948  
1949      // Add additional custom fields.
1950      foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
1951          $user[ $key ] = get_user_meta( $ID, $key, true );
1952      }
1953  
1954      // Escape data pulled from DB.
1955      $user = add_magic_quotes( $user );
1956  
1957      if ( ! empty( $userdata['user_pass'] ) && $userdata['user_pass'] !== $user_obj->user_pass ) {
1958          // If password is changing, hash it now.
1959          $plaintext_pass        = $userdata['user_pass'];
1960          $userdata['user_pass'] = wp_hash_password( $userdata['user_pass'] );
1961  
1962          /**
1963           * Filters whether to send the password change email.
1964           *
1965           * @since 4.3.0
1966           *
1967           * @see wp_insert_user() For `$user` and `$userdata` fields.
1968           *
1969           * @param bool  $send     Whether to send the email.
1970           * @param array $user     The original user array.
1971           * @param array $userdata The updated user array.
1972           */
1973          $send_password_change_email = apply_filters( 'send_password_change_email', true, $user, $userdata );
1974      }
1975  
1976      if ( isset( $userdata['user_email'] ) && $user['user_email'] !== $userdata['user_email'] ) {
1977          /**
1978           * Filters whether to send the email change email.
1979           *
1980           * @since 4.3.0
1981           *
1982           * @see wp_insert_user() For `$user` and `$userdata` fields.
1983           *
1984           * @param bool  $send     Whether to send the email.
1985           * @param array $user     The original user array.
1986           * @param array $userdata The updated user array.
1987           */
1988          $send_email_change_email = apply_filters( 'send_email_change_email', true, $user, $userdata );
1989      }
1990  
1991      clean_user_cache( $user_obj );
1992  
1993      // Merge old and new fields with new fields overwriting old ones.
1994      $userdata = array_merge( $user, $userdata );
1995      $user_id  = wp_insert_user( $userdata );
1996  
1997      if ( ! is_wp_error( $user_id ) ) {
1998  
1999          $blog_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
2000  
2001          $switched_locale = false;
2002          if ( ! empty( $send_password_change_email ) || ! empty( $send_email_change_email ) ) {
2003              $switched_locale = switch_to_locale( get_user_locale( $user_id ) );
2004          }
2005  
2006          if ( ! empty( $send_password_change_email ) ) {
2007              /* translators: Do not translate USERNAME, ADMIN_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
2008              $pass_change_text = __(
2009                  'Hi ###USERNAME###,
2010  
2011  This notice confirms that your password was changed on ###SITENAME###.
2012  
2013  If you did not change your password, please contact the Site Administrator at
2014  ###ADMIN_EMAIL###
2015  
2016  This email has been sent to ###EMAIL###
2017  
2018  Regards,
2019  All at ###SITENAME###
2020  ###SITEURL###'
2021              );
2022  
2023              $pass_change_email = array(
2024                  'to'      => $user['user_email'],
2025                  /* translators: Password change notification email subject. %s: Site title. */
2026                  'subject' => __( '[%s] Password Changed' ),
2027                  'message' => $pass_change_text,
2028                  'headers' => '',
2029              );
2030  
2031              /**
2032               * Filters the contents of the email sent when the user's password is changed.
2033               *
2034               * @since 4.3.0
2035               *
2036               * @param array $pass_change_email {
2037               *            Used to build wp_mail().
2038               *            @type string $to      The intended recipients. Add emails in a comma separated string.
2039               *            @type string $subject The subject of the email.
2040               *            @type string $message The content of the email.
2041               *                The following strings have a special meaning and will get replaced dynamically:
2042               *                - ###USERNAME###    The current user's username.
2043               *                - ###ADMIN_EMAIL### The admin email in case this was unexpected.
2044               *                - ###EMAIL###       The user's email address.
2045               *                - ###SITENAME###    The name of the site.
2046               *                - ###SITEURL###     The URL to the site.
2047               *            @type string $headers Headers. Add headers in a newline (\r\n) separated string.
2048               *        }
2049               * @param array $user     The original user array.
2050               * @param array $userdata The updated user array.
2051               */
2052              $pass_change_email = apply_filters( 'password_change_email', $pass_change_email, $user, $userdata );
2053  
2054              $pass_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $pass_change_email['message'] );
2055              $pass_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $pass_change_email['message'] );
2056              $pass_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $pass_change_email['message'] );
2057              $pass_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $pass_change_email['message'] );
2058              $pass_change_email['message'] = str_replace( '###SITEURL###', home_url(), $pass_change_email['message'] );
2059  
2060              wp_mail( $pass_change_email['to'], sprintf( $pass_change_email['subject'], $blog_name ), $pass_change_email['message'], $pass_change_email['headers'] );
2061          }
2062  
2063          if ( ! empty( $send_email_change_email ) ) {
2064              /* translators: Do not translate USERNAME, ADMIN_EMAIL, NEW_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
2065              $email_change_text = __(
2066                  'Hi ###USERNAME###,
2067  
2068  This notice confirms that your email address on ###SITENAME### was changed to ###NEW_EMAIL###.
2069  
2070  If you did not change your email, please contact the Site Administrator at
2071  ###ADMIN_EMAIL###
2072  
2073  This email has been sent to ###EMAIL###
2074  
2075  Regards,
2076  All at ###SITENAME###
2077  ###SITEURL###'
2078              );
2079  
2080              $email_change_email = array(
2081                  'to'      => $user['user_email'],
2082                  /* translators: Email change notification email subject. %s: Site title. */
2083                  'subject' => __( '[%s] Email Changed' ),
2084                  'message' => $email_change_text,
2085                  'headers' => '',
2086              );
2087  
2088              /**
2089               * Filters the contents of the email sent when the user's email is changed.
2090               *
2091               * @since 4.3.0
2092               *
2093               * @param array $email_change_email {
2094               *            Used to build wp_mail().
2095               *            @type string $to      The intended recipients.
2096               *            @type string $subject The subject of the email.
2097               *            @type string $message The content of the email.
2098               *                The following strings have a special meaning and will get replaced dynamically:
2099               *                - ###USERNAME###    The current user's username.
2100               *                - ###ADMIN_EMAIL### The admin email in case this was unexpected.
2101               *                - ###NEW_EMAIL###   The new email address.
2102               *                - ###EMAIL###       The old email address.
2103               *                - ###SITENAME###    The name of the site.
2104               *                - ###SITEURL###     The URL to the site.
2105               *            @type string $headers Headers.
2106               *        }
2107               * @param array $user The original user array.
2108               * @param array $userdata The updated user array.
2109               */
2110              $email_change_email = apply_filters( 'email_change_email', $email_change_email, $user, $userdata );
2111  
2112              $email_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $email_change_email['message'] );
2113              $email_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $email_change_email['message'] );
2114              $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $userdata['user_email'], $email_change_email['message'] );
2115              $email_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $email_change_email['message'] );
2116              $email_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $email_change_email['message'] );
2117              $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
2118  
2119              wp_mail( $email_change_email['to'], sprintf( $email_change_email['subject'], $blog_name ), $email_change_email['message'], $email_change_email['headers'] );
2120          }
2121  
2122          if ( $switched_locale ) {
2123              restore_previous_locale();
2124          }
2125      }
2126  
2127      // Update the cookies if the password changed.
2128      $current_user = wp_get_current_user();
2129      if ( $current_user->ID == $ID ) {
2130          if ( isset( $plaintext_pass ) ) {
2131              wp_clear_auth_cookie();
2132  
2133              // Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
2134              // If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
2135              $logged_in_cookie = wp_parse_auth_cookie( '', 'logged_in' );
2136              /** This filter is documented in wp-includes/pluggable.php */
2137              $default_cookie_life = apply_filters( 'auth_cookie_expiration', ( 2 * DAY_IN_SECONDS ), $ID, false );
2138              $remember            = false;
2139              if ( false !== $logged_in_cookie && ( $logged_in_cookie['expiration'] - time() ) > $default_cookie_life ) {
2140                  $remember = true;
2141              }
2142  
2143              wp_set_auth_cookie( $ID, $remember );
2144          }
2145      }
2146  
2147      return $user_id;
2148  }
2149  
2150  /**
2151   * A simpler way of inserting a user into the database.
2152   *
2153   * Creates a new user with just the username, password, and email. For more
2154   * complex user creation use wp_insert_user() to specify more information.
2155   *
2156   * @since 2.0.0
2157   * @see wp_insert_user() More complete way to create a new user
2158   *
2159   * @param string $username The user's username.
2160   * @param string $password The user's password.
2161   * @param string $email    Optional. The user's email. Default empty.
2162   * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
2163   *                      be created.
2164   */
2165  function wp_create_user( $username, $password, $email = '' ) {
2166      $user_login = wp_slash( $username );
2167      $user_email = wp_slash( $email );
2168      $user_pass  = $password;
2169  
2170      $userdata = compact( 'user_login', 'user_email', 'user_pass' );
2171      return wp_insert_user( $userdata );
2172  }
2173  
2174  /**
2175   * Returns a list of meta keys to be (maybe) populated in wp_update_user().
2176   *
2177   * The list of keys returned via this function are dependent on the presence
2178   * of those keys in the user meta data to be set.
2179   *
2180   * @since 3.3.0
2181   * @access private
2182   *
2183   * @param WP_User $user WP_User instance.
2184   * @return string[] List of user keys to be populated in wp_update_user().
2185   */
2186  function _get_additional_user_keys( $user ) {
2187      $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front', 'locale' );
2188      return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
2189  }
2190  
2191  /**
2192   * Set up the user contact methods.
2193   *
2194   * Default contact methods were removed in 3.6. A filter dictates contact methods.
2195   *
2196   * @since 3.7.0
2197   *
2198   * @param WP_User $user Optional. WP_User object.
2199   * @return string[] Array of contact method labels keyed by contact method.
2200   */
2201  function wp_get_user_contact_methods( $user = null ) {
2202      $methods = array();
2203      if ( get_site_option( 'initial_db_version' ) < 23588 ) {
2204          $methods = array(
2205              'aim'    => __( 'AIM' ),
2206              'yim'    => __( 'Yahoo IM' ),
2207              'jabber' => __( 'Jabber / Google Talk' ),
2208          );
2209      }
2210  
2211      /**
2212       * Filters the user contact methods.
2213       *
2214       * @since 2.9.0
2215       *
2216       * @param string[] $methods Array of contact method labels keyed by contact method.
2217       * @param WP_User  $user    WP_User object.
2218       */
2219      return apply_filters( 'user_contactmethods', $methods, $user );
2220  }
2221  
2222  /**
2223   * The old private function for setting up user contact methods.
2224   *
2225   * Use wp_get_user_contact_methods() instead.
2226   *
2227   * @since 2.9.0
2228   * @access private
2229   *
2230   * @param WP_User $user Optional. WP_User object. Default null.
2231   * @return string[] Array of contact method labels keyed by contact method.
2232   */
2233  function _wp_get_user_contactmethods( $user = null ) {
2234      return wp_get_user_contact_methods( $user );
2235  }
2236  
2237  /**
2238   * Gets the text suggesting how to create strong passwords.
2239   *
2240   * @since 4.1.0
2241   *
2242   * @return string The password hint text.
2243   */
2244  function wp_get_password_hint() {
2245      $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; ).' );
2246  
2247      /**
2248       * Filters the text describing the site's password complexity policy.
2249       *
2250       * @since 4.1.0
2251       *
2252       * @param string $hint The password hint text.
2253       */
2254      return apply_filters( 'password_hint', $hint );
2255  }
2256  
2257  /**
2258   * Creates, stores, then returns a password reset key for user.
2259   *
2260   * @since 4.4.0
2261   *
2262   * @global PasswordHash $wp_hasher Portable PHP password hashing framework.
2263   *
2264   * @param WP_User $user User to retrieve password reset key for.
2265   *
2266   * @return string|WP_Error Password reset key on success. WP_Error on error.
2267   */
2268  function get_password_reset_key( $user ) {
2269      global $wp_hasher;
2270  
2271      if ( ! ( $user instanceof WP_User ) ) {
2272          return new WP_Error( 'invalidcombo', __( '<strong>Error</strong>: There is no account with that username or email address.' ) );
2273      }
2274  
2275      /**
2276       * Fires before a new password is retrieved.
2277       *
2278       * Use the {@see 'retrieve_password'} hook instead.
2279       *
2280       * @since 1.5.0
2281       * @deprecated 1.5.1 Misspelled. Use {@see 'retrieve_password'} hook instead.
2282       *
2283       * @param string $user_login The user login name.
2284       */
2285      do_action_deprecated( 'retreive_password', array( $user->user_login ), '1.5.1', 'retrieve_password' );
2286  
2287      /**
2288       * Fires before a new password is retrieved.
2289       *
2290       * @since 1.5.1
2291       *
2292       * @param string $user_login The user login name.
2293       */
2294      do_action( 'retrieve_password', $user->user_login );
2295  
2296      $allow = true;
2297      if ( is_multisite() && is_user_spammy( $user ) ) {
2298          $allow = false;
2299      }
2300  
2301      /**
2302       * Filters whether to allow a password to be reset.
2303       *
2304       * @since 2.7.0
2305       *
2306       * @param bool $allow         Whether to allow the password to be reset. Default true.
2307       * @param int  $user_data->ID The ID of the user attempting to reset a password.
2308       */
2309      $allow = apply_filters( 'allow_password_reset', $allow, $user->ID );
2310  
2311      if ( ! $allow ) {
2312          return new WP_Error( 'no_password_reset', __( 'Password reset is not allowed for this user' ) );
2313      } elseif ( is_wp_error( $allow ) ) {
2314          return $allow;
2315      }
2316  
2317      // Generate something random for a password reset key.
2318      $key = wp_generate_password( 20, false );
2319  
2320      /**
2321       * Fires when a password reset key is generated.
2322       *
2323       * @since 2.5.0
2324       *
2325       * @param string $user_login The username for the user.
2326       * @param string $key        The generated password reset key.
2327       */
2328      do_action( 'retrieve_password_key', $user->user_login, $key );
2329  
2330      // Now insert the key, hashed, into the DB.
2331      if ( empty( $wp_hasher ) ) {
2332          require_once  ABSPATH . WPINC . '/class-phpass.php';
2333          $wp_hasher = new PasswordHash( 8, true );
2334      }
2335  
2336      $hashed = time() . ':' . $wp_hasher->HashPassword( $key );
2337  
2338      $key_saved = wp_update_user(
2339          array(
2340              'ID'                  => $user->ID,
2341              'user_activation_key' => $hashed,
2342          )
2343      );
2344  
2345      if ( is_wp_error( $key_saved ) ) {
2346          return $key_saved;
2347      }
2348  
2349      return $key;
2350  }
2351  
2352  /**
2353   * Retrieves a user row based on password reset key and login
2354   *
2355   * A key is considered 'expired' if it exactly matches the value of the
2356   * user_activation_key field, rather than being matched after going through the
2357   * hashing process. This field is now hashed; old values are no longer accepted
2358   * but have a different WP_Error code so good user feedback can be provided.
2359   *
2360   * @since 3.1.0
2361   *
2362   * @global wpdb         $wpdb      WordPress database object for queries.
2363   * @global PasswordHash $wp_hasher Portable PHP password hashing framework instance.
2364   *
2365   * @param string $key       Hash to validate sending user's password.
2366   * @param string $login     The user login.
2367   * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
2368   */
2369  function check_password_reset_key( $key, $login ) {
2370      global $wpdb, $wp_hasher;
2371  
2372      $key = preg_replace( '/[^a-z0-9]/i', '', $key );
2373  
2374      if ( empty( $key ) || ! is_string( $key ) ) {
2375          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
2376      }
2377  
2378      if ( empty( $login ) || ! is_string( $login ) ) {
2379          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
2380      }
2381  
2382      $user = get_user_by( 'login', $login );
2383  
2384      if ( ! $user ) {
2385          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
2386      }
2387  
2388      if ( empty( $wp_hasher ) ) {
2389          require_once  ABSPATH . WPINC . '/class-phpass.php';
2390          $wp_hasher = new PasswordHash( 8, true );
2391      }
2392  
2393      /**
2394       * Filters the expiration time of password reset keys.
2395       *
2396       * @since 4.3.0
2397       *
2398       * @param int $expiration The expiration time in seconds.
2399       */
2400      $expiration_duration = apply_filters( 'password_reset_expiration', DAY_IN_SECONDS );
2401  
2402      if ( false !== strpos( $user->user_activation_key, ':' ) ) {
2403          list( $pass_request_time, $pass_key ) = explode( ':', $user->user_activation_key, 2 );
2404          $expiration_time                      = $pass_request_time + $expiration_duration;
2405      } else {
2406          $pass_key        = $user->user_activation_key;
2407          $expiration_time = false;
2408      }
2409  
2410      if ( ! $pass_key ) {
2411          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
2412      }
2413  
2414      $hash_is_correct = $wp_hasher->CheckPassword( $key, $pass_key );
2415  
2416      if ( $hash_is_correct && $expiration_time && time() < $expiration_time ) {
2417          return $user;
2418      } elseif ( $hash_is_correct && $expiration_time ) {
2419          // Key has an expiration time that's passed.
2420          return new WP_Error( 'expired_key', __( 'Invalid key.' ) );
2421      }
2422  
2423      if ( hash_equals( $user->user_activation_key, $key ) || ( $hash_is_correct && ! $expiration_time ) ) {
2424          $return  = new WP_Error( 'expired_key', __( 'Invalid key.' ) );
2425          $user_id = $user->ID;
2426  
2427          /**
2428           * Filters the return value of check_password_reset_key() when an
2429           * old-style key is used.
2430           *
2431           * @since 3.7.0 Previously plain-text keys were stored in the database.
2432           * @since 4.3.0 Previously key hashes were stored without an expiration time.
2433           *
2434           * @param WP_Error $return  A WP_Error object denoting an expired key.
2435           *                          Return a WP_User object to validate the key.
2436           * @param int      $user_id The matched user ID.
2437           */
2438          return apply_filters( 'password_reset_key_expired', $return, $user_id );
2439      }
2440  
2441      return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
2442  }
2443  
2444  /**
2445   * Handles resetting the user's password.
2446   *
2447   * @since 2.5.0
2448   *
2449   * @param WP_User $user     The user
2450   * @param string $new_pass New password for the user in plaintext
2451   */
2452  function reset_password( $user, $new_pass ) {
2453      /**
2454       * Fires before the user's password is reset.
2455       *
2456       * @since 1.5.0
2457       *
2458       * @param WP_User $user     The user.
2459       * @param string  $new_pass New user password.
2460       */
2461      do_action( 'password_reset', $user, $new_pass );
2462  
2463      wp_set_password( $new_pass, $user->ID );
2464      update_user_option( $user->ID, 'default_password_nag', false, true );
2465  
2466      /**
2467       * Fires after the user's password is reset.
2468       *
2469       * @since 4.4.0
2470       *
2471       * @param WP_User $user     The user.
2472       * @param string  $new_pass New user password.
2473       */
2474      do_action( 'after_password_reset', $user, $new_pass );
2475  }
2476  
2477  /**
2478   * Handles registering a new user.
2479   *
2480   * @since 2.5.0
2481   *
2482   * @param string $user_login User's username for logging in
2483   * @param string $user_email User's email address to send password and add
2484   * @return int|WP_Error Either user's ID or error on failure.
2485   */
2486  function register_new_user( $user_login, $user_email ) {
2487      $errors = new WP_Error();
2488  
2489      $sanitized_user_login = sanitize_user( $user_login );
2490      /**
2491       * Filters the email address of a user being registered.
2492       *
2493       * @since 2.1.0
2494       *
2495       * @param string $user_email The email address of the new user.
2496       */
2497      $user_email = apply_filters( 'user_registration_email', $user_email );
2498  
2499      // Check the username.
2500      if ( '' == $sanitized_user_login ) {
2501          $errors->add( 'empty_username', __( '<strong>Error</strong>: Please enter a username.' ) );
2502      } elseif ( ! validate_username( $user_login ) ) {
2503          $errors->add( 'invalid_username', __( '<strong>Error</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
2504          $sanitized_user_login = '';
2505      } elseif ( username_exists( $sanitized_user_login ) ) {
2506          $errors->add( 'username_exists', __( '<strong>Error</strong>: This username is already registered. Please choose another one.' ) );
2507  
2508      } else {
2509          /** This filter is documented in wp-includes/user.php */
2510          $illegal_user_logins = (array) apply_filters( 'illegal_user_logins', array() );
2511          if ( in_array( strtolower( $sanitized_user_login ), array_map( 'strtolower', $illegal_user_logins ), true ) ) {
2512              $errors->add( 'invalid_username', __( '<strong>Error</strong>: Sorry, that username is not allowed.' ) );
2513          }
2514      }
2515  
2516      // Check the email address.
2517      if ( '' == $user_email ) {
2518          $errors->add( 'empty_email', __( '<strong>Error</strong>: Please type your email address.' ) );
2519      } elseif ( ! is_email( $user_email ) ) {
2520          $errors->add( 'invalid_email', __( '<strong>Error</strong>: The email address isn&#8217;t correct.' ) );
2521          $user_email = '';
2522      } elseif ( email_exists( $user_email ) ) {
2523          $errors->add( 'email_exists', __( '<strong>Error</strong>: This email is already registered, please choose another one.' ) );
2524      }
2525  
2526      /**
2527       * Fires when submitting registration form data, before the user is created.
2528       *
2529       * @since 2.1.0
2530       *
2531       * @param string   $sanitized_user_login The submitted username after being sanitized.
2532       * @param string   $user_email           The submitted email.
2533       * @param WP_Error $errors               Contains any errors with submitted username and email,
2534       *                                       e.g., an empty field, an invalid username or email,
2535       *                                       or an existing username or email.
2536       */
2537      do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
2538  
2539      /**
2540       * Filters the errors encountered when a new user is being registered.
2541       *
2542       * The filtered WP_Error object may, for example, contain errors for an invalid
2543       * or existing username or email address. A WP_Error object should always returned,
2544       * but may or may not contain errors.
2545       *
2546       * If any errors are present in $errors, this will abort the user's registration.
2547       *
2548       * @since 2.1.0
2549       *
2550       * @param WP_Error $errors               A WP_Error object containing any errors encountered
2551       *                                       during registration.
2552       * @param string   $sanitized_user_login User's username after it has been sanitized.
2553       * @param string   $user_email           User's email.
2554       */
2555      $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
2556  
2557      if ( $errors->has_errors() ) {
2558          return $errors;
2559      }
2560  
2561      $user_pass = wp_generate_password( 12, false );
2562      $user_id   = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
2563      if ( ! $user_id || is_wp_error( $user_id ) ) {
2564          $errors->add(
2565              'registerfail',
2566              sprintf(
2567                  /* translators: %s: Admin email address. */
2568                  __( '<strong>Error</strong>: Couldn&#8217;t register you&hellip; please contact the <a href="mailto:%s">webmaster</a> !' ),
2569                  get_option( 'admin_email' )
2570              )
2571          );
2572          return $errors;
2573      }
2574  
2575      update_user_option( $user_id, 'default_password_nag', true, true ); // Set up the password change nag.
2576  
2577      /**
2578       * Fires after a new user registration has been recorded.
2579       *
2580       * @since 4.4.0
2581       *
2582       * @param int $user_id ID of the newly registered user.
2583       */
2584      do_action( 'register_new_user', $user_id );
2585  
2586      return $user_id;
2587  }
2588  
2589  /**
2590   * Initiates email notifications related to the creation of new users.
2591   *
2592   * Notifications are sent both to the site admin and to the newly created user.
2593   *
2594   * @since 4.4.0
2595   * @since 4.6.0 Converted the `$notify` parameter to accept 'user' for sending
2596   *              notifications only to the user created.
2597   *
2598   * @param int    $user_id ID of the newly created user.
2599   * @param string $notify  Optional. Type of notification that should happen. Accepts 'admin'
2600   *                        or an empty string (admin only), 'user', or 'both' (admin and user).
2601   *                        Default 'both'.
2602   */
2603  function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {
2604      wp_new_user_notification( $user_id, null, $notify );
2605  }
2606  
2607  /**
2608   * Retrieve the current session token from the logged_in cookie.
2609   *
2610   * @since 4.0.0
2611   *
2612   * @return string Token.
2613   */
2614  function wp_get_session_token() {
2615      $cookie = wp_parse_auth_cookie( '', 'logged_in' );
2616      return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
2617  }
2618  
2619  /**
2620   * Retrieve a list of sessions for the current user.
2621   *
2622   * @since 4.0.0
2623   * @return array Array of sessions.
2624   */
2625  function wp_get_all_sessions() {
2626      $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
2627      return $manager->get_all();
2628  }
2629  
2630  /**
2631   * Remove the current session token from the database.
2632   *
2633   * @since 4.0.0
2634   */
2635  function wp_destroy_current_session() {
2636      $token = wp_get_session_token();
2637      if ( $token ) {
2638          $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
2639          $manager->destroy( $token );
2640      }
2641  }
2642  
2643  /**
2644   * Remove all but the current session token for the current user for the database.
2645   *
2646   * @since 4.0.0
2647   */
2648  function wp_destroy_other_sessions() {
2649      $token = wp_get_session_token();
2650      if ( $token ) {
2651          $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
2652          $manager->destroy_others( $token );
2653      }
2654  }
2655  
2656  /**
2657   * Remove all session tokens for the current user from the database.
2658   *
2659   * @since 4.0.0
2660   */
2661  function wp_destroy_all_sessions() {
2662      $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
2663      $manager->destroy_all();
2664  }
2665  
2666  /**
2667   * Get the user IDs of all users with no role on this site.
2668   *
2669   * @since 4.4.0
2670   * @since 4.9.0 The `$site_id` parameter was added to support multisite.
2671   *
2672   * @param int|null $site_id Optional. The site ID to get users with no role for. Defaults to the current site.
2673   * @return string[] Array of user IDs as strings.
2674   */
2675  function wp_get_users_with_no_role( $site_id = null ) {
2676      global $wpdb;
2677  
2678      if ( ! $site_id ) {
2679          $site_id = get_current_blog_id();
2680      }
2681  
2682      $prefix = $wpdb->get_blog_prefix( $site_id );
2683  
2684      if ( is_multisite() && get_current_blog_id() != $site_id ) {
2685          switch_to_blog( $site_id );
2686          $role_names = wp_roles()->get_names();
2687          restore_current_blog();
2688      } else {
2689          $role_names = wp_roles()->get_names();
2690      }
2691  
2692      $regex = implode( '|', array_keys( $role_names ) );
2693      $regex = preg_replace( '/[^a-zA-Z_\|-]/', '', $regex );
2694      $users = $wpdb->get_col(
2695          $wpdb->prepare(
2696              "
2697          SELECT user_id
2698          FROM $wpdb->usermeta
2699          WHERE meta_key = '{$prefix}capabilities'
2700          AND meta_value NOT REGEXP %s
2701      ",
2702              $regex
2703          )
2704      );
2705  
2706      return $users;
2707  }
2708  
2709  /**
2710   * Retrieves the current user object.
2711   *
2712   * Will set the current user, if the current user is not set. The current user
2713   * will be set to the logged-in person. If no user is logged-in, then it will
2714   * set the current user to 0, which is invalid and won't have any permissions.
2715   *
2716   * This function is used by the pluggable functions wp_get_current_user() and
2717   * get_currentuserinfo(), the latter of which is deprecated but used for backward
2718   * compatibility.
2719   *
2720   * @since 4.5.0
2721   * @access private
2722   *
2723   * @see wp_get_current_user()
2724   * @global WP_User $current_user Checks if the current user is set.
2725   *
2726   * @return WP_User Current WP_User instance.
2727   */
2728  function _wp_get_current_user() {
2729      global $current_user;
2730  
2731      if ( ! empty( $current_user ) ) {
2732          if ( $current_user instanceof WP_User ) {
2733              return $current_user;
2734          }
2735  
2736          // Upgrade stdClass to WP_User.
2737          if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
2738              $cur_id       = $current_user->ID;
2739              $current_user = null;
2740              wp_set_current_user( $cur_id );
2741              return $current_user;
2742          }
2743  
2744          // $current_user has a junk value. Force to WP_User with ID 0.
2745          $current_user = null;
2746          wp_set_current_user( 0 );
2747          return $current_user;
2748      }
2749  
2750      if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
2751          wp_set_current_user( 0 );
2752          return $current_user;
2753      }
2754  
2755      /**
2756       * Filters the current user.
2757       *
2758       * The default filters use this to determine the current user from the
2759       * request's cookies, if available.
2760       *
2761       * Returning a value of false will effectively short-circuit setting
2762       * the current user.
2763       *
2764       * @since 3.9.0
2765       *
2766       * @param int|bool $user_id User ID if one has been determined, false otherwise.
2767       */
2768      $user_id = apply_filters( 'determine_current_user', false );
2769      if ( ! $user_id ) {
2770          wp_set_current_user( 0 );
2771          return $current_user;
2772      }
2773  
2774      wp_set_current_user( $user_id );
2775  
2776      return $current_user;
2777  }
2778  
2779  /**
2780   * Send a confirmation request email when a change of user email address is attempted.
2781   *
2782   * @since 3.0.0
2783   * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
2784   *
2785   * @global WP_Error $errors WP_Error object.
2786   */
2787  function send_confirmation_on_profile_email() {
2788      global $errors;
2789  
2790      $current_user = wp_get_current_user();
2791      if ( ! is_object( $errors ) ) {
2792          $errors = new WP_Error();
2793      }
2794  
2795      if ( $current_user->ID != $_POST['user_id'] ) {
2796          return false;
2797      }
2798  
2799      if ( $current_user->user_email != $_POST['email'] ) {
2800          if ( ! is_email( $_POST['email'] ) ) {
2801              $errors->add(
2802                  'user_email',
2803                  __( '<strong>Error</strong>: The email address isn&#8217;t correct.' ),
2804                  array(
2805                      'form-field' => 'email',
2806                  )
2807              );
2808  
2809              return;
2810          }
2811  
2812          if ( email_exists( $_POST['email'] ) ) {
2813              $errors->add(
2814                  'user_email',
2815                  __( '<strong>Error</strong>: The email address is already used.' ),
2816                  array(
2817                      'form-field' => 'email',
2818                  )
2819              );
2820              delete_user_meta( $current_user->ID, '_new_email' );
2821  
2822              return;
2823          }
2824  
2825          $hash           = md5( $_POST['email'] . time() . wp_rand() );
2826          $new_user_email = array(
2827              'hash'     => $hash,
2828              'newemail' => $_POST['email'],
2829          );
2830          update_user_meta( $current_user->ID, '_new_email', $new_user_email );
2831  
2832          $sitename = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
2833  
2834          /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */
2835          $email_text = __(
2836              'Howdy ###USERNAME###,
2837  
2838  You recently requested to have the email address on your account changed.
2839  
2840  If this is correct, please click on the following link to change it:
2841  ###ADMIN_URL###
2842  
2843  You can safely ignore and delete this email if you do not want to
2844  take this action.
2845  
2846  This email has been sent to ###EMAIL###
2847  
2848  Regards,
2849  All at ###SITENAME###
2850  ###SITEURL###'
2851          );
2852  
2853          /**
2854           * Filters the text of the email sent when a change of user email address is attempted.
2855           *
2856           * The following strings have a special meaning and will get replaced dynamically:
2857           * ###USERNAME###  The current user's username.
2858           * ###ADMIN_URL### The link to click on to confirm the email change.
2859           * ###EMAIL###     The new email.
2860           * ###SITENAME###  The name of the site.
2861           * ###SITEURL###   The URL to the site.
2862           *
2863           * @since MU (3.0.0)
2864           * @since 4.9.0 This filter is no longer Multisite specific.
2865           *
2866           * @param string $email_text     Text in the email.
2867           * @param array  $new_user_email {
2868           *     Data relating to the new user email address.
2869           *
2870           *     @type string $hash     The secure hash used in the confirmation link URL.
2871           *     @type string $newemail The proposed new email address.
2872           * }
2873           */
2874          $content = apply_filters( 'new_user_email_content', $email_text, $new_user_email );
2875  
2876          $content = str_replace( '###USERNAME###', $current_user->user_login, $content );
2877          $content = str_replace( '###ADMIN_URL###', esc_url( admin_url( 'profile.php?newuseremail=' . $hash ) ), $content );
2878          $content = str_replace( '###EMAIL###', $_POST['email'], $content );
2879          $content = str_replace( '###SITENAME###', $sitename, $content );
2880          $content = str_replace( '###SITEURL###', home_url(), $content );
2881  
2882          /* translators: New email address notification email subject. %s: Site title. */
2883          wp_mail( $_POST['email'], sprintf( __( '[%s] Email Change Request' ), $sitename ), $content );
2884  
2885          $_POST['email'] = $current_user->user_email;
2886      }
2887  }
2888  
2889  /**
2890   * Adds an admin notice alerting the user to check for confirmation request email
2891   * after email address change.
2892   *
2893   * @since 3.0.0
2894   * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
2895   *
2896   * @global string $pagenow
2897   */
2898  function new_user_email_admin_notice() {
2899      global $pagenow;
2900  
2901      if ( 'profile.php' === $pagenow && isset( $_GET['updated'] ) ) {
2902          $email = get_user_meta( get_current_user_id(), '_new_email', true );
2903          if ( $email ) {
2904              /* translators: %s: New email address. */
2905              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>';
2906          }
2907      }
2908  }
2909  
2910  /**
2911   * Get all user privacy request types.
2912   *
2913   * @since 4.9.6
2914   * @access private
2915   *
2916   * @return array List of core privacy action types.
2917   */
2918  function _wp_privacy_action_request_types() {
2919      return array(
2920          'export_personal_data',
2921          'remove_personal_data',
2922      );
2923  }
2924  
2925  /**
2926   * Registers the personal data exporter for users.
2927   *
2928   * @since 4.9.6
2929   *
2930   * @param array $exporters  An array of personal data exporters.
2931   * @return array An array of personal data exporters.
2932   */
2933  function wp_register_user_personal_data_exporter( $exporters ) {
2934      $exporters['wordpress-user'] = array(
2935          'exporter_friendly_name' => __( 'WordPress User' ),
2936          'callback'               => 'wp_user_personal_data_exporter',
2937      );
2938  
2939      return $exporters;
2940  }
2941  
2942  /**
2943   * Finds and exports personal data associated with an email address from the user and user_meta table.
2944   *
2945   * @since 4.9.6
2946   * @since 5.4.0 Added 'Community Events Location' group to the export data.
2947   * @since 5.4.0 Added 'Session Tokens' group to the export data.
2948   *
2949   * @param string $email_address  The user's email address.
2950   * @return array An array of personal data.
2951   */
2952  function wp_user_personal_data_exporter( $email_address ) {
2953      $email_address = trim( $email_address );
2954  
2955      $data_to_export = array();
2956  
2957      $user = get_user_by( 'email', $email_address );
2958  
2959      if ( ! $user ) {
2960          return array(
2961              'data' => array(),
2962              'done' => true,
2963          );
2964      }
2965  
2966      $user_meta = get_user_meta( $user->ID );
2967  
2968      $user_props_to_export = array(
2969          'ID'              => __( 'User ID' ),
2970          'user_login'      => __( 'User Login Name' ),
2971          'user_nicename'   => __( 'User Nice Name' ),
2972          'user_email'      => __( 'User Email' ),
2973          'user_url'        => __( 'User URL' ),
2974          'user_registered' => __( 'User Registration Date' ),
2975          'display_name'    => __( 'User Display Name' ),
2976          'nickname'        => __( 'User Nickname' ),
2977          'first_name'      => __( 'User First Name' ),
2978          'last_name'       => __( 'User Last Name' ),
2979          'description'     => __( 'User Description' ),
2980      );
2981  
2982      $user_data_to_export = array();
2983  
2984      foreach ( $user_props_to_export as $key => $name ) {
2985          $value = '';
2986  
2987          switch ( $key ) {
2988              case 'ID':
2989              case 'user_login':
2990              case 'user_nicename':
2991              case 'user_email':
2992              case 'user_url':
2993              case 'user_registered':
2994              case 'display_name':
2995                  $value = $user->data->$key;
2996                  break;
2997              case 'nickname':
2998              case 'first_name':
2999              case 'last_name':
3000              case 'description':
3001                  $value = $user_meta[ $key ][0];
3002                  break;
3003          }
3004  
3005          if ( ! empty( $value ) ) {
3006              $user_data_to_export[] = array(
3007                  'name'  => $name,
3008                  'value' => $value,
3009              );
3010          }
3011      }
3012  
3013      // Get the list of reserved names.
3014      $reserved_names = array_values( $user_props_to_export );
3015  
3016      /**
3017       * Filter to extend the user's profile data for the privacy exporter.
3018       *
3019       * @since 5.4.0
3020       *
3021       * @param array    $additional_user_profile_data {
3022       *     An array of name-value pairs of additional user data items. Default empty array.
3023       *
3024       *     @type string $name  The user-facing name of an item name-value pair,e.g. 'IP Address'.
3025       *     @type string $value The user-facing value of an item data pair, e.g. '50.60.70.0'.
3026       * }
3027       * @param WP_User  $user           The user whose data is being exported.
3028       * @param string[] $reserved_names An array of reserved names. Any item in `$additional_user_data`
3029       *                                 that uses one of these for its `name` will not be included in the export.
3030       */
3031      $_extra_data = apply_filters( 'wp_privacy_additional_user_profile_data', array(), $user, $reserved_names );
3032  
3033      if ( is_array( $_extra_data ) && ! empty( $_extra_data ) ) {
3034          // Remove items that use reserved names.
3035          $extra_data = array_filter(
3036              $_extra_data,
3037              function( $item ) use ( $reserved_names ) {
3038                  return ! in_array( $item['name'], $reserved_names, true );
3039              }
3040          );
3041  
3042          if ( count( $extra_data ) !== count( $_extra_data ) ) {
3043              _doing_it_wrong(
3044                  __FUNCTION__,
3045                  sprintf(
3046                      /* translators: %s: wp_privacy_additional_user_profile_data */
3047                      __( 'Filter %s returned items with reserved names.' ),
3048                      '<code>wp_privacy_additional_user_profile_data</code>'
3049                  ),
3050                  '5.4.0'
3051              );
3052          }
3053  
3054          if ( ! empty( $extra_data ) ) {
3055              $user_data_to_export = array_merge( $user_data_to_export, $extra_data );
3056          }
3057      }
3058  
3059      $data_to_export[] = array(
3060          'group_id'          => 'user',
3061          'group_label'       => __( 'User' ),
3062          'group_description' => __( 'User&#8217;s profile data.' ),
3063          'item_id'           => "user-{$user->ID}",
3064          'data'              => $user_data_to_export,
3065      );
3066  
3067      if ( isset( $user_meta['community-events-location'] ) ) {
3068          $location = maybe_unserialize( $user_meta['community-events-location'][0] );
3069  
3070          $location_props_to_export = array(
3071              'description' => __( 'City' ),
3072              'country'     => __( 'Country' ),
3073              'latitude'    => __( 'Latitude' ),
3074              'longitude'   => __( 'Longitude' ),
3075              'ip'          => __( 'IP' ),
3076          );
3077  
3078          $location_data_to_export = array();
3079  
3080          foreach ( $location_props_to_export as $key => $name ) {
3081              if ( ! empty( $location[ $key ] ) ) {
3082                  $location_data_to_export[] = array(
3083                      'name'  => $name,
3084                      'value' => $location[ $key ],
3085                  );
3086              }
3087          }
3088  
3089          $data_to_export[] = array(
3090              'group_id'          => 'community-events-location',
3091              'group_label'       => __( 'Community Events Location' ),
3092              'group_description' => __( 'User&#8217;s location data used for the Community Events in the WordPress Events and News dashboard widget.' ),
3093              'item_id'           => "community-events-location-{$user->ID}",
3094              'data'              => $location_data_to_export,
3095          );
3096      }
3097  
3098      if ( isset( $user_meta['session_tokens'] ) ) {
3099          $session_tokens = maybe_unserialize( $user_meta['session_tokens'][0] );
3100  
3101          $session_tokens_props_to_export = array(
3102              'expiration' => __( 'Expiration' ),
3103              'ip'         => __( 'IP' ),
3104              'ua'         => __( 'User Agent' ),
3105              'login'      => __( 'Last Login' ),
3106          );
3107  
3108          foreach ( $session_tokens as $token_key => $session_token ) {
3109              $session_tokens_data_to_export = array();
3110  
3111              foreach ( $session_tokens_props_to_export as $key => $name ) {
3112                  if ( ! empty( $session_token[ $key ] ) ) {
3113                      $value = $session_token[ $key ];
3114                      if ( in_array( $key, array( 'expiration', 'login' ) ) ) {
3115                          $value = date_i18n( 'F d, Y H:i A', $value );
3116                      }
3117                      $session_tokens_data_to_export[] = array(
3118                          'name'  => $name,
3119                          'value' => $value,
3120                      );
3121                  }
3122              }
3123  
3124              $data_to_export[] = array(
3125                  'group_id'          => 'session-tokens',
3126                  'group_label'       => __( 'Session Tokens' ),
3127                  'group_description' => __( 'User&#8217;s Session Tokens data.' ),
3128                  'item_id'           => "session-tokens-{$user->ID}-{$token_key}",
3129                  'data'              => $session_tokens_data_to_export,
3130              );
3131          }
3132      }
3133  
3134      return array(
3135          'data' => $data_to_export,
3136          'done' => true,
3137      );
3138  }
3139  
3140  /**
3141   * Update log when privacy request is confirmed.
3142   *
3143   * @since 4.9.6
3144   * @access private
3145   *
3146   * @param int $request_id ID of the request.
3147   */
3148  function _wp_privacy_account_request_confirmed( $request_id ) {
3149      $request = wp_get_user_request( $request_id );
3150  
3151      if ( ! $request ) {
3152          return;
3153      }
3154  
3155      if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
3156          return;
3157      }
3158  
3159      update_post_meta( $request_id, '_wp_user_request_confirmed_timestamp', time() );
3160      wp_update_post(
3161          array(
3162              'ID'          => $request_id,
3163              'post_status' => 'request-confirmed',
3164          )
3165      );
3166  }
3167  
3168  /**
3169   * Notify the site administrator via email when a request is confirmed.
3170   *
3171   * Without this, the admin would have to manually check the site to see if any
3172   * action was needed on their part yet.
3173   *
3174   * @since 4.9.6
3175   *
3176   * @param int $request_id The ID of the request.
3177   */
3178  function _wp_privacy_send_request_confirmation_notification( $request_id ) {
3179      $request = wp_get_user_request( $request_id );
3180  
3181      if ( ! is_a( $request, 'WP_User_Request' ) || 'request-confirmed' !== $request->status ) {
3182          return;
3183      }
3184  
3185      $already_notified = (bool) get_post_meta( $request_id, '_wp_admin_notified', true );
3186  
3187      if ( $already_notified ) {
3188          return;
3189      }
3190  
3191      if ( 'export_personal_data' === $request->action_name ) {
3192          $manage_url = admin_url( 'export-personal-data.php' );
3193      } elseif ( 'remove_personal_data' === $request->action_name ) {
3194          $manage_url = admin_url( 'erase-personal-data.php' );
3195      }
3196      $action_description = wp_user_request_action_description( $request->action_name );
3197  
3198      /**
3199       * Filters the recipient of the data request confirmation notification.
3200       *
3201       * In a Multisite environment, this will default to the email address of the
3202       * network admin because, by default, single site admins do not have the
3203       * capabilities required to process requests. Some networks may wish to
3204       * delegate those capabilities to a single-site admin, or a dedicated person
3205       * responsible for managing privacy requests.
3206       *
3207       * @since 4.9.6
3208       *
3209       * @param string          $admin_email The email address of the notification recipient.
3210       * @param WP_User_Request $request     The request that is initiating the notification.
3211       */
3212      $admin_email = apply_filters( 'user_request_confirmed_email_to', get_site_option( 'admin_email' ), $request );
3213  
3214      $email_data = array(
3215          'request'     => $request,
3216          'user_email'  => $request->email,
3217          'description' => $action_description,
3218          'manage_url'  => $manage_url,
3219          'sitename'    => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
3220          'siteurl'     => home_url(),
3221          'admin_email' => $admin_email,
3222      );
3223  
3224      /* translators: Do not translate SITENAME, USER_EMAIL, DESCRIPTION, MANAGE_URL, SITEURL; those are placeholders. */
3225      $email_text = __(
3226          'Howdy,
3227  
3228  A user data privacy request has been confirmed on ###SITENAME###:
3229  
3230  User: ###USER_EMAIL###
3231  Request: ###DESCRIPTION###
3232  
3233  You can view and manage these data privacy requests here:
3234  
3235  ###MANAGE_URL###
3236  
3237  Regards,
3238  All at ###SITENAME###
3239  ###SITEURL###'
3240      );
3241  
3242      /**
3243       * Filters the body of the user request confirmation email.
3244       *
3245       * The email is sent to an administrator when an user request is confirmed.
3246       * The following strings have a special meaning and will get replaced dynamically:
3247       *
3248       * ###SITENAME###    The name of the site.
3249       * ###USER_EMAIL###  The user email for the request.
3250       * ###DESCRIPTION### Description of the action being performed so the user knows what the email is for.
3251       * ###MANAGE_URL###  The URL to manage requests.
3252       * ###SITEURL###     The URL to the site.
3253       *
3254       * @since 4.9.6
3255       *
3256       * @param string $email_text Text in the email.
3257       * @param array  $email_data {
3258       *     Data relating to the account action email.
3259       *
3260       *     @type WP_User_Request $request     User request object.
3261       *     @type string          $user_email  The email address confirming a request
3262       *     @type string          $description Description of the action being performed so the user knows what the email is for.
3263       *     @type string          $manage_url  The link to click manage privacy requests of this type.
3264       *     @type string          $sitename    The site name sending the mail.
3265       *     @type string          $siteurl     The site URL sending the mail.
3266       *     @type string          $admin_email The administrator email receiving the mail.
3267       * }
3268       */
3269      $content = apply_filters( 'user_confirmed_action_email_content', $email_text, $email_data );
3270  
3271      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
3272      $content = str_replace( '###USER_EMAIL###', $email_data['user_email'], $content );
3273      $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
3274      $content = str_replace( '###MANAGE_URL###', esc_url_raw( $email_data['manage_url'] ), $content );
3275      $content = str_replace( '###SITEURL###', esc_url_raw( $email_data['siteurl'] ), $content );
3276  
3277      $subject = sprintf(
3278          /* translators: Privacy data request confirmed notification email subject. 1: Site title, 2: Name of the confirmed action. */
3279          __( '[%1$s] Action Confirmed: %2$s' ),
3280          $email_data['sitename'],
3281          $action_description
3282      );
3283  
3284      /**
3285       * Filters the subject of the user request confirmation email.
3286       *
3287       * @since 4.9.8
3288       *
3289       * @param string $subject    The email subject.
3290       * @param string $sitename   The name of the site.
3291       * @param array  $email_data {
3292       *     Data relating to the account action email.
3293       *
3294       *     @type WP_User_Request $request     User request object.
3295       *     @type string          $user_email  The email address confirming a request
3296       *     @type string          $description Description of the action being performed so the user knows what the email is for.
3297       *     @type string          $manage_url  The link to click manage privacy requests of this type.
3298       *     @type string          $sitename    The site name sending the mail.
3299       *     @type string          $siteurl     The site URL sending the mail.
3300       *     @type string          $admin_email The administrator email receiving the mail.
3301       * }
3302       */
3303      $subject = apply_filters( 'user_request_confirmed_email_subject', $subject, $email_data['sitename'], $email_data );
3304  
3305      $headers = '';
3306  
3307      /**
3308       * Filters the headers of the user request confirmation email.
3309       *
3310       * @since 5.4.0
3311       *
3312       * @param string|array $headers    The email headers.
3313       * @param string       $subject    The email subject.
3314       * @param string       $content    The email content.
3315       * @param int          $request_id The request ID.
3316       * @param array        $email_data {
3317       *     Data relating to the account action email.
3318       *
3319       *     @type WP_User_Request $request     User request object.
3320       *     @type string          $user_email  The email address confirming a request
3321       *     @type string          $description Description of the action being performed so the user knows what the email is for.
3322       *     @type string          $manage_url  The link to click manage privacy requests of this type.
3323       *     @type string          $sitename    The site name sending the mail.
3324       *     @type string          $siteurl     The site URL sending the mail.
3325       *     @type string          $admin_email The administrator email receiving the mail.
3326       * }
3327       */
3328      $headers = apply_filters( 'user_request_confirmed_email_headers', $headers, $subject, $content, $request_id, $email_data );
3329  
3330      $email_sent = wp_mail( $email_data['admin_email'], $subject, $content, $headers );
3331  
3332      if ( $email_sent ) {
3333          update_post_meta( $request_id, '_wp_admin_notified', true );
3334      }
3335  }
3336  
3337  /**
3338   * Notify the user when their erasure request is fulfilled.
3339   *
3340   * Without this, the user would never know if their data was actually erased.
3341   *
3342   * @since 4.9.6
3343   *
3344   * @param int $request_id The privacy request post ID associated with this request.
3345   */
3346  function _wp_privacy_send_erasure_fulfillment_notification( $request_id ) {
3347      $request = wp_get_user_request( $request_id );
3348  
3349      if ( ! is_a( $request, 'WP_User_Request' ) || 'request-completed' !== $request->status ) {
3350          return;
3351      }
3352  
3353      $already_notified = (bool) get_post_meta( $request_id, '_wp_user_notified', true );
3354  
3355      if ( $already_notified ) {
3356          return;
3357      }
3358  
3359      // Localize message content for user; fallback to site default for visitors.
3360      if ( ! empty( $request->user_id ) ) {
3361          $locale = get_user_locale( $request->user_id );
3362      } else {
3363          $locale = get_locale();
3364      }
3365  
3366      $switched_locale = switch_to_locale( $locale );
3367  
3368      /**
3369       * Filters the recipient of the data erasure fulfillment notification.
3370       *
3371       * @since 4.9.6
3372       *
3373       * @param string          $user_email The email address of the notification recipient.
3374       * @param WP_User_Request $request    The request that is initiating the notification.
3375       */
3376      $user_email = apply_filters( 'user_erasure_fulfillment_email_to', $request->email, $request );
3377  
3378      $email_data = array(
3379          'request'            => $request,
3380          'message_recipient'  => $user_email,
3381          'privacy_policy_url' => get_privacy_policy_url(),
3382          'sitename'           => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
3383          'siteurl'            => home_url(),
3384      );
3385  
3386      $subject = sprintf(
3387          /* translators: Erasure request fulfilled notification email subject. %s: Site title. */
3388          __( '[%s] Erasure Request Fulfilled' ),
3389          $email_data['sitename']
3390      );
3391  
3392      /**
3393       * Filters the subject of the email sent when an erasure request is completed.
3394       *
3395       * @since 4.9.8
3396       *
3397       * @param string $subject    The email subject.
3398       * @param string $sitename   The name of the site.
3399       * @param array  $email_data {
3400       *     Data relating to the account action email.
3401       *
3402       *     @type WP_User_Request $request            User request object.
3403       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
3404       *                                               to the value of `$request->email`, but can be changed
3405       *                                               by the `user_erasure_fulfillment_email_to` filter.
3406       *     @type string          $privacy_policy_url Privacy policy URL.
3407       *     @type string          $sitename           The site name sending the mail.
3408       *     @type string          $siteurl            The site URL sending the mail.
3409       * }
3410       */
3411      $subject = apply_filters( 'user_erasure_complete_email_subject', $subject, $email_data['sitename'], $email_data );
3412  
3413      if ( empty( $email_data['privacy_policy_url'] ) ) {
3414          /* translators: Do not translate SITENAME, SITEURL; those are placeholders. */
3415          $email_text = __(
3416              'Howdy,
3417  
3418  Your request to erase your personal data on ###SITENAME### has been completed.
3419  
3420  If you have any follow-up questions or concerns, please contact the site administrator.
3421  
3422  Regards,
3423  All at ###SITENAME###
3424  ###SITEURL###'
3425          );
3426      } else {
3427          /* translators: Do not translate SITENAME, SITEURL, PRIVACY_POLICY_URL; those are placeholders. */
3428          $email_text = __(
3429              'Howdy,
3430  
3431  Your request to erase your personal data on ###SITENAME### has been completed.
3432  
3433  If you have any follow-up questions or concerns, please contact the site administrator.
3434  
3435  For more information, you can also read our privacy policy: ###PRIVACY_POLICY_URL###
3436  
3437  Regards,
3438  All at ###SITENAME###
3439  ###SITEURL###'
3440          );
3441      }
3442  
3443      /**
3444       * Filters the body of the data erasure fulfillment notification.
3445       *
3446       * The email is sent to a user when a their data erasure request is fulfilled
3447       * by an administrator.
3448       *
3449       * The following strings have a special meaning and will get replaced dynamically:
3450       *
3451       * ###SITENAME###           The name of the site.
3452       * ###PRIVACY_POLICY_URL### Privacy policy page URL.
3453       * ###SITEURL###            The URL to the site.
3454       *
3455       * @since 4.9.6
3456       *
3457       * @param string $email_text Text in the email.
3458       * @param array  $email_data {
3459       *     Data relating to the account action email.
3460       *
3461       *     @type WP_User_Request $request            User request object.
3462       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
3463       *                                               to the value of `$request->email`, but can be changed
3464       *                                               by the `user_erasure_fulfillment_email_to` filter.
3465       *     @type string          $privacy_policy_url Privacy policy URL.
3466       *     @type string          $sitename           The site name sending the mail.
3467       *     @type string          $siteurl            The site URL sending the mail.
3468       * }
3469       */
3470      $content = apply_filters( 'user_confirmed_action_email_content', $email_text, $email_data );
3471  
3472      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
3473      $content = str_replace( '###PRIVACY_POLICY_URL###', $email_data['privacy_policy_url'], $content );
3474      $content = str_replace( '###SITEURL###', esc_url_raw( $email_data['siteurl'] ), $content );
3475  
3476      $headers = '';
3477  
3478      /**
3479       * Filters the headers of the data erasure fulfillment notification.
3480       *
3481       * @since 5.4.0
3482       *
3483       * @param string|array $headers    The email headers.
3484       * @param string       $subject    The email subject.
3485       * @param string       $content    The email content.
3486       * @param int          $request_id The request ID.
3487       * @param array        $email_data {
3488       *     Data relating to the account action email.
3489       *
3490       *     @type WP_User_Request $request            User request object.
3491       *     @type string          $message_recipient  The address that the email will be sent to. Defaults
3492       *                                               to the value of `$request->email`, but can be changed
3493       *                                               by the `user_erasure_fulfillment_email_to` filter.
3494       *     @type string          $privacy_policy_url Privacy policy URL.
3495       *     @type string          $sitename           The site name sending the mail.
3496       *     @type string          $siteurl            The site URL sending the mail.
3497       * }
3498       */
3499      $headers = apply_filters( 'user_erasure_complete_email_headers', $headers, $subject, $content, $request_id, $email_data );
3500  
3501      $email_sent = wp_mail( $user_email, $subject, $content, $headers );
3502  
3503      if ( $switched_locale ) {
3504          restore_previous_locale();
3505      }
3506  
3507      if ( $email_sent ) {
3508          update_post_meta( $request_id, '_wp_user_notified', true );
3509      }
3510  }
3511  
3512  /**
3513   * Return request confirmation message HTML.
3514   *
3515   * @since 4.9.6
3516   * @access private
3517   *
3518   * @param int $request_id The request ID being confirmed.
3519   * @return string $message The confirmation message.
3520   */
3521  function _wp_privacy_account_request_confirmed_message( $request_id ) {
3522      $request = wp_get_user_request( $request_id );
3523  
3524      $message  = '<p class="success">' . __( 'Action has been confirmed.' ) . '</p>';
3525      $message .= '<p>' . __( 'The site administrator has been notified and will fulfill your request as soon as possible.' ) . '</p>';
3526  
3527      if ( $request && in_array( $request->action_name, _wp_privacy_action_request_types(), true ) ) {
3528          if ( 'export_personal_data' === $request->action_name ) {
3529              $message  = '<p class="success">' . __( 'Thanks for confirming your export request.' ) . '</p>';
3530              $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>';
3531          } elseif ( 'remove_personal_data' === $request->action_name ) {
3532              $message  = '<p class="success">' . __( 'Thanks for confirming your erasure request.' ) . '</p>';
3533              $message .= '<p>' . __( 'The site administrator has been notified. You will receive an email confirmation when they erase your data.' ) . '</p>';
3534          }
3535      }
3536  
3537      /**
3538       * Filters the message displayed to a user when they confirm a data request.
3539       *
3540       * @since 4.9.6
3541       *
3542       * @param string $message    The message to the user.
3543       * @param int    $request_id The ID of the request being confirmed.
3544       */
3545      $message = apply_filters( 'user_request_action_confirmed_message', $message, $request_id );
3546  
3547      return $message;
3548  }
3549  
3550  /**
3551   * Create and log a user request to perform a specific action.
3552   *
3553   * Requests are stored inside a post type named `user_request` since they can apply to both
3554   * users on the site, or guests without a user account.
3555   *
3556   * @since 4.9.6
3557   *
3558   * @param string $email_address User email address. This can be the address of a registered or non-registered user.
3559   * @param string $action_name   Name of the action that is being confirmed. Required.
3560   * @param array  $request_data  Misc data you want to send with the verification request and pass to the actions once the request is confirmed.
3561   * @return int|WP_Error Returns the request ID if successful, or a WP_Error object on failure.
3562   */
3563  function wp_create_user_request( $email_address = '', $action_name = '', $request_data = array() ) {
3564      $email_address = sanitize_email( $email_address );
3565      $action_name   = sanitize_key( $action_name );
3566  
3567      if ( ! is_email( $email_address ) ) {
3568          return new WP_Error( 'invalid_email', __( 'Invalid email address.' ) );
3569      }
3570  
3571      if ( ! $action_name ) {
3572          return new WP_Error( 'invalid_action', __( 'Invalid action name.' ) );
3573      }
3574  
3575      $user    = get_user_by( 'email', $email_address );
3576      $user_id = $user && ! is_wp_error( $user ) ? $user->ID : 0;
3577  
3578      // Check for duplicates.
3579      $requests_query = new WP_Query(
3580          array(
3581              'post_type'     => 'user_request',
3582              'post_name__in' => array( $action_name ), // Action name stored in post_name column.
3583              'title'         => $email_address,        // Email address stored in post_title column.
3584              'post_status'   => array(
3585                  'request-pending',
3586                  'request-confirmed',
3587              ),
3588              'fields'        => 'ids',
3589          )
3590      );
3591  
3592      if ( $requests_query->found_posts ) {
3593          return new WP_Error( 'duplicate_request', __( 'An incomplete request for this email address already exists.' ) );
3594      }
3595  
3596      $request_id = wp_insert_post(
3597          array(
3598              'post_author'   => $user_id,
3599              'post_name'     => $action_name,
3600              'post_title'    => $email_address,
3601              'post_content'  => wp_json_encode( $request_data ),
3602              'post_status'   => 'request-pending',
3603              'post_type'     => 'user_request',
3604              'post_date'     => current_time( 'mysql', false ),
3605              'post_date_gmt' => current_time( 'mysql', true ),
3606          ),
3607          true
3608      );
3609  
3610      return $request_id;
3611  }
3612  
3613  /**
3614   * Get action description from the name and return a string.
3615   *
3616   * @since 4.9.6
3617   *
3618   * @param string $action_name Action name of the request.
3619   * @return string Human readable action name.
3620   */
3621  function wp_user_request_action_description( $action_name ) {
3622      switch ( $action_name ) {
3623          case 'export_personal_data':
3624              $description = __( 'Export Personal Data' );
3625              break;
3626          case 'remove_personal_data':
3627              $description = __( 'Erase Personal Data' );
3628              break;
3629          default:
3630              /* translators: %s: Action name. */
3631              $description = sprintf( __( 'Confirm the "%s" action' ), $action_name );
3632              break;
3633      }
3634  
3635      /**
3636       * Filters the user action description.
3637       *
3638       * @since 4.9.6
3639       *
3640       * @param string $description The default description.
3641       * @param string $action_name The name of the request.
3642       */
3643      return apply_filters( 'user_request_action_description', $description, $action_name );
3644  }
3645  
3646  /**
3647   * Send a confirmation request email to confirm an action.
3648   *
3649   * If the request is not already pending, it will be updated.
3650   *
3651   * @since 4.9.6
3652   *
3653   * @param string $request_id ID of the request created via wp_create_user_request().
3654   * @return bool|WP_Error True on success, `WP_Error` on failure.
3655   */
3656  function wp_send_user_request( $request_id ) {
3657      $request_id = absint( $request_id );
3658      $request    = wp_get_user_request( $request_id );
3659  
3660      if ( ! $request ) {
3661          return new WP_Error( 'invalid_request', __( 'Invalid user request.' ) );
3662      }
3663  
3664      // Localize message content for user; fallback to site default for visitors.
3665      if ( ! empty( $request->user_id ) ) {
3666          $locale = get_user_locale( $request->user_id );
3667      } else {
3668          $locale = get_locale();
3669      }
3670  
3671      $switched_locale = switch_to_locale( $locale );
3672  
3673      $email_data = array(
3674          'request'     => $request,
3675          'email'       => $request->email,
3676          'description' => wp_user_request_action_description( $request->action_name ),
3677          'confirm_url' => add_query_arg(
3678              array(
3679                  'action'      => 'confirmaction',
3680                  'request_id'  => $request_id,
3681                  'confirm_key' => wp_generate_user_request_key( $request_id ),
3682              ),
3683              wp_login_url()
3684          ),
3685          'sitename'    => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
3686          'siteurl'     => home_url(),
3687      );
3688  
3689      /* translators: Do not translate DESCRIPTION, CONFIRM_URL, SITENAME, SITEURL: those are placeholders. */
3690      $email_text = __(
3691          'Howdy,
3692  
3693  A request has been made to perform the following action on your account:
3694  
3695       ###DESCRIPTION###
3696  
3697  To confirm this, please click on the following link:
3698  ###CONFIRM_URL###
3699  
3700  You can safely ignore and delete this email if you do not want to
3701  take this action.
3702  
3703  Regards,
3704  All at ###SITENAME###
3705  ###SITEURL###'
3706      );
3707  
3708      /**
3709       * Filters the text of the email sent when an account action is attempted.
3710       *
3711       * The following strings have a special meaning and will get replaced dynamically:
3712       *
3713       * ###DESCRIPTION### Description of the action being performed so the user knows what the email is for.
3714       * ###CONFIRM_URL### The link to click on to confirm the account action.
3715       * ###SITENAME###    The name of the site.
3716       * ###SITEURL###     The URL to the site.
3717       *
3718       * @since 4.9.6
3719       *
3720       * @param string $email_text Text in the email.
3721       * @param array  $email_data {
3722       *     Data relating to the account action email.
3723       *
3724       *     @type WP_User_Request $request     User request object.
3725       *     @type string          $email       The email address this is being sent to.
3726       *     @type string          $description Description of the action being performed so the user knows what the email is for.
3727       *     @type string          $confirm_url The link to click on to confirm the account action.
3728       *     @type string          $sitename    The site name sending the mail.
3729       *     @type string          $siteurl     The site URL sending the mail.
3730       * }
3731       */
3732      $content = apply_filters( 'user_request_action_email_content', $email_text, $email_data );
3733  
3734      $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
3735      $content = str_replace( '###CONFIRM_URL###', esc_url_raw( $email_data['confirm_url'] ), $content );
3736      $content = str_replace( '###EMAIL###', $email_data['email'], $content );
3737      $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
3738      $content = str_replace( '###SITEURL###', esc_url_raw( $email_data['siteurl'] ), $content );
3739  
3740      /* translators: Confirm privacy data request notification email subject. 1: Site title, 2: Name of the action. */
3741      $subject = sprintf( __( '[%1$s] Confirm Action: %2$s' ), $email_data['sitename'], $email_data['description'] );
3742  
3743      /**
3744       * Filters the subject of the email sent when an account action is attempted.
3745       *
3746       * @since 4.9.6
3747       *
3748       * @param string $subject    The email subject.
3749       * @param string $sitename   The name of the site.
3750       * @param array  $email_data {
3751       *     Data relating to the account action email.
3752       *
3753       *     @type WP_User_Request $request     User request object.
3754       *     @type string          $email       The email address this is being sent to.
3755       *     @type string          $description Description of the action being performed so the user knows what the email is for.
3756       *     @type string          $confirm_url The link to click on to confirm the account action.
3757       *     @type string          $sitename    The site name sending the mail.
3758       *     @type string          $siteurl     The site URL sending the mail.
3759       * }
3760       */
3761      $subject = apply_filters( 'user_request_action_email_subject', $subject, $email_data['sitename'], $email_data );
3762  
3763      $headers = '';
3764  
3765      /**
3766       * Filters the headers of the email sent when an account action is attempted.
3767       *
3768       * @since 5.4.0
3769       *
3770       * @param string|array $headers    The email headers.
3771       * @param string       $subject    The email subject.
3772       * @param string       $content    The email content.
3773       * @param int          $request_id The request ID.
3774       * @param array        $email_data {
3775       *     Data relating to the account action email.
3776       *
3777       *     @type WP_User_Request $request     User request object.
3778       *     @type string          $email       The email address this is being sent to.
3779       *     @type string          $description Description of the action being performed so the user knows what the email is for.
3780       *     @type string          $confirm_url The link to click on to confirm the account action.
3781       *     @type string          $sitename    The site name sending the mail.
3782       *     @type string          $siteurl     The site URL sending the mail.
3783       * }
3784       */
3785      $headers = apply_filters( 'user_request_action_email_headers', $headers, $subject, $content, $request_id, $email_data );
3786  
3787      $email_sent = wp_mail( $email_data['email'], $subject, $content, $headers );
3788  
3789      if ( $switched_locale ) {
3790          restore_previous_locale();
3791      }
3792  
3793      if ( ! $email_sent ) {
3794          return new WP_Error( 'privacy_email_error', __( 'Unable to send personal data export confirmation email.' ) );
3795      }
3796  
3797      return true;
3798  }
3799  
3800  /**
3801   * Returns a confirmation key for a user action and stores the hashed version for future comparison.
3802   *
3803   * @since 4.9.6
3804   *
3805   * @param int $request_id Request ID.
3806   * @return string Confirmation key.
3807   */
3808  function wp_generate_user_request_key( $request_id ) {
3809      global $wp_hasher;
3810  
3811      // Generate something random for a confirmation key.
3812      $key = wp_generate_password( 20, false );
3813  
3814      // Return the key, hashed.
3815      if ( empty( $wp_hasher ) ) {
3816          require_once  ABSPATH . WPINC . '/class-phpass.php';
3817          $wp_hasher = new PasswordHash( 8, true );
3818      }
3819  
3820      wp_update_post(
3821          array(
3822              'ID'            => $request_id,
3823              'post_status'   => 'request-pending',
3824              'post_password' => $wp_hasher->HashPassword( $key ),
3825          )
3826      );
3827  
3828      return $key;
3829  }
3830  
3831  /**
3832   * Validate a user request by comparing the key with the request's key.
3833   *
3834   * @since 4.9.6
3835   *
3836   * @param string $request_id ID of the request being confirmed.
3837   * @param string $key        Provided key to validate.
3838   * @return bool|WP_Error True on success, WP_Error on failure.
3839   */
3840  function wp_validate_user_request_key( $request_id, $key ) {
3841      global $wp_hasher;
3842  
3843      $request_id = absint( $request_id );
3844      $request    = wp_get_user_request( $request_id );
3845  
3846      if ( ! $request ) {
3847          return new WP_Error( 'invalid_request', __( 'Invalid request.' ) );
3848      }
3849  
3850      if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
3851          return new WP_Error( 'expired_link', __( 'This link has expired.' ) );
3852      }
3853  
3854      if ( empty( $key ) ) {
3855          return new WP_Error( 'missing_key', __( 'Missing confirm key.' ) );
3856      }
3857  
3858      if ( empty( $wp_hasher ) ) {
3859          require_once  ABSPATH . WPINC . '/class-phpass.php';
3860          $wp_hasher = new PasswordHash( 8, true );
3861      }
3862  
3863      $key_request_time = $request->modified_timestamp;
3864      $saved_key        = $request->confirm_key;
3865  
3866      if ( ! $saved_key ) {
3867          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3868      }
3869  
3870      if ( ! $key_request_time ) {
3871          return new WP_Error( 'invalid_key', __( 'Invalid action.' ) );
3872      }
3873  
3874      /**
3875       * Filters the expiration time of confirm keys.
3876       *
3877       * @since 4.9.6
3878       *
3879       * @param int $expiration The expiration time in seconds.
3880       */
3881      $expiration_duration = (int) apply_filters( 'user_request_key_expiration', DAY_IN_SECONDS );
3882      $expiration_time     = $key_request_time + $expiration_duration;
3883  
3884      if ( ! $wp_hasher->CheckPassword( $key, $saved_key ) ) {
3885          return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
3886      }
3887  
3888      if ( ! $expiration_time || time() > $expiration_time ) {
3889          return new WP_Error( 'expired_key', __( 'The confirmation email has expired.' ) );
3890      }
3891  
3892      return true;
3893  }
3894  
3895  /**
3896   * Return the user request object for the specified request ID.
3897   *
3898   * @since 4.9.6
3899   *
3900   * @param int $request_id The ID of the user request.
3901   * @return WP_User_Request|false
3902   */
3903  function wp_get_user_request( $request_id ) {
3904      $request_id = absint( $request_id );
3905      $post       = get_post( $request_id );
3906  
3907      if ( ! $post || 'user_request' !== $post->post_type ) {
3908          return false;
3909      }
3910  
3911      return new WP_User_Request( $post );
3912  }


Generated: Tue May 19 15:51:04 2020 Cross-referenced by PHPXref 0.7.1