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


Generated: Sun May 31 01:00:03 2020 Cross-referenced by PHPXref 0.7.1