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


Generated: Fri Oct 30 01:00:03 2020 Cross-referenced by PHPXref 0.7.1