[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Wed Aug 12 01:00:03 2020 Cross-referenced by PHPXref 0.7.1